简体   繁体   English

嵌套的php循环仅在连接到sql时运行一次

[英]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. 我正在尝试学习php,并且正在从事此练习。 I have an SQL db with two tables: categories and items. 我有一个带有两个表的SQL数据库:类别和项目。 I want to loop through categories and create an html table for each category. 我想遍历类别并为每个类别创建一个html表。 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. 我试过在项目上使用foreach循环,但是什么都没显示出来。

<?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. 对于第一次之后的内部循环,item_result指针将结束,如果要再次循环,则必须将其重置。

so before the inside while add this line 所以在里面之前添加这行

mysqli_data_seek($items_result, 0);

this line set the item_result pointer to first row 这行将item_result指针设置为第一行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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