用sql变量绘制图形

时间:2013-07-29 11:10:48

标签: php sql google-visualization

我使用Google图表通过下面的代码绘制图表,但问题是我的数据是在sql表上,我如何将表格变量放入此图表?

<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]
    ]);

    var options = {
      title: 'Company Performance'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

通过查询数据库并将其转换为JSON字符串,从表中检索数据。然后将json字符串传递给变量

var data=/*your json string*/

答案 1 :(得分:0)

$db = new mysqli('localhost', 'user', 'pass', 'demo');

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

$sql = "SELECT attempt, login FROM result";

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}

echo "var data = google.visualization.arrayToDataTable([['Attempt', 'Login']";

while($row = $result->fetch_assoc()){
    echo ",['".$row['attempt'] ."','".$row['attempt']."']";
}

echo "]);";

$result->free();

$db->close();

答案 2 :(得分:0)

<?php


$result = mysql_query("SELECT year,sales,expenses from tablename");
$value=array();
while($r = mysql_fetch_assoc($result)) {
$year=$r['year'];
$sales=$r['sales'];
$expenses=$r['expenses'];
$val="[".$year.",".$sales.",".$expenses."]";
array_push($value,$val );
}
$final_value = implode(",", $value);

?>

将此$ final_value放入Google图表

function drawChart() {
    var data = google.visualization.arrayToDataTable([
      <?php echo $final_value?>
    ]);

    var options = {
      title: 'Company Performance'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }