Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...