php - 在 PHP 中显示具有相同 id 的行的值

标签 php mysql string

我正在尝试制作一个自动打印订单的系统,但我现在遇到了一个问题。 我正在尝试以打印机可以理解的格式制作一个字符串,现在,我需要在发送之前从数据库中收集数据。现在我的问题是在某些情况下 order_id 是相同的。这是一个例子:

+----------+----------------------+
| order_id |     product_name     |
+----------+----------------------+
|     1    |   Pizza with cheese  |
+----------+----------------------+
|     1    |    Coca-Cola Zero    |
+----------+----------------------+
|     2    |       Spaghetti      |
+----------+----------------------+
|     3    |        Lasagna       |
+----------+----------------------+

所以我想做的是将所有“product_name”收集到一个具有相同“order_id”的字符串中,因此它显示为: “芝士披萨,可口可乐零度”

有什么办法吗?

提前致谢。

编辑: 我不知道我是否在上面清楚地提到了它,但我想制作一个显示它的 PHP 脚本。对不起,如果我混淆了。

最佳答案

你可以选择这个

select order_id, count(*), group_concat(product_name)
from orders
group by order_id
having count(*) > 1;

这会为您提供所有具有多个条目的 order_id,条目数和订单连接在一起。如果您不需要该数字,请在列列表中省略 count(*)

如果您想要所有 订单,请省略having

select order_id, count(*), group_concat(product_name)
from orders
group by order_id

并从 PHP 中使用它

$conn = new mysqli($host, $user, $pass, $db);
// use the appropriate select
$result = $conn->query('select order_id, group_concat(product_name) '
                       . 'from orders group by order_id');
while ($row = $result->fetch_array()) {
    // process the result row
}

这当然只是一个简要的概述。您必须添加错误处理并填写您要对结果执行的操作。

关于php - 在 PHP 中显示具有相同 id 的行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13434337/

相关文章:

php - 显示自定义 SQL 结果

python - 什么更有效率?使用 .replace() 或将字符串传递给列表

php - MySQL 日期搜索 MM/DD/YYYY 到 MM/DD/YYYY

php - 3 表 1 嵌套结果查询 - Mysql - Php

PHP for 循环 - 在表中显示数据

javascript - 如何将 NumPy 字符串转换为较短的版本,然后恢复为正常形式?

c - 如何在不使用正则表达式的情况下提取 C 字符串中双引号之间的文本?

php - 链式选择框 - 基本

php - 将邮件标记为未读

php - 我无法返回 MySQL 数据