This is my admin class, DB class and how I use OOP.
I am looking for ways to improve my code to make better use of OOP. Please help me if you think I can improve my code in some way.
db.class.php
class database
{
private $conn;
private $db_name = 'profil_penduduk';
private $db_user = 'root';
private $db_pass = '';
private $db_host = 'localhost';
public function connect()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
admin.class.php
class admin
{
private $conn;
function __construct()
{
# code...
$database = new database();
$db = $database->connect();
$this->conn = $db;
}
public function runQuery($sql)
{
# code...
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
This is how I fetch the data:
index.php
$auth_admin = new admin();
$admin_id = $_SESSION['admin_session'];
$stmt = $auth_admin->runQuery("SELECT * FROM admin WHERE admin_id=:admin_id");
$stmt->execute(array(":admin_id"=>$admin_id));
$adminRow=$stmt->fetch(PDO::FETCH_ASSOC);
Is there a better way for me to do this? Should I use CRUD? Or should I make a function with this query:
"SELECT * FROM admin WHERE admin_id=:admin_id"
inside the admin class?
Should I also use interface in my class? I don't understand much about interfaces, either.