从数据库显示Google图表无法正确显示数据

时间:2018-06-28 06:34:49

标签: javascript php html ajax google-visualization

我正在制作一个管理Web应用程序。我想显示数据库中的销售和购买图。我正在使用php检索数据,并使用ajax将其显示在html页面中。图形在绘制,但问题是数据无法正确显示。

这是我页面的链接:

  

https://smilestechno.000webhostapp.com/My/past.html

您可以通过输入以下内容来进行尝试-Categary=Purchase, View=Monthly, Year=2018, Month=Jun

脚本

<script type="text/javascript">

// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['bar']});

function drawChart() {

     var category = document.getElementById('category');
      var categorySelected = category.options[category.selectedIndex].value;
      var view = document.getElementById('view');
      var viewSelected = view.options[view.selectedIndex].value;
      var month = document.getElementById('month');
      var monthSelected = month.options[month.selectedIndex].value;
      var year = document.getElementById('year');
      var yearSelected = year.options[year.selectedIndex].value;

      var settings = {
    "url": "php/past.php",
    "method": "post",
    "headers": {
    "Content-Type": "application/x-www-form-urlencoded",
    },
    "data": {
    "category": categorySelected,
    "view": viewSelected,
    "month": monthSelected,
     "year": yearSelected
     }
    }

    $.ajax(settings).done(function(response) {
var data = google.visualization.arrayToDataTable([
['Month', 'Amount'], response
 ]);

var options = {
chart: {
  title: 'Past Performance Graph',
  subtitle: 'Duration : Jan 2018- Jun 2018',
}
};

var chart = new google.charts.Bar(document.getElementById('graph'));
chart.draw(data, google.charts.Bar.convertOptions(options));
});
}

</script>

PHP

<?php
$category = $_POST["category"];
$view = $_POST["view"];
$month = $_POST["month"];
$year = $_POST["year"];

$con = mysqli_connect("localhost","username","pw","db");

if($category == "Purchase"){
if($view == "Weekly"){
    $sql = "SELECT Date,SUM(Amount) from AccPurchase WHERE Date LIKE '$year-$month%' GROUP BY WEEK(Date)";
}else if($view == "Monthly"){
    $sql = "SELECT Date,SUM(Amount) from AccPurchase WHERE Date LIKE '$year%' GROUP BY MONTH(Date)";
}else if($view == "Yearly"){
    $sql = "SELECT Date,SUM(Amount) from AccPurchase GROUP BY YEAR(Date)";
}
}else if($category == "Sales"){
if($view == "Weekly"){
    $sql = "SELECT Date,SUM(Amount) from AccSales WHERE Date LIKE '$year-$month%' GROUP BY WEEK(Date)";
}else if($view == "Monthly"){
    $sql = "SELECT Date,SUM(Amount) from AccSales WHERE Date LIKE '$year%' GROUP BY MONTH(Date)";
}else if($view == "Yearly"){
    $sql = "SELECT Date,SUM(Amount) from AccSales GROUP BY YEAR(Date)";
}
}

$exc = mysqli_query($con, $sql);
$rows = array();
while ($row = mysqli_fetch_assoc($exc)) {
  $rows[] = array("v"=>$row["Date"], "v"=>$row["SUM(Amount)"]);
}
header('Content-Type: application/json');
echo json_encode($rows);
mysqli_close($con);
?>

我正在寻找解决方案,我得到了这篇文章:

  

How to create DataTable for ColumnChart by JSON object?

我认为我需要以这种格式对数据进行打磨,但我不知道如何从php以这种格式发送数据。

{
"cols": [
    {"id": "date", "label": "date","pattern": "","type": "string"},
    {"id": "newjobs","label": "newjobs","pattern": "","type": "number"}
],
"rows": [
    {"c": [
            {"v": "01-02-2013","f": null},
            {"v": 132,"f": null}
        ]},
    {"c": [
            {"v": "08-02-2013","f": null},
            {"v": 78,"f": null}
        ]},
    {"c": [
            {"v": "15-02-2013","f": null},
            {"v": 105,"f": null}
        ]
    },
    {"c": [
            {"v": "22-02-2013","f": null},
            {"v": 8,"f": null}
        ]}
]
}

1 个答案:

答案 0 :(得分:0)

第一,让我们在所有 sql语句中给总和计算一个名称...

将-> SUM(Amount)-更改为-> SUM(Amount) as TotalAmount

例如

$sql = "SELECT Date,SUM(Amount) as TotalAmount from AccPurchase WHERE Date LIKE '$year-$month%' GROUP BY WEEK(Date)";

下一步,以下php将以Google的数据表格式创建json ...

$exc = mysqli_query($con, $sql);

$rows = array();
$table = array();

$table['cols'] = array(
  array('label' => 'Month', 'type' => 'string'),
  array('label' => 'Amount', 'type' => 'number')
);

while ($row = mysqli_fetch_assoc($exc)) {
  $data = array();
  $data[] = array("v" => date_format($row["Date"], "Y-m"));
  $data[] = array("v" => $row["TotalAmount"]);
  $rows[] = array('c' => $data);
}

$table['rows'] = $rows;

header('Content-Type: application/json');
echo json_encode($table);
mysqli_close($con);

注意:您可能要更改日期格式,不确定此处是否需要...

$data[] = array("v" => date_format($row["Date"], "Y-m"));

这将为您提供-> 2018-06的格式-6月...


最终,因为您现在拥有正确的json格式,
您可以直接创建新的数据表,而无需使用-> arrayToDataTable
像这样...

$.ajax(settings).done(function(response) {

  var data = new google.visualization.DataTable(response);

  var options = {
    chart: {
      title: 'Past Performance Graph',
      subtitle: 'Duration : Jan 2018- Jun 2018',
    }
  };

  var chart = new google.charts.Bar(document.getElementById('graph'));
  chart.draw(data, google.charts.Bar.convertOptions(options));
});