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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题