dqz84361326 2012-02-11 19:32 采纳率: 0%
浏览 48
已采纳

在PHP中循环SQL结果 - 没有获得整个数组

I'm probably missing something easy, but I seem to be blocked here... I have a MySQL database with two tables and each table has several rows. So the goal is to query the database and display the results in a table, so I start like so:

$query = "SELECT name, email, phone FROM users";

Then I have this PHP code:

$result = mysql_query($query);

Then, I use this to get array:

$row = mysql_fetch_array($result);

At this point, I thought I could simply loop through the $row array and display results in a table. I already have a function to do the looping and displaying of the table, but unfortunately the array seems to be incomplete before it even gets to the function.

To troubleshoot this I use this:

for ($i = 0; $i < count($row); $i++) {
    echo $row[$i] . " ";
}

At this point, I only get the first row in the database, and there are 3 others that aren't displaying. Any assistance is much appreciated.

  • 写回答

2条回答 默认 最新

  • dongyongan9941 2012-02-11 19:34
    关注

    You need to use the following because if you call mysql_fetch_array outside of the loop, you're only returning an array of all the elements in the first row. By setting row to a new row returned by mysql_fetch_array each time the loop goes through, you will iterate through each row instead of whats actually inside the row.

    while($row = mysql_fetch_array($result))
    {
       // This will loop through each row, now use your loop here
    
    }
    

    But the good way is to iterate through each row, as you have only three columns

    while($row = mysql_fetch_assoc($result))
    {
       echo $row['name']." ";
       echo $row['email']." ";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计