简体   繁体   中英

Google Pie charts from custom mysqli query

I was trying to implement google charts using php, mysqli. I want to make a Pie chart with 3 slices for a Lesson-Activity and the 3slices are the three columns : count(<50%), count(Between 50-60%), count(>60%). I tried searching with different program, tried from different possibilities from my end, but couldn't get with this kind of requirement. I couldn't add more than two columnns in my code.

Requirement : I was looking for a Pie chart with lesson_activity showing all the three columns: cond1, cond2 and cond3 (in one piechart).

I came to stack overflow to share my code with high qualified developers.

Kindly share your suggestions.

TABLE : lesson_grades

id            lesson           lesson_activity   count(<50%)   count(Between 50-60%)   count(>60%)
5      Community Health Care        CHC.001            9                 7                   2
5      Community Health Care        CHC.002            2                 5                   6
5      Community Health Care        CHC.003            9                 2                   0
13     Spaceship                    SS.001             1                 13                  7
3      Risk Analysis                RA.001             1                 13                  7
3      Risk Analysis                RA.002             1                 9                   0
3      Risk Analysis                RA.003             1                 3                   4
3      Risk Analysis                RA.004             0                 7                   21
3      Risk Analysis                RA.005             0                 30                  11
15     Community Qualifications     CA.001             1                 13                  32

CODE

<?php

  $DB_NAME = 'lessons';
  $DB_HOST = 'localhost';
  $DB_USER = '---';
  $DB_PASS = '---';

  $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

  if (mysqli_connect_errno()) 
  {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  }
$sql = $mysqli->query('SELECT id, lesson, lesson_activity, count(<50%) AS cond1, count(Between 50-60%) AS cond2, count(>60%) AS cond3  FROM lesson_grades');

$rows = array();
$flag = true;

$table = array();

$table['cols'] = array(
  array('label' => 'lesson_activity', 'type' => 'string'),
  array('label' => 'cond1', 'type' => 'number'),
  array('label' => 'cond2', 'type' => 'number'),
  array('label' => 'cond3', 'type' => 'number'),
);

$rows = array();
while($r = mysqli_fetch_assoc($sql)) 
{
    $temp = array();
    $temp[] = array('v' => (string) $r['lesson_activity']); 
    $temp[] = array('v' => $r['cond1'], $r['cond2'], $r['cond3']); 
    $rows[] = array('c' => $temp);
}

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

?>

<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.8.2/jquery.min.js"></script>
    <script type="text/javascript">

    google.load('visualization', '1', {'packages':['corechart']});

    google.setOnLoadCallback(drawChart);

    function drawChart() 
    {
      var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
      var options = 
      {
           title: 'My Weekly Plan',        
           legend: 'none',        
           slices: {0: {color: 'black'}, 1: {color: 'red'}} 
      };     
      var chart = new google.visualization.PieChart(document.getElementById('piechart'));
      chart.draw(data, options);
    }
    </script>
  </head>
  <body><div id="piechart" style="width:500px;height:500px;"></div></body>   
  </html>

I'm sure someone will give you a pure javascript version, but here is a class that works with php that will auto-generate the javascript if you are interested. If not the bottom most code is the output to try:

Library:

Update: https://github.com/rasclatt/PHP-to-Google-PieCharts-Converter

<?php
    class   GoogleCharts
        {
            public      $newArr;
            public      $VarName;
            public      $DataArray;
            public      $options;

            protected   $id;
            protected   $compiler;
            protected   $chartType;

            const   PIE     =   'pie';
            const   SCATTER =   'scatter';

            public  function __construct()
                {
                    $this->options      =   array("title"=>"Untitled");
                    $this->chartType    =   'pie';
                }

            function CreatePie($settings = false)
                {
                    if(!is_array($settings))
                        return;

                    $data           =   (!empty($settings['data']))? $settings['data']:false;
                    $this->id       =   (!empty($settings['id']))? $settings['id']:false;
                    $incr           =   (!empty($settings['incr']))? $settings['incr']:false;

                    $this->VarName  =   "";
                    $this->newArr   =   array();

                    if($data != false && $this->id != false) {
                            foreach($data as $key => $value) {
                                    $dvalue         =   (is_numeric($value))? $value:"'{$value}'";
                                    $key            =   (is_numeric($key))? $key:"'{$key}'";
                                    $this->newArr[] =   "\t\t\t\t\t[{$key}, {$dvalue}]";
                                }
                        }

                    $this->VarName  =   "DataSet{$incr}";

                    if(!empty($this->newArr)) {
                            $str    =   PHP_EOL."var {$this->VarName}   =   [".PHP_EOL;
                            $str    .=  implode(",".PHP_EOL,$this->newArr).PHP_EOL;
                            $str    .=  "\t\t\t\t]".PHP_EOL;
                        }

                    $this->DataArray    =   (!empty($str))? $str:false;

                    return $this;
                }

            public  function ChartData()
                {
                    $str    =   (!empty($this->DataArray))? $this->DataArray:"";
                    $str    .=  PHP_EOL;

                    return $str;
                }

            protected   function MakeJSObjects($arr)
                {
                    if(is_array($arr)) {            
                            foreach($arr as $k => $v) {
                                        $return[$k] =   $k.': '.$this->MakeJSObjects($v);
                                }
                        }
                    else {
                            $arr    =   (is_numeric($arr) || $arr === 'true' || $arr === 'false')? $arr: "'$arr'";
                            $return =   (strpos($arr,'{') !== false && strpos($arr,'}') !== false)? trim($arr,"'") : $arr;
                        }

                    return (is_array($return))? '{ '.PHP_EOL."\t".implode(",\t".PHP_EOL."\t",$return).PHP_EOL.' }' : $return;
                }

            public  function ChartOptions($opts)
                {
                    if(!is_array($opts))
                        return $this;

                    $this->options  =   "\t\tvar options =".$this->MakeJSObjects($opts).";";

                    return $this;
                }

            public  function ChartInstance()
                {
                    $str    =   (!empty($this->VarName))? "drawChart({$this->VarName},'{$this->id}');":"";
                    $str    .=  PHP_EOL;

                    return $str;
                }

            public  function CreateJavascript($settings = false)
                {
                    $library    =   (!empty($settings['lib']))? $settings['lib']:false;
                    $wrap       =   (!empty($settings['wrap']))? $settings['wrap']:false;
                    $wrap       =   (!empty($settings['data']) && is_array($settings['data']))? $settings['data']:array();

                    if($library)
                        $comp[] =   '<script type="text/javascript" src="https://www.google.com/jsapi?autoload={\'modules\':[{\'name\':\'visualization\',\'version\':\'1.1\',\'packages\':[\'corechart\']}]}"></script>'.PHP_EOL;

                    if($wrap)
                        $comp[] =   '<script type="text/javascript">'.PHP_EOL;

                    $comp[] =   '
google.load("visualization", "1", {packages:["corechart"]});
// Let the callback run a function
google.setOnLoadCallback(function() {';

                    for($i = 0; $i < count($settings['data']); $i++) {
                            $comp[] =   $settings['data'][$i].PHP_EOL;
                        }
                    $comp[] =   '
    });

// Give the function some arguments, first is data, second id
// You could do a third for the options attribute
function drawChart(ArrayElem,IdElem)
    {
        var data = google.visualization.arrayToDataTable(ArrayElem);'.PHP_EOL;
        if(!empty($this->options))
            $comp[] =   $this->options;

        $comp[] =   '

        var chart = new google.visualization.'.$this->chartType.'(document.getElementById(IdElem));

        chart.draw(data, options);
    }';

                    if($wrap)
                        $comp[] =   PHP_EOL.'</script>'.PHP_EOL;

                    return implode("",$comp);
                }
            public  function ChartKind($type = 'pie')
                {
                    switch($type) {
                            case('scatter'):
                                $this->chartType    =   'ScatterChart';
                                break;
                            default:
                                $this->chartType    =   'PieChart';
                        }

                    return $this;
                }
        }
?>

To use:

<html>
<head>
<?php
// Settings for the first chart
// This is so you can make multiple charts
$settings["incr"]           =   1;
// Id name for the chart (where to put the chart)
$settings["id"]             =   "piechart".$settings["incr"];
$settings["data"]["Task"]   =   "Lessons/Activity";

//**********************************//
// Your numbers from your db go here
//**********************************//
$settings["data"]['count(<50%)']            =   7;
$settings["data"]['count(Between 50-60%)']  =   3;
$settings["data"]['count(>60%)']            =   6;
//**********************************//
//**********************************//

// Create instance of GoogleCharts class
$Googlizer  =   new GoogleCharts();
// Create the pie chart
$Googlizer->CreatePie($settings);
// Save the instance of the js data array
$chart1_data    =   $Googlizer->ChartData();
// Save the instance of the js function
$chart1_inst    =   $Googlizer->ChartInstance();
// Write the whole shebangle to the page
echo $Googlizer ->ChartOptions(array("title"=>"My Weekly Plan","legend"=>"none"))
                ->ChartKind(GoogleCharts::PIE)
                ->CreateJavascript(array("data"=>array($chart1_data, $chart1_inst),"wrap"=>true,"lib"=>true));
?>
</head>
<body>
    <div id="piechart1" style="width: 900px; height: 500px;"></div>
</body>
</html>

Gives you:

<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

google.load("visualization", "1", {packages:["corechart"]});
// Let the callback run a function
google.setOnLoadCallback(function() {
var DataSet1   =   [
                    ['Task', 'Lessons/Activity'],
                    ['count(<50%)', 7],
                    ['count(Between 50-60%)', 3],
                    ['count(>60%)', 6]
                ]


drawChart(DataSet1,'piechart1');


    });

// Give the function some arguments, first is data, second id
// You could do a third for the options attribute
function drawChart(ArrayElem,IdElem)
    {
        var data = google.visualization.arrayToDataTable(ArrayElem);
        var options = {
            title: 'My Weekly Plan',
            legend: 'none'
        };


        var chart = new google.visualization.PieChart(document.getElementById(IdElem));

        chart.draw(data, options);
    }
</script>
</head>
<body>
    <div id="piechart1" style="width: 900px; height: 500px;"></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