在 PHP 中循环遍历 SQL 结果 - 未获取整个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9243383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:25:47  来源:igfitidea点击:

Looping Through SQL Results in PHP - Not getting Entire Array

phpmysqlfor-loop

提问by nicorellius

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:

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

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

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

Then I have this PHP code:

然后我有这个PHP代码:

$result = mysql_query($query);

$result = mysql_query($query);

Then, I use this to get array:

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

$row = mysql_fetch_array($result);

$row = mysql_fetch_array($result);

At this point, I thought I could simply loop through the $rowarray 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.

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

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.

在这一点上,我只得到了数据库中的第一行,还有 3 行没有显示。非常感谢任何帮助。

回答by Gaurav

You need to use the following because if you call mysql_fetch_arrayoutside 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_arrayeach time the loop goes through, you will iterate through each row instead of whats actually inside the row.

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

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

回答by daxnitro

One common way to loop through results is something like this:

循环结果的一种常见方法是这样的:

$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
    print_r($row);
    // do stuff with $row
}

Check out the examples and comments on PHP.net. You can find everything you need to know there.

查看 PHP.net 上的示例和评论。你可以在那里找到你需要知道的一切。