Question: Im always using while loop in generating all record in my database, and some of my friend told me that it is better to use foreach in generating record from a database, but i dont know how.

```
<?php
    $query =  mysql_query("select * from sampleTABLE");
    while($i =  mysql_fetch_array){
    echo $i['samplefieldName'];
    }
?>

```

My question is, how to display records from my database using foreach? and can some one compare it in the while loop in terms in syntax and generating its result, thank you.

Answer: 
There is no need to use foreach instead of while here as @Zerkms says 

```
 while($i =  mysql_fetch_array( $query)){

```

however ou can do this by below code but i am sure its not good approach 

```
$result_list = array();
while($row = mysql_fetch_array($query)) {
   result_list[] = $row;
}

foreach($result_list as $item) {
   //you can now echo $item ; or whatever you want
}

```

---

**Note**
--------

1. The entire **`ext/mysql`** PHP extension, which provides all functions named with the prefix mysql\_, is [officially deprecated as of PHP v5.5.0](http://php.net/manual/en/changelog.mysql.php) and will be removed in the future. So use either `PDO` or `MySQLi`

**Good read**

1. [The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead](https://stackoverflow.com/questions/13944956/the-mysql-extension-is-deprecated-and-will-be-removed-in-the-future-use-mysqli/13944958#comment19236631_13944958.)
2. [PDO Tutorial for MySQL Developers](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers)
3. [Pdo Tutorial For Beginners](https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php/14110189#14110189)
It's not possible to iterate over a result set using `foreach`.

`foreach` only works for cases when you already have the data fetched.

So your friend was just wrong and his advice doesn't make any sense.