我正在尝试使用php PDO绘制数据库表,我使用以下代码成功制作了数据库:
test.php的
<?php
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$statement=$dbh->prepare("SELECT * FROM pdotable");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
?>
我需要将结果转换为图表JS代码,他的数据数组在此代码中:
initCharts: function() {
if (Morris.EventEmitter) {
// Use Morris.Area instead of Morris.Line
dashboardMainChart = Morris.Area({
element: 'sales_statistics',
padding: 0,
behaveLikeLine: false,
gridEnabled: false,
gridLineColor: false,
axes: false,
fillOpacity: 1,
data:
[{
period: '2011',
sales: 1400,
profit: 400
}, {
period: '2011 Q2',
sales: 1100,
profit: 600
}, {
period: '2011 Q3',
sales: 1600,
profit: 500
}, {
period: '2011 Q4',
sales: 1200,
profit: 400
}, {
period: '2012 Q1',
sales: 1550,
profit: 5
}],
lineColors: ['#399a8c', '#92e9dc'],
xkey: 'period',
ykeys: ['sales', 'profit'],
labels: ['Sales', 'Profit'],
pointSize: 0,
lineWidth: 0,
hideHover: 'auto',
resize: true
});
}
},
如何用PHP结果中的JSON替换data : [json]
?
答案 0 :(得分:1)
在关闭标签后的php文件中你需要编写JS部分,就像它
<script type="text/javascript" charset="utf-8">
var data = <?php echo json_encode($results); ?>;
</script>
小心分号。只需要纠正一个小小的JS脚本,但我认为你可以做到。
答案 1 :(得分:1)
// test.php
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$statement=$dbh->prepare("SELECT * FROM pdotable");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
header('Content-type: application/json');
echo $json;
//js
...
if (Morris.EventEmitter) {
//if you use jQuery
$.get('/test.php', {}, function(result) { //or use $.getJSON
dashboardMainChart = Morris.Area({
...
data: result,
...
xmlhttp如果你不使用jQuery
答案 2 :(得分:1)
您需要回显内容类型,以便浏览器看到返回数据并接受为json。
echo ('Content-type: application/json');
$json = json_encode($results);
echo $json;
我通常打开google控制台或firefox的firebug来查看您发送到的网络标签上的响应标签。从那里,您可以看到从服务器返回的数据,以检查您是否回显了正确的数据。
此外,您可以通过pluggin
在控制台日志中打印它们console.log(data);
在您的javascript中确认您是否以正确的格式获取数据。
您还可以查看一些db文档来提取您需要的数据。
而不是SELECT * FROM pdotable,SELECT period,sales,profit会做。
希望这会有所帮助。
答案 3 :(得分:0)