使用php和google图表从mysql数据库创建饼图字符

使用php和google图表从mysql数据库创建饼图字符,php,json,graph,google-visualization,Php,Json,Graph,Google Visualization,我正在尝试为我的数据库表创建一个饼图字符 temp -> with columns(id, sent, pcount, ncount) pcount和ncount是整数。我想为这两个值创建一个饼图 我正在尝试加载此文件 <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text

我正在尝试为我的数据库表创建一个饼图字符

temp -> with columns(id, sent, pcount, ncount)
pcount
ncount
是整数。我想为这两个值创建一个饼图

我正在尝试加载此文件

<html>
<head>

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

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

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

var options = {'title':'Ticket Sales',
'width':500,    
'height':400};

// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options); 
}
</script>
</head>

<body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
</body>


</html>

load(“可视化”、“1”、{packages:[“corechart”]});
setOnLoadCallback(drawChart);
函数绘图图()
{
var jsonData=$.ajax({
url:“graphData.php”,
数据类型:“json”,
异步:false
}).responseText;
//使用从服务器加载的JSON数据创建我们的数据表。
var data=新的google.visualization.DataTable(jsonData);
var options={'title':'ticketsales',
“宽度”:500,
‘高度’:400};
//实例化并绘制图表,传入一些选项。
var chart=new google.visualization.ColumnChart(document.getElementById('chart_div'));
图表绘制(数据、选项);
}
php的内容如下

<?php

$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: ".mysqli_connect_error();
}

$sql = "SELECT pcount,count(*) AS count from temp";

if ($result=mysqli_query($con,$sql))
{
    $rownum=mysqli_num_rows($result);
    printf("Result set has %d rows.\n",$rownum);
    mysqli_free_result($result);
}

//start the json data in the format Google Chart js/API expects to receieve it
$data = array('cols' => array(array('label' => 'pcount', 'type' => 'int'),
                              array('label' => 'mcount', 'type' => 'int')),
              'rows' => array());

while($row = mysqli_fetch_row($result)) {
    $data['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}    

echo json_encode($data);
?>

我已经从网上取得了这段代码,并根据我的需要进行了修改。当我加载第一个PHP页面时,它没有显示任何内容。我做错了什么

我已经从网上取得了这段代码,并根据我的需要进行了修改。当我加载第一个PHP页面时,它没有显示任何内容。我做错了什么

显然,您错误地修改了脚本,不符合您的需要。否则你就不会问自己做错了什么

由于询问“我做错了什么?”意味着您不理解代码(包括您的修改),您需要做的第一件事是返回到代码的最后一个工作版本

因此,现在提交您的更改,然后将您的脚本与最后一次工作提交区分开来。这将向您显示您的更改,并且通常更容易发现引入错误的部分

我已经从网上取得了这段代码,并根据我的需要进行了修改。当我加载第一个PHP页面时,它没有显示任何内容。我做错了什么

显然,您错误地修改了脚本,不符合您的需要。否则你就不会问自己做错了什么

由于询问“我做错了什么?”意味着您不理解代码(包括您的修改),您需要做的第一件事是返回到代码的最后一个工作版本


因此,现在提交您的更改,然后将您的脚本与最后一次工作提交区分开来。这将显示您所做的更改,并且通常更容易发现您引入错误的部分。

以下是从PHP中的我的sql表创建饼图(只更改其他图表的函数名)的代码

重要的是要记住

array('label' => 'ind_type', 'type' => 'string'),
    array('label' => 'sum', 'type' => 'number')
ind_type和sum是我的表中的列,这里的第一个变量应该是string

<?php
/*
Script  : PHP-JSON-MySQLi-GoogleChart
Author  : Enam Hossain
version : 1.0

*/

/*
--------------------------------------------------------------------
Usage:
--------------------------------------------------------------------

Requirements: PHP, Apache and MySQL

Installation:

  --- Create a database by using phpMyAdmin and name it "chart"
  --- Create a table by using phpMyAdmin and name it "googlechart" and make sure table has only two columns as I have used two columns. However, you can use more than 2 columns if you like but you have to change the code a little bit for that
  --- Specify column names as follows: "weekly_task" and "percentage"
  --- Insert some data into the table
  --- For the percentage column only use a number

      ---------------------------------
      example data: Table (googlechart)
      ---------------------------------

      weekly_task     percentage
      -----------     ----------

      Sleep           30
      Watching Movie  10
      job             40
      Exercise        20     


*/

  /* Establish the database connection */
 // $mysqli = new mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');

/*  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  } */

  $mysqli =mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: ".mysqli_connect_error();
}

   /* select all the weekly tasks from the table googlechart */
  $result = $mysqli->query('SELECT * FROM new_temp');

  /*
      ---------------------------
      example data: Table (googlechart)
      --------------------------
      Weekly_Task     percentage
      Sleep           30
      Watching Movie  10
      job             40
      Exercise        20       
  */



  $rows = array();
  $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 Slice title
    */

    array('label' => 'ind_type', 'type' => 'string'),
    array('label' => 'sum', 'type' => 'number')

);
    /* Extract the information from $result */
    foreach($result as $r) {

      $temp = array();

      // The following line will be used to slice the Pie chart

      $temp[] = array('v' => (string) $r['ind_type']); 

      // Values of the each slice

      $temp[] = array('v' => (int) $r['sum']); 
      $rows[] = array('c' => $temp);
    }

$table['rows'] = $rows;

// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;


?>


<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() {

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(<?=$jsonTable?>);
      var options = {
           title: 'Index analysis',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

  <body>
    <!--this is the div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

//加载可视化API和piechart包。
load('visualization','1',{'packages':['corechart']});
//将回调设置为在加载Google Visualization API时运行。
setOnLoadCallback(drawChart);
函数绘图图(){
//使用从服务器加载的JSON数据创建我们的数据表。
var data=new google.visualization.DataTable();
变量选项={
标题:“指数分析”,
is3D:'正确',
宽度:800,
身高:600
};
//实例化并绘制图表,传入一些选项。
//别忘了检查你的部门ID
var chart=new google.visualization.PieChart(document.getElementById('chart_div');
图表绘制(数据、选项);
}

以下是在PHP中从我的sql表创建饼图(只需更改其他图表的函数名)的代码

重要的是要记住

array('label' => 'ind_type', 'type' => 'string'),
    array('label' => 'sum', 'type' => 'number')
ind_type和sum是我的表中的列,这里的第一个变量应该是string

<?php
/*
Script  : PHP-JSON-MySQLi-GoogleChart
Author  : Enam Hossain
version : 1.0

*/

/*
--------------------------------------------------------------------
Usage:
--------------------------------------------------------------------

Requirements: PHP, Apache and MySQL

Installation:

  --- Create a database by using phpMyAdmin and name it "chart"
  --- Create a table by using phpMyAdmin and name it "googlechart" and make sure table has only two columns as I have used two columns. However, you can use more than 2 columns if you like but you have to change the code a little bit for that
  --- Specify column names as follows: "weekly_task" and "percentage"
  --- Insert some data into the table
  --- For the percentage column only use a number

      ---------------------------------
      example data: Table (googlechart)
      ---------------------------------

      weekly_task     percentage
      -----------     ----------

      Sleep           30
      Watching Movie  10
      job             40
      Exercise        20     


*/

  /* Establish the database connection */
 // $mysqli = new mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');

/*  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  } */

  $mysqli =mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: ".mysqli_connect_error();
}

   /* select all the weekly tasks from the table googlechart */
  $result = $mysqli->query('SELECT * FROM new_temp');

  /*
      ---------------------------
      example data: Table (googlechart)
      --------------------------
      Weekly_Task     percentage
      Sleep           30
      Watching Movie  10
      job             40
      Exercise        20       
  */



  $rows = array();
  $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 Slice title
    */

    array('label' => 'ind_type', 'type' => 'string'),
    array('label' => 'sum', 'type' => 'number')

);
    /* Extract the information from $result */
    foreach($result as $r) {

      $temp = array();

      // The following line will be used to slice the Pie chart

      $temp[] = array('v' => (string) $r['ind_type']); 

      // Values of the each slice

      $temp[] = array('v' => (int) $r['sum']); 
      $rows[] = array('c' => $temp);
    }

$table['rows'] = $rows;

// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;


?>


<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() {

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(<?=$jsonTable?>);
      var options = {
           title: 'Index analysis',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

  <body>
    <!--this is the div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

//加载可视化API和piechart包。
load('visualization','1',{'packages':['corechart']});
//将回调设置为在加载Google Visualization API时运行。
setOnLoadCallback(drawChart);
函数绘图图(){
//使用从服务器加载的JSON数据创建我们的数据表。
var data=new google.visualization.DataTable();
变量选项={
标题:“指数分析”,
is3D:'正确',
宽度:800,
身高:600
};
//实例化并绘制图表,传入一些选项。
//别忘了检查你的部门ID
var chart=new google.visualization.PieChart(document.getElementById('chart_div');
图表绘制(数据、选项);
}

为什么要使用ajax进行此操作?将值直接发送到饼图函数。@Zia:您能告诉我需要做哪些更改吗?我真的很抱歉不知道在这里删除ajax!为什么要使用ajax呢?将值直接发送到饼图函数。@Zia:您能告诉我需要做哪些更改吗?我真的很抱歉不知道在这里删除ajax!我同意你的观点,但是之前的代码是使用json文件来完成的,我没有json文件,而且我也不熟悉它@卡里姆汗:如果你选择修改的例子太复杂,你无法使用,请使用另一个你能理解的例子。修改我经常不理解的代码结果并不好。我要么开始理解它,要么惨败。我想这也和其他人一样。我同意你的观点,但是之前的代码使用json文件来做这些事情,我没有json文件,而且我也不熟悉它@卡里姆汗:如果你选择修改的例子太复杂,你无法使用,请使用另一个你能理解的例子。修改我经常不理解的代码结果并不好。我要么开始理解它,要么惨败。我想这也和其他人一样。