Ram Deep Siwach Ram Deep Siwach - 3 years ago 116
MySQL Question

Getting sum of rows with same id in SQL to PHP

I need help to get some of two rows with the same id:
I know the SQL code for this which is:

SELECT orderID,sum(itemPrice) as sum FROM orderitems GROUP BY orderID;

But I don't know how to implement this in PHP.
Here is my code :

$query = 'SELECT * FROM `orderitems`';
$statement = $db->prepare($query);
$addresses = $statement->fetchAll();

$order_id = filter_input(INPUT_POST, 'order_id');

$total='SELECT SUM(itemPrice)
FROM orderitems
group by orderID';
$statement = $db->prepare($total);
$total_order= $statement->fetchAll();

<title>Total of the order</title>
<link rel="stylesheet" type="text/css" href="main.css" />

Total for an order
<label>orderID : </label> <?php echo $order_id ;?>

<p>The total for this order consisting of :</p>

<p><?php echo $total_order; ?>


But it is not showing the result instead write simple

I even tried
but then it shows like that:

array(3) { [0]=> array(2) { ["SUM(itemPrice)"]=> string(6) "399.00" [0]=> string(6) "399.00" } [1]=> array(2) { ["SUM(itemPrice)"]=> string(6) "699.00" [0]=> string(6) "699.00" } [2]=> array(2) { ["SUM(itemPrice)"]=> string(7) "1048.99" [0]=> string(7) "1048.99" } }

It shows the right answer but I wanna get rid of this others things.

Answer Source

You can try with a simple foreach

    $total='SELECT SUM(itemPrice)   as sum
        FROM orderitems 
        group by orderID';
    $statement = $db->prepare($total);
    $total_order= $statement->fetchAll(PDO::FETCH_ASSOC);
    foreach($total_order as $row) {
       echo $row['sum'] . ' <br />';

in this juts an echo but you can add to div

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download