显示表查询,但对类别进行分组并水平显示子类别

时间:2016-04-22 16:01:26

标签: php mysql categories

到目前为止,这是我的剧本..

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT Category, Genre FROM skills";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     // output data of each row
 while($row = $result->fetch_assoc()) {
     echo "<br> Category: ". $row["Category"]. " - Genre: ". $row["Genre"]. "<br>";
}
} else {
     echo "0 results";
}

$conn->close();
?>    

我想让显示器看起来像:

类别:流派,流派,流派。类别:流派,流派,流派。

我在mySQL表中有15个不同的类别,每个类别有5-15种类型。

我之前在Microsoft Access中使用主键做了类似的事情,但是我没有访问权限(现在在Mac上必须学习php和sql)

1 个答案:

答案 0 :(得分:0)

首先使用GROUP_CONCAT()函数连接每个类别的所有类型,然后简单地遍历结果集。

以下是相关参考资料:

因此您需要从

更改SQL查询
$sql = "SELECT Category, Genre FROM skills";

$sql = "SELECT Category, GROUP_CONCAT(Genre SEPARATOR ', ') as Genre FROM skills GROUP BY Category";

这是完整的代码:

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT Category, GROUP_CONCAT(Genre SEPARATOR ', ') as Genre FROM skills GROUP BY Category";

$result = $conn->query($sql);

if ($result->num_rows > 0){
    while($row = $result->fetch_assoc()) {
        echo "Category: ". $row["Category"]. " - Genre: ". $row["Genre"]. "<br />";
    }
}else {
    echo "0 results";
}

$conn->close();