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: 
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.
@zerkms

I also thought like that.. But following works... 

My 'tbl\_login' table structure also attached as a 

```
<?php
    include '../common/dbConnection.php';

     class foreachtest{
        function foreachtesting(){
            $sql="SELECT * FROM tbl_login";
            $query_result=$GLOBALS['con']->query($sql);
            return $query_result;
        }
    }

    $myobject = new foreachtest();
    $result=$myobject->foreachtesting();

    foreach ($result as $a){
        echo $a['username'];
    }

?>

```

[tbl\_login MYSQL table screenshot](https://i.stack.imgur.com/WOldy.png)