【问题标题】:Php mysql group by sum issuephp mysql group by sum 问题
【发布时间】:2017-10-20 07:19:50
【问题描述】:

得到这个代码 HTML

<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>

PHP

<?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);
?>

Angularjs

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

数据库

有两列 price 和 table_number。我得到了三个值。

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

但我得到的只是:

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

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

【问题讨论】:

  • 你能用数据发布你的表结构吗?
  • 请编辑您的问题并提供一个可重现的示例问题,并附上数据。

标签: php jquery mysql angularjs mysqli


【解决方案1】:

问题出现在这里:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 2019-02-11
    • 2013-04-30
    • 1970-01-01
    相关资源
    最近更新 更多