我正尝试使用来自MySQL表的重量和日期数据并使用PHP PDO代码(在我的本地Mac计算机上)来生成Google折线图...出于某种原因,它没有填充JSON表。
我已经遍历了我的代码几次(这里还有所有其他示例)-但似乎无法找出我在做什么错。非常感谢任何指针。
这是我的代码:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myhestiatest";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT date, weight FROM weight WHERE userid = :userid");
// Bind parameters to statement
$stmt->bindParam(':userid', $_POST['userid']);
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'date'),
array('label' => 'Weight', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$sub_array = array();
$sub_array[] = array("v" => $row["date"]);
$sub_array[] = array("v" => $row["weight"]);
$rows[] = array("c" => $sub_array);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var options = {
title:'Weight Data',
legend:{position:'bottom'},
chartArea:{width:'95%', height:'65%'}
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
}
</script>
<style>
.page-wrapper
{
width:1000px;
margin:0 auto;
}
</style>
</head>
<body>
<div class="page-wrapper">
<br />
<h2 align="center">Display Google Line Chart with JSON PHP & Mysql</h2>
<div id="line_chart" style="width: 100%; height: 500px"></div>
</div>
</body>
</html>