我不知道如何将数据库中的每个用户分配为类属性并显示它们。看一看。例如,我的数据库中有这张表:
+----+----------+------------+-----------+
| id | username | first_name | last_name |
+----+----------+------------+-----------+
| 1 | guu | Guu | GuuShtein |
| 3 | user1 | Allan | Last |
| 4 | Donny | Name | Last Name |
+----+----------+------------+-----------+
这是课程:
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);
我的问题是如何编写一个方法,逐个显示所有用户?我的意思是类似于我的 user_nfo 函数,但仅适用于所有记录?我尝试使用 PDOfetchAll 进行“foreach”循环,但它只是覆盖属性并且只显示最后一条记录。