简体   繁体   中英

Nested php loop only runs once when connecting to sql

I'm trying to learn php and I have this exercise I'm working on. I have an SQL db with two tables: categories and items. I want to loop through categories and create an html table for each category. I can do that part fine. Then for every category, I want to loop through every item and check to see if it belongs to that category. If it does, then it gets passed into the table. However, for some reason the second loop only gets run for the first category.

I've tried using a foreach loop on the items but then nothing shows up.

<?php while($category = mysqli_fetch_assoc($category_result)) : ?>

<button class="collapsible"><?= $category[Name]; ?></button>
    <div class="link-data">
        <table class="link-table">
            <?php while($item = mysqli_fetch_assoc($items_result)) : ?>
            <?php if (item[category_id] = category[id] ) : ?>
            <tr>
                <td><?= $item[name]; ?></td>
                <td><?= $item[price]; ?></td>
                <td><?= $item[description]; ?></td>
            </tr>
            <?php endwhile; ?>
            <?php endif; ?>
        </table>

    </div>

<?php endwhile; ?>

I then expect a result like this for example:

Phones :
  - Samsung

Toys :
 - Rubber ball

Books :
 - Harry Potter

Instead I'm getting this:

Phones :
 - Samsung
 - Rubber ball
 - Harry Potter

Toys :

Books :

for the inside loop after first time, item_result pointer goes to end and you have to reset it if you wanna loop again.

so before the inside while add this line

mysqli_data_seek($items_result, 0);

this line set the item_result pointer to first row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM