PHP MYSQL 连接

PHP MYSQL CONCAT

我正在为一群在 COVID 期间向弱势群体运送食物的当地企业做一些志愿工作。

订单示例:

Order No |  Customer Name | Address | Quantity | Item Name | Notes
===================================================
 #1234     |     Freda Smith      |3 High St   |      1     |   Loaf Bread  | Wholemeal 
 #1234     |     Freda Smith      |3 High St   |      2     |   500ml Milk  | Skimmed
 #1234     |     Freda Smith      |3 High St   |      1     |   Tea         | Eng. Breakfast

我需要将#1234 号订单的所有详细信息打印到一张机票上,如下所示:

#1234, Freda Smith, 3 High St
     
1 X Loaf Bread, Wholemeal   
2 X 500ml Milk, skimmed  
1 X Tea, Eng. Breakfast

我玩过 CONCATCONCAT_GROUP 并试图通过将 SELECT 与 HTML 格式分开来弄清楚,但无法得到我需要的.我很接近,但没有雪茄!

编辑:

SELECT IS:             $sql =    "SELECT id,
                       Order_Number, 
                       Full_Name,
                       Address,
                       Time_To_Deliver,
                CONCAT(Quantity, Item_Name, Notes)
                FROM orders
                CONCAT_GROUP BY Order_Number";
                    
            $users = $mysqli->query($sql);
            while($user = $users->fetch_assoc()){

您当前的设计有冗余数据,您应该 normalize 您的数据库结构,为订单和订单项目维护单独的 table 此外,您还可以添加客户 table。

根据您当前的设计,您可以遍历所有行并有条件地显示每个订单号。只有一次。

select id,
    order_number,
    full_name,
    address,
    time_to_deliver,
    quantity,
    item_name,
    notes
from orders
order by order_number asc

这里的 order by 子句很重要,这样您将获得每个订单的有序项目列表。获得查询的所有结果后,您可以将数据循环为

$currentParent = false;
while ($orderItem = $result->fetch_assoc()) {
   if ($currentParent != $orderItem['order_number']) {
        // display common detail of each order here
        echo '<h1>' . $orderItem['order_number'] .' '. $orderItem['full_name'] .' '. $orderItem['address']'</h1>';
        $currentParent = $orderItem['order_number'];
    }
    echo '<p>' . $orderItem['quantity'] .' '. $orderItem['item_name'] . ' '. $orderItem['notes'] .'</p>'; // here list rest of the information of order iterms 
    ...     
}

生成的标记类似于

<h1>#1234, Freda Smith, 3 High St</h1>
    <p>1 X Loaf Bread, Wholemeal</p>
    <p>2 X 500ml Milk, skimmed </p>
<h1>#1235, Freda Smith, 3 High St</h1>
    <p>1 X Tea, Eng. Breakfast</p>
//....

虽然您可以直接在数据库级别使用 group_concat 聚合(请参阅 Query for post and tags in same query),但它有字符限制的限制,可以调整但不是一个很好的方法来遵循当你可以处理应用层这种情况