数据库和php父ID

时间:2018-11-26 17:03:45

标签: php mysql pdo

你好,我今天整天都在工作,实际上我真的迷路了,我现在有一张这样的桌子。

id |类别| parent_id

id = 5类别=笔记本电脑parent_id = 0
id = 7类别=房屋parent_id = 0
id = 8类别= HP parent_id = 5
id = 9 category = Lenovo parent_id = 5

所以我想做的是将其作为类别子类别样式获得;

  • 笔记本电脑

    • HP
    • 联想
  • 房屋

直到知道我拥有什么;

            <?php
        include_once("dir/db.php");
        $result = $db->query("SELECT * FROM categories WHERE parent_id = 0");
        ?>
        <ul>
        <?php
        while($row = $result->fetch(PDO::FETCH_ASSOC)):
            ?>
                <a href="gallerycato.php?id=<?php echo $row['id']?>"><li><?php echo $row['category'] ?></li></a>

        <?php endwhile;?>
    </ul>

输出;

<ul>
                            <a href="gallerycato.php?id=5"><li>Laptops</li></a>

                            <a href="gallerycato.php?id=7"><li>Houses</li></a>

                </ul>

但是我想让我的联想和惠普笔记本电脑使用,如果您能帮助我,我将非常高兴!谢谢。

1 个答案:

答案 0 :(得分:0)

<?php
        include_once("dir/db.php");
        $result = $db->query("SELECT * FROM categories WHERE parent_id = 0");
        echo "<ul>";
        while($row = $result->fetch(PDO::FETCH_ASSOC)):
            echo "<a href=\"gallerycato.php?id=" . $row['id'] ."\"><li>" . $row['category'] . "</li></a>";

            $sub_result = $db->query("SELECT * FROM categories WHERE parent_id = " . $row['id']);
            echo "<ul>";
            while($sub_row = $sub_result->fetch(PDO::FETCH_ASSOC)):
               echo "<a href=\"gallerycato.php?id=" . $sub_row['id'] ."\"><li>" . $sub_row['category'] . "</li></a>";
            endwhile;
            echo "</ul>";
        endwhile;
        echo "</ul>";
?>