使用嵌套的while循环不能提供所需的输出

时间:2016-02-03 10:07:54

标签: php mysql pdo

我要做的是创建一个从数据库中提取的类别列表,然后在每个类别下面列出 相关的子类别。

到目前为止,我得到了:

<?php
// this query lets us know that we are looking for matches that equal 2,      which points to the subject of vehicles.
// from this query i am able to list all categories that are relevant to vehicles.

$getCategoriesQuery = $db->query("SELECT * FROM item_cat WHERE sub_id =  '2'"); //2 = vehicles
?>

<?php
while($row = $getCategoriesQuery->fetch()){
    echo '<ul>'.$row['category'].'';
}
?>

显示:

- motor vehicles
- railed vehicles
- aircraft

现在,当我将以下while循环添加到上面的那个:

<?php
while($row = $getCategoriesQuery->fetch()){
    echo '<ul>'.$row['category'].'';

    // this has been added to try and get the sub categories
    $getSubCatQuery = $db->query("SELECT * FROM item_cat, item_sub_cat
                WHERE item_cat.cat_id = item_sub_cat.cat_id "); // cat_id
        while($row = $getSubCatQuery->fetch()){
            echo '<li><a href="vehicles.php?p='.$row['sub_category'].'"  >'.$row['sub_category'].'</a></li>';

        }
    echo '</ul>';
}
?>

我得到:

- motor vehicles
   - cars
   - motorbikes
   - buses
   - trucks
   - trains
   - planes
-railed vehicles
   - cars
   - motorbikes
   - buses
   - trucks
   - trains
   - planes
-aircraft
   - cars
   - motorbikes
   - buses
   - trucks
   - trains
   - planes

当我想要做的是:

-motor vehicles
   - cars
   - motorbikes
   - buses
   - trucks
-railed vehicles
   - trains
-aircraft
   - planes

我尝试过加入查询,但没有快乐,所以我分成2个查询,试着看看事情好一点。 我已经在第二个while循环中将“$ row”更改为“$ row2”,但是这给了我一个未定义的索引错误“row2 ['sub_category']”

我也尝试使用“foreach循环”而不是第二个“while循环”:

<?php
// this query lets us know that we are looking for matches that equal 2, which points to vehicles.
$getCategoriesQuery = $db->query("SELECT * FROM item_cat WHERE sub_id = '2'"); //vehicles
?>

<?php
while($row = $getCategoriesQuery->fetch()){
    echo '<ul>'.$row['category'].'';

    $getSubCatQuery = $db->query("SELECT * FROM item_cat, item_sub_cat
                    WHERE item_cat.cat_id = item_sub_cat.cat_id "); // cat_id

        foreach ($getSubCatQuery->fetchAll () as $row2) {
        echo '<li><a href="vehicles.php?p='.$row2['sub_category'].'"  >'.$row2['sub_category'].'</a></li>';
        }
    echo '</ul>';
}
?>

我花了一整天时间试图解决这个问题,但是没有快乐 - 只是头疼。任何人都可以告诉我哪里出错了...我错过了什么? - 如果不清楚,我也在使用PDO。

提前感谢!

- UPDATED-- 我已将while循环部分更改为:

<?php
while($row = $getCategoriesQuery->fetch()){
    echo '<ul>'.$row['category'].'';

    $getSubCatQuery = $db->query("SELECT * FROM item_sub_cat, item_cat WHERE  item_sub_cat.cat_id ='".$row['cat_id']."' ");
        while($sub_row = $getSubCatQuery->fetch()){
            echo '<li><a href="vehicles.php?p='.$sub_row['sub_category'].'"  >'.$sub_row['sub_category'].'</a></li>';

        }
    echo '</ul>';
}
?>

并且输出显示正确类别中的内容....但是它按照我在数据库中的总记录重复每个项目:

- motor vehicles
  - cars
  - motorcycles
  - trucks
  - buses
  - cars
  - motorcycles
  - trucks
  - buses
  - cars
  - motorcycles
  - trucks
  - buses
  - cars
  - motorcycles
  - trucks
  - buses
  - cars
  - motorcycles
  - trucks
  - buses
- railed vehicles
  - trains
  - trains
  - trains
  - trains
  - trains

我试过在查询中添加“LIMIT 1”和“GROUP BY”,但之后每个类别只显示1个项目。

- motor vehicles
  - cars
- railed vehicles
  - trains

2 个答案:

答案 0 :(得分:1)

您的内部while循环正在重新分配$row数组变量。将其更改为其他名称,例如$sub_row

您的内部查询也不会根据外部查询的值而更改,因此每次都执行完全相同的方式。使用类似的东西 内部查询中的SELECT * FROM item_sub_cat WHERE item_sub_cat.cat_id = $row["category_id"]将允许结果依赖于外部查询的每个结果。

编辑:请注意在您的查询中包含表格,输出方式,您不需要。如果您需要执行两个表的连接,则仅包括它们。

答案 1 :(得分:0)

我不知道这是否有用但我认为您应该能够使用联接来一次性获取所有相关记录

select * from `item_cat` c
    right join `item_sub_cat` sc on sc.`cat_id`=c.`cat_id`
where c.`sub_id` =  '2'


create table if not exists `item_cat` (
  `cat_id` smallint(5) unsigned not null auto_increment,
  `category` varchar(50) default null,
  primary key (`cat_id`)
) engine=innodb auto_increment=4 default charset=utf8;

insert into `item_cat` (`cat_id`, `category`) values
    (1, 'aircraft'),
    (2, 'railed vehicles'),
    (3, 'motor vehicles');

+--------+-----------------+
| cat_id | category        |
+--------+-----------------+
|      1 | aircraft        |
|      2 | railed vehicles |
|      3 | motor vehicles  |
+--------+-----------------+


create table if not exists `item_sub_cat` (
  `scid` smallint(5) unsigned not null auto_increment,
  `cat_id` smallint(5) unsigned not null,
  `sub_category` varchar(50) not null,
  primary key (`scid`),
  key `cat_id` (`cat_id`),
  constraint `fk_cat_subcat` foreign key (`cat_id`) references `item_cat` (`cat_id`) on delete cascade on update cascade
) engine=innodb auto_increment=10 default charset=utf8;

insert into `item_sub_cat` (`scid`, `cat_id`, `sub_category`) values
    (1, 3, 'car'),
    (2, 3, 'motorbike'),
    (3, 3, 'buses'),
    (4, 3, 'truck'),
    (5, 2, 'train'),
    (6, 2, 'wagon'),
    (7, 1, 'helicopter'),
    (8, 1, 'plane'),
    (9, 1, 'microlite');

+------+--------+--------------+
| scid | cat_id | sub_category |
+------+--------+--------------+
|    1 |      3 | car          |
|    2 |      3 | motorbike    |
|    3 |      3 | buses        |
|    4 |      3 | truck        |
|    5 |      2 | train        |
|    6 |      2 | wagon        |
|    7 |      1 | helicopter   |
|    8 |      1 | plane        |
|    9 |      1 | microlite    |
+------+--------+--------------+

select * from item_cat c
    right join item_sub_cat sc on sc.cat_id=c.cat_id;

+--------+-----------------+------+--------+--------------+
| cat_id | category        | scid | cat_id | sub_category |
+--------+-----------------+------+--------+--------------+
|      3 | motor vehicles  |    1 |      3 | car          |
|      3 | motor vehicles  |    2 |      3 | motorbike    |
|      3 | motor vehicles  |    3 |      3 | buses        |
|      3 | motor vehicles  |    4 |      3 | truck        |
|      2 | railed vehicles |    5 |      2 | train        |
|      2 | railed vehicles |    6 |      2 | wagon        |
|      1 | aircraft        |    7 |      1 | helicopter   |
|      1 | aircraft        |    8 |      1 | plane        |
|      1 | aircraft        |    9 |      1 | microlite    |
+--------+-----------------+------+--------+--------------+

从上面的记录集中生成你所追求的html布局应该相对容易 - 尽管我可能错过了这一点。