显示 table 查询但将类别分组并水平显示子类别

Display a table query but group a category and display subcategory horizontally

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

// 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 table 中有 15 个不同的类别,每个类别有 5-15 种类型。

不久前我在 Microsoft Access 中借助主键做了类似的事情,但我迷失了访问权限(现在 Mac 不得不学习 php & sql)

首先使用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();