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 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程