Firstly, the mysql_xxx()
functions are deprecated. They are not recommended for use. There are two alternatives in PHP that are recommended instead -- mysqli()
and PDO
.
The older mysql_xxx()
functions do not allow you to use foreach
to loop through a recordset.
However, both the newer alternative APIs do allow this, as they implement the Iterator
interface.
So yes, it is possible to use foreach
to loop through a recordset in PHP, but not with the old mysql_xxx()
functions.
You could write code like this:
$conn = new mysqli(....);
foreach ( $conn->query('SELECT ....') as $row ) {
print_r($row);
}
or like this:
$db = new PDO('mysql:....', $user, $pass);
foreach ($db->query('SELECT ....') as $row) {
print_r($row);
}
Having said that, please note that it's only been possible to do this with mysqli
since PHP v5.4, so you'll need to be up-to-date with your PHP version for that. PDO
on the other hand has supported this feature for ages.
They can, of course, both also use a while
loop as well, and this is where your friend isn't quite right, because really there isn't any difference between while
and foreach
here. Switching from while
to foreach
won't make any difference to the performance of your code. They do the same thing under the hood. foreach
in this case is really just "syntactic sugar".
I would strongly recommend switching to one of these newer APIs, even if you don't plan to use foreach
to do your looping, because as I say, the old mysql
functions are deprecated, which means that they are likely to be removed entirely from future PHP versions. So if you want your code to keep running into the future, you should switch now.