在 PHP 中以每种类型显示带有组的 MySQL 数据


display mysql data with group in every type in php

>我的表结构如下所示:

TBL1

id  prodid prodname height cost category
-----------------------------------------
 1    1     Test      5     54    ABC
 2    5     Test1     6     85    DEF
 3    8     Test2     8     20    DEF
 4    2     Test3     4     10    GHI
 5    3     test4     8     58    ABC
 6    4     Test5     84    878   ABC

TBL2

 id(FK of pid)   color intensity vibrance
-----------------------------------------
  1                 red   5        NA
  5                 pink  0.5      8 ..and so on

现在我想要如下所示的输出,

想要输出

ABC
----
 Test ... & other parameters
 test4 ... & other parameters
 Test5 ... & other parameters
DEF
---
 Test1 ... & other parameters
 Test2 ... & other parameters
GHI
----
 Test3 ... & other parameters

我尝试过的查询是:

"SELECT tbl1.*,tbl2.* from tbl1 LEFT JOIN tbl2 on tbl1.prodid=tbl2.id;

.PHP

我试图通过以下方式展示猫:

$category="";
foreach($all as $row){
  if ($row['category'] != $category && !empty($row['category'])) {
        echo $row['category']; $category=$row['category'];
  }
  echo $row['othercolumns'];
}

但它不是分组...它每次都在重复。

你可以

使用PDO,它在PDOStatement::fetchAll()函数中有一个很好的功能PDO::FETCH_GROUP选项。首先,在您的查询中,将category作为第一列,如下所示:

SELECT tbl1.category, tbl1.* from tbl1 LEFT JOIN tbl2 on tbl1.pid=tbl2.id;

然后以PDO运行查询,并使用PDO::FETCH_GROUP fetchAll

$sth = $dbh->prepare($query);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
print_r($result); 
//Result will be something like this:
Array (
    [ABC] => Array
        [0] => Array
            (
               [id] => 1,
               [prodid] => 1,
               [prodname] => "test",
               [height] => 5,
               [cost] => 54,
               [category] => "ABC",
            ),
        [1] => Array
            (
             ...
            ),
        ....
        ),
    [DEF] => Array
        (
         ...
        ),
    ....
)

您可以选择所有内容,并在PHP中获取结果的时间,只需搜索类别即可。

SQL查询:

SELECT tbl1.*, tbl2.*, tbl2.id AS id2
FROM tbl1 AS tbl1
LEFT JOIN tbl2 AS tbl2 ON(prodid = id2)

PHP部分:

while ($row = mysqli_fetch_array($rows)){
   // handle $row[category] using switch or ifs 
      then put each in array to display the html part
}