简体   繁体   English

如何将MySQL数据库中的数据存储到ID索引的数组中?

[英]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 . 现在,我可以访问值idtext 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.

相关问题 如何将数组中的数据存储到mySQL数据库中? - How can I store data from an array into the mySQL database? 如何将mySQL数据库中的数据存储到数组中? - How can I store data from mySQL database into an array? 如何将区域语言 php 数组数据(古吉拉特语、印地语、旁遮普语)存储和检索到 mysql 数据库? - How can I store and retrieve regional language php array data (gujarati, hindi, punjabi) to mysql database? 如何使用mysql php将数组值存储在数据库中 - how can i store the array values in database using mysql php 如何在php中从mysql数据库将数据存储为关联数组 - how to store data as an associative array from mysql database in php 如何将嵌套/多维数组中的值存储在 MySQL 数据库中? - How can I store values from a nested/multidimensional array in a MySQL database? 我如何将大量内容从多阵列数组存储到mysql数据库中? - How can I store a huge amount of content from multidiemsional array into mysql database? 如何在MySQL数据库中存储对象的颜色数据? - How can I store an object's color data in MySQL database? 如何将敏感数据安全地存储在MySQL数据库中? - How can I store sensitive data securely in a MySQL database? 如何将laravel数据库查询放入索引的php数组中? - How can I put laravel database queries into an indexed php array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM