我正试图从我的SQL数据库中显示信息到google图表。该项目是一个健康仪表板,我需要显示步骤,千卡等。
我从数据库中得到了信息,但我在循环它时遇到了麻烦(相同的信息显示多次)。我认为问题出在 "data.addrows"-代码的某个地方。
php
include('template.php');
$query = /** @lang text */ <<
SELECT * FROM project_healthinfo WHERE id = {$_SESSION['userId']} ORDER BY date DESC
END;
$res = $mysqli->query($query);
$result = $res->fetch_object();
$content = <<<END
<!-- Google Chart script starts here -->
<!--Load the AJAX API-->
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Steps taken');
data.addRows([
['$result->date', $result->steps],
['$result->date', $result->steps],
['$result->date', $result->steps]
]);
var options = {
chart: {
title: ''
},
width: 550,
height: 300
};
var chart = new google.charts.Line(document.getElementById('steps_chart'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
</script>
<!-- Google Chart script ends here -->
你需要把$content分成两部分。
$before_result_date = <<<EOS
...
EOS;
$after_result_data = <<<EOQ
...
EOS;
然后在这两部分之间应该有一个类似于这样的循环。
while($result = $mysqli->fetch_object()){
printf("['%s', %s],\n",$result->date, $result->steps);
}
然后全部加在一起就是这样的东西。
include('template.php');
$query = /** @lang text */ <<
SELECT * FROM project_healthinfo WHERE id =
{$_SESSION['userId']} ORDER BY date DESC
END;
$res = $mysqli->query($query);
print $before_result_date;
while($result = $mysqli->fetch_object()){
printf("['%s', %s],\n",$result->date, $result->steps);
}
print $after_result_date;
这样就可以了