[英]How can I store data from MySQL database into array indexed by id?
I store some data from the MySQL database into an array: 我将来自MySQL数据库的一些数据存储到一个数组中:
$p = $db->query('SELECT * FROM comments;');
while ($row = $p->fetch(PDO::FETCH_ASSOC)) {
$commentlist[$row['id']] = $row['text'];
}
foreach($commentlist as $key => $value) {
echo $key;
echo $value;
}
Now I have access to the values id
and text
. 现在,我可以访问值
id
和text
。 But I also need to have access to the value image
(which is another row in the MySQL database). 但是我还需要访问值
image
(这是MySQL数据库中的另一行)。 But how can I store it if I have only two available elements: key and value? 但是,如果我只有两个可用的元素:键和值,该如何存储呢?
If you need other fields, then you should store the whole row in $value. 如果需要其他字段,则应将整行存储在$ value中。
However, PDO is a little more than everyone think. 但是,PDO超出了所有人的想象。 It can give you the desired result in a single call thanks to, fetchAll() method with PDO::FETCH_UNIQUE modifier :
多亏了具有PDO :: FETCH_UNIQUE修饰符的fetchAll()方法,它可以在一次调用中给您所需的结果:
$commentlist = $db->query('SELECT * FROM comments;')->fetchAll(PDO::FETCH_UNIQUE);
Now you can foreach over comments 现在您可以遍历评论
foreach($commentlist as $id => $value) {
echo $id;
echo $value['text'];
echo $value['image'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.