gpt4 book ai didi

php - 来自 Mysql 数据库的 Google 条形图

转载 作者:行者123 更新时间:2023-11-29 19:13:08 24 4
gpt4 key购买 nike

我有一个带有 3 个字段的 mysql 数据库:region(vachar)、new_customers(int) 和 old_customers(int)。

我正在尝试使用 google 图表和 php 创建条形图,但它不起作用。我认为我在 echo 上做错了。这是我的代码:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawMaterial);

function drawMaterial() {
var data = google.visualization.arrayToDataTable([
['Region', 'New Customers', 'Old Customers'],
<?php
$query = "SELECT sum(new_customers) AS new, sum(old_customers) AS old, region FROM daily GROUP BY region";

$exec = mysqli_query($con,$query);

while($row = mysqli_fetch_array($exec)){

echo "['".$row['region']."',";

echo "['".$row['new']."',";

echo "['".$row['old']."',";

}
?>
]);

var options = {

title: 'Country wise new and returned visitors',

bars: 'horizontal'
};
var material = new google.charts.Bar(document.getElementById('barchart'));
material.draw(data, options);
}
</script>

最佳答案

您遇到的问题是图表没有采用数据变量中的三个参数。目前你有这样的:['Region', 'New Customers', 'Old Customers'], .

将其更改为: ['Region', 'New Customers'] ,。

while loop ,PHP 无法识别任何名为 $row['new'] 的列或$row['old'] 。相反,使用索引并将 echo 更改为:<强> echo "['".$row[2]." [".$row[0]."]', ".$row[1]."], ”;

我还建议您在函数之外进行 sql 查询,并且仅对 sql 结果进行迭代( while loopecho )。

此外,您没有正确加载图表。您忘记添加“图表”一词:

  google.charts.load('visualization', '1', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMaterial);

这是最终的解决方案:

<?php
include("YOUR PHP CONNECT FILE");

$query = "SELECT sum(new_customers) AS new, sum(old_customers) AS old, region FROM daily GROUP BY region";
$exec = mysqli_query($YOURCONNECTIONVARIABLE ,$query);

?>

<!DOCTYPE html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('visualization', '1', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMaterial);

function drawMaterial() {
var data = google.visualization.arrayToDataTable([
['Region', 'New Customers'],
<?php
while($row = mysqli_fetch_array($exec)){
echo "['".$row[2]." [".$row[0]."]', ".$row[1]."],";
}
?>
]);

var options = {
title: 'Country wise new and returned visitors',
bars: 'horizontal'
};

var material = new google.charts.Bar(document.getElementById('barchart'));
material.draw(data, options);
}
</script>
</head>
<body>
<div id="barchart" style="width: 100%; height: 40em;"></div>
</body>
</html>

如果您有任何疑问,请告诉我。

关于php - 来自 Mysql 数据库的 Google 条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42921138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com