1

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 ?

3
  • You could use a framework such as codeigniter Commented Apr 13, 2012 at 18:42
  • 4
    @RPM, what's that got to do with anything? Commented Apr 13, 2012 at 18:43
  • Because it handles what your trying to do. Actually nevermind. You're trying to get all rows, without specifying their column names Commented Apr 13, 2012 at 18:44

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Should be Iterator instead of ArrayAccess
@dev-null-dweller, both ArrayAccess and Iterator can be used with foreach. Updated answer.
But ArrayAcces does not give you control on order of kes/values and skips protected/private properties, and fails completely when using internal array (or resource in this case) as data holder instead of class properties, so it can give different results when accessing as array and iterating with foreach, so to have true iterable object, better use Iterator.
1

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

1 Comment

It is possible with for loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.