php - 从数据库获取子类别数据到列表

标签 php mysql

我想创建一个包含类别的列表,并且在悬停该类别时我需要显示子类别。我能够在列表中显示父类别。但无法理解如何获取子类别。在我的表中,我有category_id、parent_id 列和其他一些列。如果parent_id为“0”,则它是主类别,对于子类别,它包含category_id。所以现在我需要显示主类别的子类别。我不明白如何继续。任何人都可以提供建议吗?

<ul class="betterList">
  <?php 
        $con = mysql_connect("localhost","root","pwd") or die('couldnot connect to database'.mysql_error());
        mysql_select_db("DB",$con);
 $result=mysql_query("select * from table order by `name_en-GB`")or die("No table available with this name"."<br/><br/>".mysql_error());
             while($row=mysql_fetch_array($result))
            {
                $parent_id=$row['category_parent_id'];
                $category_id=$row['category_id'];
                if($parent_id==0)

                {
   ?>
                <li><?php echo $row['name_en-GB'];?></li>
               <?php }
                    ?>


                <ul id="internal" style=" margin:0px; 
padding:0;"><li><?php //echo $row['name_en-GB']; ?></li><li>data</li></ul></li> 

   <?php

           }?>   
</ul>

最佳答案

使用了此代码

 <ul class="betterList">
  <?php 
  $con = mysql_connect("localhost","root","pwd") or die('couldnot connect to database'.mysql_error());
  mysql_select_db("DB",$con);
  $result=mysql_query("select * from table where parent_id=0 order by `name_en-GB`")or die("No table available with this name"."<br/><br/>".mysql_error());
  while($row=mysql_fetch_array($result))
  {
    $category_id=$row['category_id'];
                ?>
                <li><?php echo $row['name_en-GB']; ?></li>

                <?php 
                $result1=mysql_query("select * from table where category_id=".$category_id." order by `name_en-GB`")or die("No table available with this name"."<br/><br/>".mysql_error());
                $num_row    = mysql_num_rows($result1);
                if($num_row>0) {
                    ?>
                     <ul id="internal" style=" margin:0px; padding:0;">
                    <?php                   
                }
                while($row1=mysql_fetch_array($result1))
                {?>
                    <li><?php echo $row1['name_en-GB']; ?></li>
                <?php
                }
                if($num_row>0) {
                    ?>
                     </ul>
                    <?php                   
                }
  }
                    ?>

关于php - 从数据库获取子类别数据到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19194811/

相关文章:

mysql - 分组并将每一行与两个不同的列相乘

mysql - MS Access 将链接表更改为 AWS MySQL Db 会减慢表单/报告的速度

php - fatal error : Namespace declaration statement has to be the very first statement in the script

php - 如果之前不存在则插入新记录,否则更新它。也不要针对特定​​条件插入超过 N 条记录

php - 更快网站的提示

mysql - 优化 select SQL - MySQL

php - 如何根据sql中的特定日期范围进行过滤

javascript - 使用 php 等待 10 秒后下载 html 文档的特定部分

php - 计算 codeigniter 中的总小时数和分钟数?

mysql - 优化 django 数据库查询