Fetching data from a MySQL table using a while loop in PHP

Fetching data from a MySQL table using a while loop in PHP

This:

$row = mysql_fetch_array($result)

while($row){
    echo $row[name].  - . $row[age];
    echo <br />;
}

doesnt work because $row will only take one value per execution which means that the while loop will run forever.

From the mysql_fetch_array doc:

Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

In the while($row = mysql_fetch_array($result)) version instead, the whiles conditional expression will be executed at every loop, therefore moving the mysql internal results pointer forward (reading the next result).

you should keep this

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

because, at every loop turn, $row gets a new value. If you set the value for $row outside the while statement, $row will reman the same value.

Fetching data from a MySQL table using a while loop in PHP

You need to use mysql_fetch_array function in the while loop like:

while(($row = mysql_fetch_array($result)) !== FALSE){
    echo $row[name].  - . $row[age];
    echo <br />;
}

The mysql_fetch_array function returns false if there is no record remaining. So loop it until it returns false.

Leave a Reply

Your email address will not be published.