How to iterate by row through a mysql query in php
$result = mysql_query("SELECT id, name FROM mytable");while ($row = mysql_fetch_array($result, MYSQL_NUM)) { printf("ID: %s Name: %s", $row[0], $row[1]); }
or using MYSQL_ASSOC will allow you to use named columns
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { printf("ID: %s Name: %s", $row["id"], $row["name"]);}
With PHP 7+ becoming the new standard and mysql_fetch_array becoming deprecated you will need to start using mysqli_fetch_array.
Object-oriented style
$result = $mysqli->query($query);/* numeric array */while ($row = $result->fetch_array(MYSQLI_NUM)) { // Do stuff with $row}/* associative array */while ($row = $result->fetch_array(MYSQLI_ASSOC)){ // Do stuff with $row}/* associative and numeric array */while ($row = $result->fetch_array(MYSQLI_BOTH)){ // Do stuff with $row}
Procedural style
$result = mysqli_query($mysqli, $query);/* numeric array */while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) { // Do stuff with $row}/* associative array */while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ // Do stuff with $row}/* associative and numeric array */while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)){ // Do stuff with $row}
You can read more about this change on the PHP Bible..