While loop

I’m learning PHP. I am facing difficult to understand how while loop is implemented in array.
Here is

  if(mysqli_num_rows($result) > 0){
                echo "<table border='3' cellpadding='2' cellspacing='4' bgcolor='#bdb76b'><tr><th>Employee ID</th><th>Name</th><th>Email Address</th></tr>";
                //output data from each row
                while ($row = mysqli_fetch_assoc($result)){
                    echo "<tr><td>".$row['EmployeeId']."</td><td>".$row['FirstName']." ".$row['LastName']."</td><td>".$row['Email']."</td></tr>";
                }

please can any one help me to understand why this display as many rows as are in $result
Thanks,I am Athanas Shauritanga from Tanzania.

This line

while ($row = mysqli_fetch_assoc($result)){

is the start of your while() loop. Basically the loop will run while the evaluation inside the brackets does not evaluate to false. The mysqli_fetch_assoc() function retrieves the next row from the result set specified in $result, but returns false when there are no more results to return. So, at the end of the results set, $row becomes false and the while loop ends.

Note that in this code, $result is not an array, it is an object which contains the results (or enough information for MySQL to provide the results) from your query. So you couldn’t var_dump($result) and see all the rows that your query returned. PDO has a function called fetchAll() which will return all rows as an array, and then you can iterate through the array as you wish.

2 Likes

Thanks you very much droopsnoot!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.