Php mysql group by sum issue

时间:2017-05-20 05:27:30

标签: php jquery mysql angularjs mysqli

有这个代码 HTML

Model

PHP

<div class="ultventas_group" ng-repeat="mesa in mesas">
  <div class="ultventas_group_item">MESA {{mesa.table_number}}</div>
  <div class="ultventas_group_price">$ {{mesa.price}}</div>
</div>

Angularjs

<?php
include('base.php');
$result = mysqli_query($mysqli,"SELECT table_number, SUM(price) as totalprice FROM orders GROUP BY table_number LIMIT 30");
if(mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
        $data = $row;
    }
}else {
    echo "0 results";
};
echo json_encode($data);
mysqli_close($mysqli);
?>

DB

有两列价格和table_number。我有三个价值观。

$http({
    method: 'GET',
    url: '../../php/getTableList.php'
  }).then(function successCallback(response) {
      $scope.mesas = response.data;
  }, function errorCallback(response) {
      $scope.mesas = 'No Response';
  });

使用此代码,我应该得到结果

1. table_number=1 price = 30
1. table_number=1 price = 30
1. table_number=5 price = 60

但我得到了:

1. table_number=1 price = 60
1. table_number=5 price = 60

第一行是价格,第一行的价格,它忽略了所有其他的价格,我尝试使用table_number 5,这是同样的问题。

1 个答案:

答案 0 :(得分:2)

问题出现在这里:

if(mysqli_num_rows($result) > 0){
  while($row = mysqli_fetch_assoc($result)){
    $data = $row; // overwrite $data with new value.
  }
}else {
  echo "0 results";
};

而是这样做:

$data[] = $row;

由于您没有对每个行数据执行任何特殊操作,因此您可能希望使用mysqli_fetch_all()

if(count($data = mysqli_fetch_all($result,MYSQLI_ASSOC)) > 0){
  echo json_encode($data);
}