Jeremy
Jeremy

Reputation: 883

PHP Nested While loop not working with mysql_fetch_assoc

I tested looping nested While statements so:

$count1 = 0;

while ($count1 < 3) {
 $count1++;
 $count2 = 0;
 echo "count1: ".$count1."<br />";

    while ($count2 < 3) {
    $count2++;
    echo "count2: ".$count2."<br />";
    }
}

This works perfectly (looping three times each) with results:

count1: 1
 count2: 1
 count2: 2
 count2: 3
count1: 2
 count2: 1
 count2: 2
 count2: 3
count1: 3
 count2: 1
 count2: 2
 count2: 3

Then I tried the same with a loop using mysql_fetch_assoc ($ContactsInterests is a two row associative array, and $LatestNews has 50 rows) i.e.

$CI_count = 0;

while ($CI_Row = mysql_fetch_assoc($ContactsInterests)) { //loop thru interests
$CI_count++;
$LN_count = 0;
echo "CI_count: ".$CI_count."<br />";

while ($LN_Row = mysql_fetch_assoc($LatestNews)) { //loop thru news
    $LN_count++;
    echo "LN_count: ".$LN_count."<br />";

}
}

The results are:

CI_count: 1
 LN_count: 1
 LN_count: 2
 ...
 LN_count: 50
 LN_count: 51
CI_count: 2

But where it the second iteration of LN_count? I don't understand why the LN_count didn't increment a second time.

Help appreciated.

Upvotes: 4

Views: 4297

Answers (4)

mysql_fetch_assoc does iteration for "mysql result" type. Seeks index for each fetch. you must use mysql_data_seek to go to the first result like;

<?php

    $CI_count = 0;

    while ($CI_Row = mysql_fetch_assoc($ContactsInterests)) { //loop thru interests
        $CI_count++;
        $LN_count = 0;
        echo "CI_count: ".$CI_count."<br />";

        mysql_data_seek($LatestNews,0);
        while ($LN_Row = mysql_fetch_assoc($LatestNews)) { //loop thru news
            $LN_count++;
            echo "LN_count: ".$LN_count."<br />";

        }
    }

Upvotes: 5

Ervin
Ervin

Reputation: 2442

mysql_fetch_assoc() takes out one by one the rows of the source, you when you will be in the second step of the first loop, you wont have any rows in the source variable.

You need to put the results of the second query in an array, then loop the array, and not using mysql_fetch_assoc.

Upvotes: 0

Dexter Huinda
Dexter Huinda

Reputation: 1222

You need to reset the mysql internal pointer:

see http://php.net/mysql_data_seek

Upvotes: 0

cjsissingh
cjsissingh

Reputation: 64

Because the results have been exhausted. You've iterated through all of them... If you wanted to loop again you're have to repopulate the $LatestNews variable.

Upvotes: 0

Related Questions