简体   繁体   中英

Creating Pie char from mysql database using php and google charts

I am trying to create a pie char for my database table.

temp -> with columns(id, sent, pcount, ncount)

pcount and ncount are int numbers. I want to create a pie chart for this two values.

I am trying to load this file.

<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>

graphData.php content is the following.

<?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);
?>

I have taken this code from web and modified as per my need. When I load my first PHP page, it shows nothing. What am I doing wrong?

I have taken this code from web and modified as per my need. When I load my first PHP page, it shows nothing. What am I doing wrong?

You obviously have modified the script wrongly and not to your needs. Otherwise you wouldn't be asking what you're doing wrong.

As asking "What am I doing wrong?" implies you do not understand the code incl. your modifications, the first thing you need to do is to step back to the last working version of the code.

So commit your changes now and then diff your script to the last working commit. This will show you your changes and it's often much more easier to spot the part where you introduced the error.

Here is the code to create PIE chart(Just change function name for other charts) from my sql table in PHP.

Important thing to remember is

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

ind_type and sum are the column in my table, first var should be string here.

<?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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM