arti
arti

Reputation: 657

Two MySQL while loops not working properly [PHP]

I have two while loops, both through MySQL results, see code:

        $result1 = $sql->runQuery1();
        $result2 = $sql->runQuery2();

                    while($record1 = mysqli_fetch_array($result1))
                    {
                        echo "$record1['id'] : ";
                        while($record2 = mysqli_fetch_array($result2))
                        {
                            echo "$record2['id'] <br> ";
                        }
                    }

Above code will run inside loop only once, code below:

        $result1 = $sql->runQuery1();


                    while($record1 = mysqli_fetch_array($result1))
                    {
                        $result2 = $sql->runQuery2();
                        echo "$record1['id'] : ";
                        while($record2 = mysqli_fetch_array($result2))
                        {
                            echo "$record2['id'] <br> ";
                        }
                    }

above will run internal loop as many times as many records is in MySQL query. Is there more efficient way of looping through that data? I don't want to re-run query each time.

Upvotes: 0

Views: 81

Answers (1)

Wep0n
Wep0n

Reputation: 402

If you fetch your result in an array, you should get all results. I suggest for PHP using $results = $sql->runQuery1() which will let you iterate through your results in a loop:

foreach($results as $var) {
    $var->doStuff(); // or display or whatever
}

you can of course nest these

foreach($results as $var) {
    foreach($results2 as $var2) {
        $var->doStuff($var2); //for example
    }
}

Here's the manual: http://php.net/manual/de/control-structures.foreach.php

The fetch_array and fetch_assoc will give you all fields in a row from your query into an associative array.

Upvotes: 1

Related Questions