0

I has problem looping the second while Loop.It will only loop once.So I can only get the value for the first row for the second loop. Please help me to figure this out, I am a beginner.

<ul id="navbar">

     <?php
     $rel = "SELECT * FROM table1 ORDER BY category";
     $sql=$db->query($rel); 
     while($row = $sql -> fetch_array()){
     ?>

     <li><a href="category.php?id=<?php echo $row['category_id'];?>"><?php echo $row['category'];?></a> 

        <ul>

            <?php
            $sel = "SELECT * FROM table2 WHERE category_id=".$row['category_id']." ORDER BY subcategory ASC";
            $sql=$db->query($sel);  
            while($row1 = $sql -> fetch_array()){
            ?>

            <li><a href="subcategory.php?id=<?php echo $row1['subcategory_id'];?>"><?php echo $row1['subcategory'];?></a></li>

            <?php }?>

        </ul>
    </li>

    <?php }?>

</ul>

3 Answers 3

3

You are overwriting $sql for the inner loop, invalidating it for the outer one. Use another variable name for the SQL result identifier in the second query.

Sign up to request clarification or add additional context in comments.

Comments

2

Well, you are keeping the results of the first query in the variable $sql

$sql=$db->query($rel); 

But then, before the second loop, you overwrite that variable.

$sql=$db->query($sel);  

Try declaring a new variable for the second use. Say, $sql2.

1 Comment

Thank you for having a look at my codes and helping me out...that was really helpful
1

The reason for this is that you use the variable $sql for both queries. Rename the second one to $sql2 for example.

Also, avoid using so many <?php ?> tags.

1 Comment

Thank you, I'll make a note of that...this was really helpful. Thank you for having a look at my codes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.