I have a website written with procedural PHP and now I'm re-coding it in (at least partly) OOP style so that I can start learning it. It is a simple page displaying several learning courses (title, description, etc) from a database. The admin can add or delete anything so it has to be dynamic. At first I ran a single line of code:
$courses=$pdo->run("SELECT id,title,description FROM courses WHERE status=1 ORDER BY id")->fetchAll(PDO::FETCH_CLASS, 'Course');
$cmax = count($courses);
and echoed e.g. $courses[3]->description but I felt like I'm doing nothing else but pretending OOP while just using a multidimensional array. Again, it would be ok for the purpose of the website but my question is, in order to get used to OOP logic, can I do it like this: I'm generating a dropdown menu with only the titles and IDs from the database, and after either is clicked, only then I'm creating the object (to get the description, date, teacher, whatever):
$obj = new Course($pdo,$userSelectedID);
echo $obj->getTitle($pdo);
$obj->showDetails($pdo); // etc
The class:
class Course {
protected $id;
protected $title;
protected $description;
public function __construct($pdo,$id) {
$this->id=$id;
}
public function getTitle($pdo) {
$this->title=$pdo->run("SELECT title FROM courses WHERE id=?",[$this->id])->fetchColumn();
return $this->title;
}
public function getDescription($pdo) {
$this->description=$pdo->run("SELECT description FROM courses WHERE id=?",[$this->id])->fetchColumn();
return $this->description;
}
public function showDetails($pdo) {
echo "<h3>".$this->getTitle($pdo)."</h3>".$this->getDescription($pdo);
}
}
Is this a wrong approach? Is it ok to run sql commands inside a class? Especially when I already had to use some DB data to generate the dropdown menu. I hope my question makes sense.
PS: I've heard passing the PDO object every time isn't the best practice but I'm not there yet to do it with the recommended instance(?)