在PHP中的'mysql_fetch_row'中用'foreach'更改'while'

Is it possible to change while by foreach in mysql_fetch_row in PHP?

For example

$result = mysql_query("SELECT * FROM test");

while ($row = mysql_fetch_row($result)) {
    print_r($row);
}

This will take all records(rows) from query SELECT * FROM test.

But, if foreach is used

foreach (mysql_fetch_row($result) as $row) {
    print_r($row);
}

This will take only first record(row) from query SELECT * FROM test.

Is it possible get all records by foreach loop when using with mysql_fetch_row ?

You can only use foreach if:

  • you create a class that implements ArrayAccess or Iterator, or
  • you obtain the whole result set in an array and use that array with foreach.

You could use a for loop, but the code would be less than readable:

for ($row = mysql_fetch_row($result); $row !== false; $row = mysql_fetch_row($result)) {
    print_r($row);
}

No, because foreach needs a array. Here, mysql_fetch_row() returns only one row at a time.