在php mysql中使用Google图表API显示条形图

在php mysql中使用Google图表API显示条形图,php,mysql,ajax,google-api,google-visualization,Php,Mysql,Ajax,Google Api,Google Visualization,我一直在寻找这个。我找到了解决办法。就在这里。这是在php中使用AJAX完成的。 我有两个关于is googleapi.php和从googleapi.php发送的AJAX请求所使用的其他getData.php的页面 googleapi.php <html> <head> <!--Load the Ajax API--> <script type="text/javascript" src="https://www.google.co

我一直在寻找这个。我找到了解决办法。就在这里。这是在php中使用AJAX完成的。 我有两个关于is googleapi.php和从googleapi.php发送的AJAX请求所使用的其他getData.php的页面

googleapi.php

 <html>
  <head>
    <!--Load the Ajax API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

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

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

    function drawChart(object) {

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(object);
      var options = {
           title: 'Test API',
          is3D: 'true',
          width: 200,
          height: 100
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }

    function show()
    {

        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET","getdata.php?name=jaspreet",true);
        xmlhttp.send();
        xmlhttp.onreadystatechange = getResponse;
    }
    function getResponse()
    {
        if(xmlhttp.readyState==4){
            alert(xmlhttp.responseText);
            var obj = JSON.parse(xmlhttp.responseText);
            drawChart(obj);
        }
    }
    </script>
  </head>

  <body>
    <!--this is the div that will hold the pie chart-->
    <div id="chart_div"></div>
    <select id="name" onchange="show();">
        <option value="test">test</option>
        <option value="test1">test1</option>
        <option value="test2">test2</option>
    </select>
  </body>
</html>
<?php $con=mysql_connect("localhost","root","") or die("Failed to connect with database!!!!");
mysql_select_db("student", $con); 
// The Chart table contains two fields: weekly_task and percentage
// This example will display a pie chart. If you need other charts such as a Bar chart, you will need to modify the code a little to make it work with bar chart and other charts
$sth = mysql_query("SELECT * FROM marks where name='jas'");

/*
---------------------------
example data: Table (Chart)
--------------------------
marks     percentage
English           30
Maths             40
Science            44
*/

$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(

    // Labels for your chart, these represent the column titles
    // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
    array('label' => 'subject', 'type' => 'string'),
    array('label' => 'marks', 'type' => 'number')

);

$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $temp = array();
    // the following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $r['subject']); 

    // Values of each slice
    $temp[] = array('v' => (int) $r['marks']); 
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>

//加载可视化API和piechart包。
load('visualization','1',{'packages':['corechart']});
//将回调设置为在加载Google Visualization API时运行。
//setOnLoadCallback(drawChart);
功能绘图图(对象){
//使用从服务器加载的JSON数据创建我们的数据表。
var data=newgoogle.visualization.DataTable(对象);
变量选项={
标题:“测试API”,
is3D:'正确',
宽度:200,
身高:100
};
//实例化并绘制图表,传入一些选项。
//别忘了检查你的部门ID
var chart=new google.visualization.ColumnChart(document.getElementById('chart_div'));
图表绘制(数据、选项);
}
函数show()
{
xmlhttp=新的XMLHttpRequest();
open(“GET”,“getdata.php?name=jaspreet”,true);
xmlhttp.send();
xmlhttp.onreadystatechange=getResponse;
}
函数getResponse()
{
if(xmlhttp.readyState==4){
警报(xmlhttp.responseText);
var obj=JSON.parse(xmlhttp.responseText);
绘图图(obj);
}
}
测试
测试1
测试2
getData.php

 <html>
  <head>
    <!--Load the Ajax API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

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

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

    function drawChart(object) {

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(object);
      var options = {
           title: 'Test API',
          is3D: 'true',
          width: 200,
          height: 100
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }

    function show()
    {

        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET","getdata.php?name=jaspreet",true);
        xmlhttp.send();
        xmlhttp.onreadystatechange = getResponse;
    }
    function getResponse()
    {
        if(xmlhttp.readyState==4){
            alert(xmlhttp.responseText);
            var obj = JSON.parse(xmlhttp.responseText);
            drawChart(obj);
        }
    }
    </script>
  </head>

  <body>
    <!--this is the div that will hold the pie chart-->
    <div id="chart_div"></div>
    <select id="name" onchange="show();">
        <option value="test">test</option>
        <option value="test1">test1</option>
        <option value="test2">test2</option>
    </select>
  </body>
</html>
<?php $con=mysql_connect("localhost","root","") or die("Failed to connect with database!!!!");
mysql_select_db("student", $con); 
// The Chart table contains two fields: weekly_task and percentage
// This example will display a pie chart. If you need other charts such as a Bar chart, you will need to modify the code a little to make it work with bar chart and other charts
$sth = mysql_query("SELECT * FROM marks where name='jas'");

/*
---------------------------
example data: Table (Chart)
--------------------------
marks     percentage
English           30
Maths             40
Science            44
*/

$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(

    // Labels for your chart, these represent the column titles
    // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
    array('label' => 'subject', 'type' => 'string'),
    array('label' => 'marks', 'type' => 'number')

);

$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $temp = array();
    // the following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $r['subject']); 

    // Values of each slice
    $temp[] = array('v' => (int) $r['marks']); 
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>

我知道你的帖子是一个“答案”,但我想我会插话的。如果您希望动态地将数据输入到Google图表中,那么只需使用PHP将数据回送到javascript中即可。php可用于从服务器或mysql表获取信息

以下是一个例子:

    <?php   $i = 0; $grab = mysql_query("SELECT * FROM `productList` WHERE 1");
    $pricelist = mysql_fetch_array($grab);
    $numberofproducts = mysql_num_rows($grab);

                              ?>       
    <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([
      ['parts', 'Prices'],
      ['Number of Products',  <?php echo $numberofproducts;?>],

    ]);

    var options = {
      title: 'Number of Products',
      hAxis: {title: '', titleTextStyle: {color: 'red'}},
                width: 980,
                height: 200
    };

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

load(“可视化”、“1”、{packages:[“corechart”]});
setOnLoadCallback(drawChart);
函数绘图图(){
var data=google.visualization.arrayToDataTable([
[“零件”、“价格”],
[‘产品数量’,],
]);
变量选项={
标题:“产品数量”,
hAxis:{title:'',titleTextStyle:{color:'red'}},
宽度:980,
身高:200
};
var chart=new google.visualization.ColumnChart(document.getElementById('chart_div'));
图表绘制(数据、选项);
}

这不是问题。这是一个解决办法。我一直在寻找这个。在得到stackoverflow的帮助后,这项功能得以实现。所以我想把我的工作代码发布给其他人。@Daan我相信JassJava不是在问问题,而是在展示他们发现的问题的解决方案。如果是这样的话,那么最好是以问题的形式发布原始帖子,然后以答案的形式发布他们的解决方案。有关详细信息,请参阅。谢谢。我真的很感激。我会处理好的。