I'm trying to learn OOPHP and I think I'm getting there. I just don't know what the best way of outputting multiple database rows is.
The first method I've tried is doing the outputting normally within the function, but I think this kind of defeats the purpose of OOP.
I've also tried setting a public $list within the class that the database query pushes all the data to and then looping through the data outside the code, but ideally I'd like to create multiple instances of the object from the query and use their public variables (id, name, and eyecolour in my test case) to get the data so that the data always comes from the same place. But how do I create multiple objects from a query within the class and then how do I loop through them to display them, and how do I differentiate between them or just target a specific object with a specific value?
I have trawled through multiple topics but they all seem to focus on the problem in a specific situation. I'd like to learn it in this simple sense so I can then apply it to bigger projects.
Here is the code that I have been playing around with:
class Ignition {
public function dataConnection() {
return new PDO('mysql:host=localhost;port=8889;dbname=oop_testing','root','root',array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
}
class People {
private $db;
// Each person has a
public $id;
public $name;
public $eyecolour;
public $list = array();
public function __construct() {
$this->db = new Ignition();
$this->db = $this->db->dataConnection();
}
public function getList() {
echo "People:<br /><br />";
$sql = $this->db->prepare("SELECT * FROM people");
$sql->execute();
//$this->list = $sql->fetch(PDO::FETCH_ASSOC);
while($person = $sql->fetch(PDO::FETCH_ASSOC)) {
array_push($this->list, $person);
}
/*while($person = $sql->fetch(PDO::FETCH_ASSOC)) {
echo $person['name'] . "<br />";
}*/
}
public function getIndividual($search, $by = "id") {
$sql = $this->db->prepare("SELECT * FROM people WHERE $by = :search");
//$sql->bindParam(":by", $by);
$sql->bindParam(":search", $search);
$sql->execute();
$individual = $sql->fetch(PDO::FETCH_ASSOC);
$this->id = $individual['id'];
$this->name = $individual['name'];
$this->eyecolour = $individual['eyecolour'];
}
}
$people = new People();
$people->getList();
/*echo "<pre>";
var_dump($people->list);
echo "</pre>";*/
foreach ($people->list as $person) {
echo $person['name'];
}
$people->getIndividual(1);
echo "<br />Name: " . $people->name;
echo "<br />Eye Colour: " . $people->eyecolour;