The following PHP script joins two tables together and displays JSON based on the query.
<?php
$con=mysqli_connect("localhost","username","password","dbName");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT User, SUM(Price) as sumValue
FROM Table1
LEFT JOIN Table2 USING(Product)
GROUP BY User";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>
Because the query groups by the user, each user shows its own sumValue.
And I get the following JSON results:
[{"user":"Jack","sumValue":"4.50"},
{"user":"Jake","sumValue":" 4.00 "},{"user":"Mary","sumValue":" 8.50 "}]
How can I add a sum of all the sumValue
and display them at the end of the JSON like:
[{"user":"Jack","sumValue":"4.50"},
{"user":"Jake","sumValue":" 4.00 "},{"user":"Mary","sumValue":" 8.50 "},
{"sumTotal": "17.00"}]
Untested but I think you can make one more variable, add to it in the loop, then append after the execution and before the json
creation.
$tempArray = array();
$sum = 0;
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
$sum += $tempArray['sumValue'];
}
array_push($resultArray, array('sumTotal' => $sum);
echo json_encode($resultArray);
Simply sum them in the loop.
<?php
$con=mysqli_connect("localhost","username","password","dbName");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT User, SUM(Price) as sumValue
FROM Table1
LEFT JOIN Table2 USING(Product)
GROUP BY User";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
// you want an array of objects, so create an object to sum the sub totals
$total = new stdClass;
$total->sumTotal = 0;
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
// $resultArray[] = $row; // shorter... $tempArray unneeded.
$total->sumTotal += $row->sumValue;
// better way to do it:
// $total->sumTotal = bcadd($total->sumTotal, $row->sumValue);
}
$resultArray[] = $total;
echo json_encode($resultArray);
}
mysqli_close($con);
?>
However, there is one huge caveat: floating point math.
If precision is important, such as in currency, you'll want to use bcmath function
Try this:
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$total = 0;
while($row = $result->fetch_object())
{
array_push($resultArray, $row);
$total += $row->sumValue;
}
array_push($resultArray, array('sumTotal' => $total));
echo json_encode($resultArray);
}
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.