javascript - 尝试使用 mysql 表和 PHP 绘制谷歌图表时出现“无法读取未定义的属性 'datefield'”
问题描述
我尝试使用 PHP 从数据库表中检索的值创建 google 图表,我的数据库已连接,但出现类似“无法读取未定义的属性 'datefield'”的错误
我的数据库表包含两列'Row Labels (VARCHAR)', 'Sum of No in Rows (INT)'。我不明白为什么会出现这个错误。
<?php
$connection = mysqli_connect('localhost', 'root', '', 'testingoforiginal');
$result = mysqli_query($connection, "SELECT * FROM ba");
if($result){
echo "CONNECTED";
}
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Row Labels', 'Sum of No in Rows'],
<?php
if(mysqli_num_rows($result) > 0 ){
while($row = mysqli_fetch_array($result)){
echo"['".$row['Row Labels']."',[".$row['Sum of No in Rows']."]],";
}
}
?>
]);
var options = {
title: 'BA',
width: 900,
legend: { position: 'none' },
chart: { title: 'BA',
subtitle: ' ' },
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Sum of No in Rows'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
};
</script>
</head>
<body>
<div id="top_x_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
解决方案
尝试删除第二行值中的额外括号...
改变...
echo"['".$row['Row Labels']."',[".$row['Sum of No in Rows']."]],";
至...
echo"['".$row['Row Labels']."',".$row['Sum of No in Rows']."],";
编辑
推荐使用json_encode
从 php 传递 json 数据。
在 php 中构建你的数组...
<?php
$connection = mysqli_connect('localhost', 'root', '', 'testingoforiginal');
$result = mysqli_query($connection, "SELECT * FROM ba");
if($result){
echo "CONNECTED";
}
$data = array();
$data[] = ['Row Labels', 'Sum of No in Rows'];
if(mysqli_num_rows($result) > 0 ){
while($row = mysqli_fetch_array($result)) {
$data[] = [$row['Row Labels'], $row['Sum of No in Rows']];
}
}
?>
然后在页面上对其进行编码以创建数据表...
var data = new google.visualization.arrayToDataTable(<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>);
推荐阅读
- c# - Autofac 两个 pgsql 数据库连接
- notepad++ - 如何从记事本++或任何其他文本编辑器中选择一个模式?
- c# - 如何从 IList Xamarin.Android c# 填充 ListView?
- python - 返回空列表和 CSV 文件 Selenium Python
- python - Python subplot 3 绘制 2x2 矩阵(金字塔)
- json - 邮递员:TypeError:无法读取未定义的属性“响应”
- python - 将函数应用于字典中 2 个键的每个可能组合
- sql - odi 列沿袭查询
- r - 多面 ggplot 华夫饼图中的手动色标
- flutter - 每次获取数据时,我的 FutureBuilder 都会触发两次