如何从mysql读取和写入数据到JSON,然后用于谷歌表格图表

时间:2014-09-02 05:34:33

标签: php mysql json

我在mysql数据库中有employee表 表列为.. EMPNO 为ename 萨尔...等 我正在创建自定义查询页面。用户将在textarea中键入查询,然后单击提交按钮。我想根据用户请求的列从mysql中检索数据,并希望显示谷歌图表。

我尝试过JSON但没有运气

以下代码就是我所做的......

<form action="fire.php" id="usrform" method="post" target="iframe1">
    <p> Enter custom query here...</p>
    <textarea name="query" form="usrform" wrap="hard soft" cols="60" rows="10"></textarea>                   <br>
     <input type="submit" value="Fire Query">
</form>

Fire .php页面......

$con = mysqli_connect($db_host,$db_username,$db_pass) or die ("could not connect to mysql");

mysqli_select_db($con,$db_name) or die ("no database");  
//query all records from the database
$query=$_POST['query'];
$returnArray = array();
$result = mysqli_query($con,$query);
while($rs = mysqli_fetch_array($result, MYSQL_ASSOC))    
{    
$returnArray[] = $rs;     
}
$fp = fopen('sampledata.json', 'w+');
fwrite($fp, json_encode($returnArray));
fclose($fp);
}
?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
            <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
            <script type="text/javascript">

            // Load the Visualization API and the piechart package.
            google.load('visualization', '1', {'packages':['table']});

            // Set a callback to run when the Google Visualization API is loaded.
            google.setOnLoadCallback(drawChart);

            function drawChart() {
              var jsonData = $.ajax({
                  url: "getdata.php",
                  dataType:"json",
                  async: false
                  }).responseText;

              // Create our data table out of JSON data loaded from server.
              var data = new google.visualization.DataTable(jsonData);

              // Instantiate and draw our chart, passing in some options.
              var chart = new google.visualization.Table(document.getElementById('chart_div'));
              chart.draw(data, {width: 700, height: 400});
            }
            </script>
             <div id="chart_div"></div>
             </html>

访问getdata.php

<?php 
$string = file_get_contents("sampledata.json")`enter code here`;
echo $string;
?>

请告知我,因为我没有得到表格

1 个答案:

答案 0 :(得分:0)

尝试并更改

var jsonData = $.ajax({
              url: "getdata.php",
              dataType:"json",
              async: false
              }).responseText;

之类的东西
var jsonData;
var request = $.ajax({
  url: "getdata.php",
  dataType:"json",
  async: false,
  type: "GET"
});

request.done(function( msg ) {
  jsonData = $.parseJSON(msg.d);
  var data = new google.visualization.DataTable(jsonData);

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.Table(document.getElementById('chart_div'));
  chart.draw(data, {width: 700, height: 400});
});

并建议添加一个函数来调用图表,可能使用json数据参数。