Vikas Kumar Vikas Kumar - 1 year ago 51
PHP Question

Why and how does this function fetches next row each time?

As we know, to fetch all relevant rows from a table we use a while loop like this:

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

Now, I don't understand this expression: $row = mysqli_fetch_assoc($query) and consequently this while loop. How does mysqli_fetch_assoc fetch a new row each time?

How does it work? What is this expression actually?

Answer Source

Actually, the right and correct way of writing it is:

while (false != ($row = mysql_fetch_assoc($query))) {

Or in better ways:

while (false != ($row = mysqli_fetch_assoc($query))) {
  • Firstly, it should only take up a boolean value (either true or false) and not an assignment.
  • Secondly, please make use of mysqli_* functions or PDO instead of mysql_* functions, as the former one is deprecated and removed in PHP 7.

The $row is assigned with the content of the next row set values in an associative array here. At the same time, when there are no more rows, the function returns false, which breaks the while loop.

From the manual:

Fetch a result row as an associative array. Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in resultset.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysqli_fetch_row() or add alias names.

According to your DB structure, say I have this DB:

| Name              |
| Praveen           |
| Vikas             |
| Kumar             |

When you call the function like this:

  mysql_fetch_assoc($query);  // returns {"Name" => "Praveen"}
  mysql_fetch_assoc($query);  // returns {"Name" => "Vikas"}
  mysql_fetch_assoc($query);  // returns {"Name" => "Kumar"}
  mysql_fetch_assoc($query);  // returns NULL

Hope this explains you. It has an internal pointer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download