I have a table like this in my database
orderID| productID | qty
1 5 1
1 2 1
1 6 1
1 4 1
2 9 1
2 5 2
2 6 1
I want to output it into my HTML/php page in a similar way to this
Order ID:1
Product ID | Qty
5 | 1
2 | 1
6 | 1
4 | 1
Order ID:2
Product ID | Qty
9 | 1
5 | 2
6 | 1
Is this even possible to do? I have tried to use DISTINCT but that only outputs 1 row for each orderID. Here is the closest way I have outputted using the ORDER BY statement at the moment but this makes the headers for every row from the database.
<?php
if ($query = "SELECT * FROM productOrders ORDER BY orderID"){
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
?>
<table>
<tr>
<th>Order ID: <?php echo $row['orderID'] ?></th>
</tr>
<tr>
<th>Product ID</th>
<th>Qty</th>
</tr>
<tr>
<td><?php echo $row['productID'] ?></td>
<td><?php echo $row['qty'] ?></td>
</tr>
</table>
<?php
}
}
?>
Try this
<?php
$query = "SELECT * FROM productOrders ORDER BY orderID";
if ($query){
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$id=$row['orderID'];
$sql="SELECT orderID, qty FROM productOrders WHERE orderID=$id";
$q=mysqli_query($connection,$sql);
if(!$q){ echo "error"; }
else { while($row1=mysqli_fetch_assoc($q)){
?>
<table>
<tr>
<th>Order ID <?php echo $id; ?></th>
</tr>
<tr>
<th>Product ID</th>
<th>Qty</th>
</tr>
<tr>
<td><?php echo $row1['productID'] ?></td>
<td><?php echo $row1['qty'] ?></td>
</tr>
</table>
<?
}
}
}
}
}
?>
select orderid, productid, sum(qty)
from productOrders
group by orderid, productid
which will give you layout of...
OrderID | ProductID | Qty
1 | 5 | 1
1 | 2 | 1
1 | 6 | 1
1 | 4 | 1
2 | 9 | 1
2 | 5 | 2
2 | 6 | 1
Then just loop through each row and display as needed in PHP
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.