dtwy2858 2017-07-27 19:32
浏览 61
已采纳

从两个表循环访问mysqli查询以打印每个客户的逐项收据

I have two tables created for and online ordering system that look as such:
Table 1 (orders)

orderid | customername | email

15 | joe | joe@s.com
16 | ron | ron@this.com
17 | tim | tim@nice.com
18 | sue | sue@rad.com

and: Table 2 (orderitems)

id | orderid | orderitems

1 | 15 | sourdough
2 | 15 | four grain
3 | 16 | original fruit
4 | 16 | finnish rye
5 | 16 | sourdough
6 | 17 | sourdough
7 | 18 | original fruit

The orderid's are the same on both tables and I am trying to figure out how I can loop through all orderid's on the orderitems table to to print receipts for each customer.

so far i have a the mysqli statement:

$sql = 'SELECT a.orderid, a.customername, a.email, b.orderid, b.menuitem FROM orders a, orderitems b WHERE a.orderid = b.orderid';

$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
            echo "<td>" . $row['customername'] . "</td>";
            echo "<td>" . $row['phone'] . "</td>";
            echo "<td>" . $row['email'] . "</td>";
            echo "<td>" . $row['menuitem'] . "</td>";
}

this gets everything thing I need except I would like to separate each order individually so I can send each customer a receipt. I am not sure how to achieve this and I have exhausted all search terms here to try to find what I am looking for.
Any help would be appreciated.
Thanks in advance!!

  • 写回答

1条回答 默认 最新

  • dti3914 2017-07-27 19:42
    关注

    You should use an explicit join with an on (or using in this case where the two columns are exact match) clause. You then can group by the orders by their id and concatenate the items of the order with group_concat.

    select o.customername as name, o.email as email, group_concat(oi.orderitems) as items
    from orders as o
    join orderitems as oi using (orderid)
    group by orderid
    

    the on syntax would be:

    select o.customername as name, o.email as email, group_concat(oi.orderitems) as items
    from orders as o
    join orderitems as oi 
    on o.orderid = oi.orderid
    group by orderid
    

    You were using a loose join but the explicit is cleaner and more accurate.

    The conditional_expr used with ON is any conditional expression of the form that can be used in a WHERE clause. Generally, the ON clause serves for conditions that specify how to join tables, and the WHERE clause restricts which rows to include in the result set

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容