Search code examples
phparraysforeachresultset

How to access mysql result set data with a foreach loop


I'm developing a php app that uses a database class to query MySQL.

The class is here: http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/
*note there are multiple bad practices demonstrated in the tutorial -- it should not be used as a modern guide!

I made some tweaks on the class to fit my needs, but there is a problem (maybe a stupid one).

When using select() it returns a multidimensional array that has rows with 3 associative columns (id, firstname, lastname):

Array
(
    [0] => Array
        (
            [id] => 1
            [firstname] => Firstname one
            [lastname] => Lastname one
        )

    [1] => Array
        (
            [id] => 2
            [firstname] => Firstname two
            [lastname] => Lastname two
        )

    [2] => Array
        (
            [id] => 3
            [firstname] => Firstname three
            [lastname] => Lastname three
        )
)

Now I want this array to be used as a mysql result (mysql_fetch_assoc()).

I know that it may be used with foreach(), but this is with simple/flat arrays. I think that I have to redeclare a new foreach() within each foreach(), but I think this could slow down or cause some higher server load.

So how to apply foreach() with this multidimensional array the simplest way?


Solution

  • You can use foreach here just fine.

    foreach ($rows as $row) {
        echo $row['id'];
        echo $row['firstname'];
        echo $row['lastname'];
    }
    

    I think you are used to accessing the data with numerical indices (such as $row[0]), but this is not necessary. We can use associative arrays to get the data we're after.