I cant figure out how to assign each one user from my database as class attribute and display them. Take a look. For example I have this table in my db:
+----+----------+------------+-----------+
| id | username | first_name | last_name |
+----+----------+------------+-----------+
| 1 | guu | Guu | GuuShtein |
| 3 | user1 | Allan | Last |
| 4 | Donny | Name | Last Name |
+----+----------+------------+-----------+
And here is the class:
class users {
public $db;
private $id;
private $username;
private $first_name;
private $last_name;
public function __construct($db) {
$this->db=$db;
}
private function find_by_id($id) {
$record = $this->db->query('SELECT * FROM users WHERE id=' . $id .' LIMIT 1')->fetch(PDO::FETCH_ASSOC);
foreach ($record as $atribute => $value) {
$this->$atribute = $value;
}
}
public function user_nfo($id){
$this->find_by_id($id);
$user_nfo = "User id: " . $this->id . "<br />";
$user_nfo .= "Username: " . $this->username . "<br />";
$user_nfo .= "User full name: " . $this->first_name . " " . $this->last_name . "<br />";
return $user_nfo;
}
}
$users = new mysql_a($db);
echo $users->user_nfo(1);
My question is how to write a method, that displays all users one by one? I mean something similar like in my user_nfo function, but just for all records? I tried “foreach” loop with PDOfetchAll, but it just overrides attributes and and displays only last record.
What you want is a new object called user that has all the properties that you want, Like the below.
Does this help?