Ram Deep Siwach Ram Deep Siwach - 1 month ago 7
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 :

<?php
require('database.php');
$query = 'SELECT * FROM `orderitems`';
$statement = $db->prepare($query);
$statement->execute();
$addresses = $statement->fetchAll();
$statement->closeCursor();



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

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


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

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


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

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

</p>
</body>
</html>


But it is not showing the result instead write simple
ARRAY

I even tried
var_dumb
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

You can try with a simple foreach

    $total='SELECT SUM(itemPrice)   as sum
        FROM orderitems 
        group by orderID';
    $statement = $db->prepare($total);
    $statement->execute();
    $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