Php – 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.

Best Solution

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