Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

mysql - Looping Through SQL Results in PHP - Not getting Entire Array

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...