在 PHP 中循环遍历 SQL 结果 - 未获取整个数组 [英] Looping Through SQL Results in PHP - Not getting Entire Array

查看:47
本文介绍了在 PHP 中循环遍历 SQL 结果 - 未获取整个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能遗漏了一些简单的东西,但我似乎在这里被阻止了...我有一个包含两个表的 MySQL 数据库,每个表都有几行.所以目标是查询数据库并将结果显示在表中,所以我是这样开始的:

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";

然后我有这个 PHP 代码:

Then I have this PHP code:

$result = mysql_query($query);

然后,我用它来获取数组:

Then, I use this to get array:

$row = mysql_fetch_array($result);

此时,我想我可以简单地遍历 $row 数组并在表格中显示结果.我已经有一个函数来执行表格的循环和显示,但不幸的是,在到达函数之前,数组似乎不完整.

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] . " ";
}

此时,我只得到了数据库中的第一行,还有 3 行没有显示.非常感谢任何帮助.

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.

推荐答案

您需要使用以下内容,因为如果您在循环外调用 mysql_fetch_array,您只会返回一个包含所有第一行的元素.通过将 row 设置为每次循环通过 mysql_fetch_array 返回的新行,您将遍历每一行而不是行内实际内容.

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']." ";
}

这篇关于在 PHP 中循环遍历 SQL 结果 - 未获取整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆