duanci1858 2014-09-13 05:57
浏览 134
已采纳

如何将多行MySQL数据库放入多维数组(PHP)?

I am working on a system where a query checks the database for records matching multiple ids and puts each row into it's own array. So far I only got the last row to echo out in it's own array. Here is the query code:

$query = "SELECT * FROM messages WHERE senderid IN ($senderids) ORDER BY messageid DESC";
$resource = mysql_query($query, $database);
$result = mysql_fetch_array($resource);
foreach($result as $result1)
    {
    print_r($result1);
    echo '<br>';
    }

This is what echos in the browser:

2
2
1
1
TEST MSG 2
TEST MSG 2
2014_09_13_01:29:59
2014_09_13_01:29:59

This is what should echo:

Array ([messageid] => 1 [senderid] => 1 [message] => test message [date] => 2014_09_13_01:01:09)
Array ([messageid] => 2 [senderid] => 1 [message] => TEST MSG 2 [date] => 2014_09_13_01:29:59)

How would I go about fixing this issue?

  • 写回答

2条回答 默认 最新

  • doutan5724 2014-09-13 06:09
    关注

    mysql_fetch_array does not return the whole result set, just the row at the current cursor. Your code isn't moving the mysql cursor; to do that, your code should be:

    $resource = mysql_query($query, $database);
    while($row = mysql_fetch_array($resource)){
      print_r($row);
      echo '<br />';
    }
    

    Also, for the desired output you posted, you should use mysql_fetch_assoc instead as it will be a hash with column names instead of an indexed array

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 access中怎么分割分别获取一下图中的值
  • ¥15 keras_tcn已经安装成功,还是显示ModuleNotFoundError: No module named 'keras_tcn'
  • ¥15 类图中关联与聚合的区别
  • ¥15 ENVI高分五号去除云层的方法
  • ¥15 16进制数据如何得到奇偶校验位
  • ¥15 求合并两个字节流VB6代码
  • ¥15 Pyqt 如何正确的关掉Qthread,并且释放其中的锁?
  • ¥30 网站服务器通过node.js部署了一个项目!前端访问失败
  • ¥15 WPS访问权限不足怎么解决
  • ¥15 java幂等控制问题