简体   繁体   中英

MySQL multiple joins - how do i display the data? (using PHP)

Ok, i know this is stupid but I'm stuck and I need a kick in the head. I have 3 tables (orders, orderitems, products) and I'm using 2 left outer joins in a query to display the orders history in the clients section:

SELECT * FROM orderitems oi, orders o
LEFT OUTER JOIN product p ON p.dbarcode = oi.orderitems_item
WHERE o.order_code = oi.orderitems_ordercode 
    AND oi.orderitems_ordercode = '".$_GET['ordercode']."'` 

I can display a row for each product in the table order_items but I can't seem to display (echo) the total amount which is held in the field orders.order_amount, i presume it has to do with the fact that the field has multiple instances or whatsoever. How do I display data as a result of several tables joined?

Edit for Quassnoi:

I loop through the results and create a table row for each one and, after the loop, i want to display the general total:

  <? do { ?>
  <tr>
    <td><? echo $row_OrderItems['dbarcode']; ?></td>
    <td><? echo $row_OrderItems['name']; ?></td>
    <td><? echo $row_OrderItems['orderitems_quantity']; ?></td>
    <td><? echo $row_OrderItems['price']; ?></td>
  </tr>
  <? } while ($row_OrderItems = mysql_fetch_assoc($OrderItems)); ?>

  <tr>
    <td colspan="5">Total order amount (incl. shipping and handling): &euro; <? echo $row_OrderItems['order_amounteuro']; ?></td>
  </tr>

o.order_amount will be repeated in every row, just take the first one.

And, of course, never use this:

oi.orderitems_ordercode = '".$_GET['ordercode']."'` 

without mysql_real_escape_string .

<? do { ?>
  <tr>
    <td><? echo $row_OrderItems['dbarcode']; ?></td>
    <td><? echo $row_OrderItems['name']; ?></td>
    <td><? echo $row_OrderItems['orderitems_quantity']; ?></td>
    <td><? echo $row_OrderItems['price']; ?></td>
  </tr>
  <? 
$total = $row_OrderItems['order_amounteuro']; // store the total, before you loop past the last row
} while ($row_OrderItems = mysql_fetch_assoc($OrderItems)); ?>

  <tr>
    <td colspan="5">Total order amount (incl. shipping and handling): &euro; <? echo $total; ?></td>
  </tr>

Just an FYI, this part of your statement:

SELECT * FROM orderitems oi, orders o 
LEFT OUTER JOIN product p ON p.dbarcode = oi.orderitems_item

is fetching everything from orderitems , orders and products . Prefix the * with the table you want all the fields from, or rewrite it to fetch specific fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM