在php中显示每种类型的组的mysql数据

时间:2016-01-23 05:03:33

标签: php mysqli

我的表结构如下所示:

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'];
}

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

2 个答案:

答案 0 :(得分:0)

您可以使用herePDO功能中category选项为您提供了很好的功能。首先在您的查询中,将SELECT tbl1.category, tbl1.* from tbl1 LEFT JOIN tbl2 on tbl1.pid=tbl2.id; 设为第一列,如下所示:

PDO

然后使用fetchAll

PDO::FETCH_GROUP$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 ( ... ), .... ) 中运行查询
{{1}}

答案 1 :(得分:0)

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

SQL查询:

I

PHP部分:

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