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