1
$result = mysql_query("SELECT Country, Quantity FROM `table 1`");

$rows = array();
while($r = mysql_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}

print json_encode($rows, JSON_NUMERIC_CHECK);

How can I fetch a data while calculating it at first? I need to add below code to the above code and display in graph.

while($row = mysql_fetch_array($result1)){
            echo "Total Quantity = ". $row['SUM(quantity)'];
            echo "<br />";
christinano
  • 23
  • 1
  • 5

2 Answers2

1

You can simply get your total by SUM in mysql

$result = mysql_query("SELECT SUM(column_name) AS TotalFROM `table 1`");

or you can sum it in your while loop

    $total = '';    
    $rows = array();
    while($r = mysql_fetch_array($result)) {
    $row[0] = $r[0];
    $row[1] = $r[1];
    $total = $r[1] + $total;
    array_push($rows,$row);
    }
    $rows[]['total'] = $total;
    echo "<pre>";print_r($rows );

Also use PDO or mysqli prepared statements mysql is depreciated and completely removed in PHP7

Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
0

You can add a total row by keeping a running total in your loop, and after the loop you can add that total to the array:

$total = 0;
while($r = mysql_fetch_array($result)) {
    $total += $r[1];
    $rows[] = $r;
}
$rows[] = ['Total', $total];

Note that:

  • you don't need to copy each value one by one (like $row[0] = $r[0];), you can just assign the whole array;
  • adding to an array can be done with array_push, but $rows[] = also works, and probably faster.
  • mysql_ functions have been deprecated for a long time now, and are no longer supported in the current version of PHP (7.x). Please use mysqli_ functions or PDO instead.
Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286