Sum values in one mysql column and group by values of other column (using php foreach) -
started write question, while wrote question, answer. not delete content, post answer (possibly may useful). , may there improve.
based on https://stackoverflow.com/a/15048890/2465936 answer trying sum values in 1 column , group values in other column
for example, table named 2_1_journal
transactionpartnername | amount ------------------------------- name 1 | 1 name 2 | 2 name 1 | 3 name 3 | 10 name 2 | 7 name 1 | 150
as result want this
name 1 = 154 name 2 = 9 name 3 = 10
mysql query
$query_select_all =" select transactionpartnername, sum(amount) 2_1_journal group transactionpartnername";
then
$sql = $db->prepare($query_select_all); $sql->execute(); $sql = $sql->fetchall();
with print_r($sql);
get
array ( [0] => array ( [transactionpartnername] => name 1 [0] => name 1 [sum(amount)] => 154.00 [1] => 154.00 ) [1] => array ( [transactionpartnername] => name 3 [0] => name 3 [sum(amount)] => 10.00 [1] => 10.00 ) [2] => array ( [transactionpartnername] => name 2 [0] => name 2 [sum(amount)] => 9.00 [1] => 9.00 ) )
so far seems ok.
then foreach
<?php foreach ($sql $i1 => $row1) { ?> <tr> <td width="90px"><div style="width:90px;"> <?php echo htmlspecialchars($row1['transactionpartnername'])?> </div></td> <td width="50px"><div style="width:53px;"> <?php echo htmlspecialchars($row1['sum(amount)'])?> </div></td> </tr> <?php } ?>
Comments
Post a Comment