循环访问PHP中的SQL结果 - 没有获取整个数组 [英] Looping Through SQL Results in PHP - Not getting Entire Array

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

问题描述

我可能错过了一些简单的东西,但我似乎被阻止在这里...我有一个MySQL数据库与两个表,每个表有几行。所以我的目标是查询数据库并在表中显示结果,所以我开始如此:
$ b

$ query =SELECT name,电子邮件,电话FROM用户;



然后我有这个PHP代码:

$ result = mysql_query($ query);

然后,我用这个来获取数组:



$ row = mysql_fetch_array($ result);



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



要排除这个I ($ i = 0; $ i
$ b $ p $ $ b echo $ row [$ i]。 ;
}

此时,我只获取数据库中的第一行,是另外3个不显示。任何帮助的赞赏。

解决方案

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

  while($ row = mysql_fetch_array($ result))
{
//这将遍历每行,现在使用循环这里

}

但是最好的方法是遍历每一行($ row = mysql_fetch_assoc($ result))
$ {$ b $($ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' b echo $ row ['name']。;
echo $ row ['email']。;
}


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.

解决方案

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天全站免登陆