Share
Fetch Array While Loop
As we have said, the mysql_fetch_array function returns an associative array, but it also returns FALSE if there are no more rows to return! Using a PHP While Loop we can use this information to our advantage.
If we place the statement "$row = mysql_fetch_array()" as our while loop's conditional statement we will accomplish two things:
- We will get a new row of MySQL information that we can print out each time the while loop checks its conditional statement.
- When there are no more rows the function will return FALSE causing the while loop to stop!
Now that we know what we need to do and how to go about doing it, the code pretty much writes itself, so let's move on to the next lesson. Just kidding! Here is the code that will print out all the rows of our MySQL Resource.
Fetch Array While Loop PHP and MySQL Code
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['age'];
echo "
";
}
?>
Fetch Array While Loop PHP & MysQL Display
Putu Sanjaya - 20
Made Sanjaya - 23
Haru Sanjaya - 18
And there we have all the rows from our example table! You could apply this script to any MySQL table as long as you change both the table name in the query and the column names that we have in the associative array.