PHP 从数据库中获取数据

标签 php mysql database

我在以我想要的方式检索和格式化检索到的信息时遇到了一些问题。

基本上我的产品 ID 与类别 ID 相匹配。一个产品可以有多个类别,我得到了预期的结果。但我正在尝试以一种方式对其进行格式化,以便为每个产品获得类别 ID 列表。现在我为每个类别 ID 获得了多个产品 ID,如下所示:

Product Id: 65 ––> Categories Id:250
Product Id: 65 ––> Categories Id:249
Product Id: 66 ––> Categories Id:250
Product Id: 66 ––> Categories Id:249
Product Id: 66 ––> Categories Id:252
Product Id: 66 ––> Categories Id:251
Product Id: 66 ––> Categories Id:276
Product Id: 66 ––> Categories Id:268
Product Id: 66 ––> Categories Id:255

我需要它更像:

Product Id: 65 ––> Categories Id:250, 249
Product Id: 66 ––> Categories Id:250, 249, 252, 251, 276,268, 255

这是我执行查询的代码:

$sql = "SELECT * FROM `products_categories` ORDER BY `products_categories`.`productid` ASC";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
   while($row = $result->fetch_assoc()) {
      echo "Product Id: " . $row["productid"] . "  ––>  " . "Categories Id:" . $row["categoryid"] . "<br>";
   }
} else {
   echo "0 results";
}

提前感谢您的任何意见。

最佳答案

使用 GROUP_CONCAT

SELECT productid, GROUP_CONCAT(categoryid) as categoryid
FROM products_categories
group by productid
order by productid

关于PHP 从数据库中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39420587/

相关文章:

mysql - 跳过所有数据库,只运行特定的一个

mysql - 带有 OneToOne 注释的数据库结构

php - mysql中如何清除某一列的数据而不删除它

php - 使用 PHP 为 Apple Wallet passes 创建 PKCS #7 分离签名

php - 连接具有相同 ID 和相同列名但值不同的两个表

mysql - 为 MySql 中的 View 生成唯一长 ID

php - 将数组转换为对象以自动化 array_key_exists()

php - 可捕获的 fatal error : Object of class SimpleImage could not be converted to string (casting a var is not working)

mysql - 比较mysql中的2列

python - 在不同列中打印数据库变量