Hi! I'm new here
I'm following an online course where we building CMS using OOP PHP and PDO. I read some articles and watched a few youtube tutorials and to be honest, I'm pretty confused. Some of the developers suggest using function __construct(PDO $connection) inside the class.
Their code looks something like that:
private PDO $connection;
function __construct(PDO $connection) {
$this->connection = $connection;
connect.php
class dbh{
private $host = "localhost";
private $user = "root";
private $pwd = "";
private $dbname = "cms";
protected function connect() {
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
$pdo = new PDO ($dsn, $this->user, $this->pwd);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
}
}
function.php // not a whole code
class CategoriesData extends dbh{
public function getAllCategories() {
$sql = "SELECT * FROM categories_tbl";
$stmt = $this->connect()->query($sql);
while ($row = $stmt->fetch()){
echo $row['category_name'] . '<br>';
}
}
public function getCategoryName() {
$sql = "SELECT category_name FROM categories_tbl";
$stmt = $this->connect()->prepare($sql);
$stmt->execute();
$category = $stmt->fetch(PDO::FETCH_OBJ);
if($category == null) {
return null;
}else {
return $category->category_name;
}
}
public function getCategoryDetials() {
$sql = "SELECT * FROM categories_tbl";
$stmt = $this->connect()->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll((PDO::FETCH_OBJ));
return $result;
}
public function addCategory ($filter_name, $filter_title, $filter_description, $filter_slug) {
$sql = "INSERT INTO categories_tbl (category_name, category_title, category_description, category_slug) VALUES (?, ?, ?, ?)";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$filter_name, $filter_title, $filter_description, $filter_slug]);
}
public function deleteCategory($delete_category_id) {
$sql = "DELETE FROM categories_tbl WHERE category_id = ?";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$delete_category_id]);
}
}
}