iceman
iceman

Reputation: 31

PHP Loop with in a loop

I have a database containing a list of students with their names and availed books (list of books, serialized, stored in one row). I and now trying to display all of the students and the list of books they availed, I created a loop within a loop, but the thing is it just display the first record. It displays fine, but just the first record.

mysql_select_db("MYDB", $con);
$result = mysql_query("Select * From EnrolleeList where Gradelvl = 2 Order By Lname ASC");
while($row=mysql_fetch_array($result))
    {
    echo $row['name'] . " " . $row['lastname'];
    $glvl = $row['Gradelvl'];
    $getbooks = $row['BookList']; //data containing book list

    $getbooks = unserialize($getbooks);
    $arrlength = count($getbooks);  

    for($actr = 0; $actr < $arrlength; $actr++) 
        {
        $result = mysql_query("Select * From  ELEMBooks where GradeLevel = '$glvl' and BID = '$getbooks[$actr]' ");
        while($row = mysql_fetch_array($result))
            {
            echo $row['Subject'];
            echo " - ";
            echo $row['Book'];
            echo " - ";
            echo $row['Weight'];
            echo " - ";
            }
        }       
}
mysql_close($con);

Upvotes: 0

Views: 52

Answers (1)

Dhara Parmar
Dhara Parmar

Reputation: 8101

For outer loop use $row and for inner row use different variable ex. $rowInner and same for all duplicate variables

while($row=mysql_fetch_array($result)) // $row here
    {
    echo $row['name'] . " " . $row['lastname'];
    $glvl = $row['Gradelvl'];
    $getbooks = $row['BookList']; //data containing book list

    $getbooks = unserialize($getbooks);
    $arrlength = count($getbooks);  

    for($actr = 0; $actr < $arrlength; $actr++) 
        {
        $resultInner = mysql_query("Select * From  ELEMBooks where GradeLevel = '$glvl' and BID = '$getbooks[$actr]' ");
        while($rowInner = mysql_fetch_array($resultInner)) // $rowInner here
            {
            echo $rowInner['Subject'];
            echo " - ";
            echo $rowInner['Book'];
            echo " - ";
            echo $rowInner['Weight'];
            echo " - ";
            }
        }       
}

Upvotes: 2

Related Questions