Google multiline bar chart using mySQL db data

I am going through a bit of training to create a small database that supports reporting for my company.

The goal is to draw a multi-line chart using google charts based on mysql database.

I was able to get the data to echo from the mysql database, but it didn't produce a chart. All I get is echo and blank space where the diagram should be. Echo is displayed for debugging purposes.

Here is the code:

<?php include 'confile.php';

$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-03-02' ORDER BY time ASC";
$result = $conn->query($qry);

if($result === FALSE) {
    echo mysql_errno($result) .": ". mysql_error($result) ."/n";
    die(mysql_error());
}

$rows = array();
$table = array();
$table['cols'] = array(
                        array('label' => 'Time', 'type' => 'datetime'),
                        array('label' => 'Probe 1', 'type' => 'number'),
                        array('label' => 'Probe 2', 'type' => 'number'),
                        array('label' => 'Probe 3', 'type' => 'number'),
                        array('label' => 'Probe 4', 'type' => 'number')
                        );

while($r = mysqli_fetch_assoc($result)) {

    $temp = array();
    $temp[] = array($r['time']);

    $temp[] = array($r['p1']);
    $temp[] = array($r['p2']);              
    $temp[] = array($r['p3']);
    $temp[] = array($r['p4']);

    $rows[] = array('c' => $temp);  
}

$table['rows'] = $rows;

$jsonTable = json_encode($table);
echo $jsonTable;
?>
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></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.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = new google.visualization.DataTable(<?$jsonTable?>);
        var options = {
            title: 'Recorded Temperatures',
            legend: {position: 'bottom' },
            width: 800,
            height: 600
        }; 

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

    </script>
  </head>
  <body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>
  </body>
</html>

      

And this is the exit "echo"

{"cols":[{"label":"Time","type":"datetime"},{"label":"Probe 1","type":"number"},{"label":"Probe 2","type":"number"},{"label":"Probe 3","type":"number"},{"label":"Probe 4","type":"number"}],"rows":[{"c":[["03:02:07"],["270.26"],["298.40"],["111.54"],["228.06"]]},{"c":[["03:28:42"],["273.23"],["190.43"],["245.69"],["283.21"]]},{"c":[["07:26:04"],["144.33"],["217.26"],["206.53"],["167.68"]]},{"c":[["12:13:20"],["153.15"],["277.23"],["167.20"],["240.88"]]}]}

      

This is test data using test query on db. Once I understand the formatting for rendering the chart, it will be a setting to allow the user to choose which date to view, etc.

This was the closest existing question I can find, but doesn't seem to answer the question.

Failed to create google chart using MySQL table data as data source


Following @MickMackusa's answer, I was able to hack this together to get it working, ensuring that the mysql / php array was output in a way that suits google charts.

Thanks to @MickMacUSA for the help.

The last working code is below.

<?php include 'confile.php';

$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-04-16' ORDER BY time ASC";
$result = $conn->query($qry);

if($result === FALSE) {
    echo mysqli_errno($result) .": ". mysqli_error($result) ."/n";
    die(mysqli_error());
}
    $i = 0; //iteration counter - start at 0

    $totalRows = mysqli_num_rows($result); // we need this to know when to change the output
    $targetRows = $totalRows - 1; //row indies start from 0, not 1.

    foreach ($result as $row){ 

        $comTime = str_replace(":",",",$row['time']); // for each row, remove the : and put , in its place
        if ($targetRows == $i) { // if the index is the same value as the target (ie, it the last row)...

            $temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."]". PHP_EOL;
            } else {
            $temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."],". PHP_EOL;
            }
        $i = $i + 1; 
        $rows[] = $temp; 
    }

 $table = $rows;
 $data = implode($table); //format the table as a single string, with line returns

//echo $i;
//echo $data;

?>
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  </head>
  <body>
    <div id="chart" style="width: 900px; height: 500px"></div>

    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart(){
        var data = new google.visualization.DataTable();
            data.addColumn('timeofday','Time'); 
            data.addColumn('number','Probe 1');
            data.addColumn('number','Probe 2');
            data.addColumn('number','Probe 3');
            data.addColumn('number','Probe 4');

            data.addRows([              
                <?php echo $data; ?> //dump the result into here, as it correctly formatted   
            ]);

        var options = {
            title: 'Recorded Temperatures',
            legend: { position: 'bottom' },
            width: 900,
            height: 500,
            hAxis: { format: 'hh:mm:ss' }
        }; 

    var chart = new google.visualization.LineChart(document.getElementById('chart'));
      chart.draw(data, options);    
      }
    </script>
  </body>
</html>

      

+3


source to share


1 answer


Your numeric values ​​must be formatted differently and you want timeofday

not datetime

.

According to: https://developers.google.com/chart/interactive/docs/reference#dataparam

Format your data like this:

{cols:
    [
        {"label":"Time","type":"timeofday"},
        {"label":"Probe 1","type":"number"},
        {"label":"Probe 2","type":"number"},
        {"label":"Probe 3","type":"number"},
        {"label":"Probe 4","type":"number"}
    ],
rows:
    [
        {c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
        {c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
        {c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
        {c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
    ]
}

      

And you have to repeat it in javascript:

changes:

<?$jsonTable?>

      

in

<?php echo $jsonTable; ?>  

      



And put your javascript code block just before the tag </body>

.

This is a complete working code using the above data format that I tested on my server:

<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>

    <script type="text/javascript">
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart(){
        var data = new google.visualization.DataTable(
            {cols:[
                {"label":"Time","type":"timeofday"},
                {"label":"Probe 1","type":"number"},
                {"label":"Probe 2","type":"number"},
                {"label":"Probe 3","type":"number"},
                {"label":"Probe 4","type":"number"}
            ],
            rows:[
                {c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
                {c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
                {c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
                {c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
            ]
        });

        var options = {
            title: 'Recorded Temperatures',
            legend: { position: 'bottom' },
            width: 900,
            height: 500,
            hAxis: { format: 'hh:mm:ss' }
        };

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
        chart.draw(data, options);   
    }
    </script>
</body>
</html>

      

This is an alternative format that will be simpler / clearer / easier to create / understand using your mysqli results:

<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>

    <script type="text/javascript">
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart(){
        var data = new google.visualization.DataTable();
            data.addColumn('timeofday','Time');
            data.addColumn('number','Probe 1');
            data.addColumn('number','Probe 2');
            data.addColumn('number','Probe 3');
            data.addColumn('number','Probe 4');
        data.addRows([
            [[03,02,07],270.26,298.40,111.54,228.06],
            [[03,28,42],273.23,190.43,245.69,283.21],
            [[07,26,04],144.33,217.26,206.53,167.68],
            [[12,13,20],153.15,277.23,167.20,240.88]
        ]);

        var options = {
            title: 'Recorded Temperatures',
            legend: { position: 'bottom' },
            width: 900,
            height: 500,
            hAxis: { format: 'hh:mm:ss' }
        };

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
        chart.draw(data, options);   
    }
    </script>
</body>
</html>

      


See the SO demo provided by WhiteHat :

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart', 'table']
});

function drawChart() {
  var data = new google.visualization.DataTable({cols: [
      {"label":"Time","type":"timeofday"},
      {"label":"Probe 1","type":"number"},
      {"label":"Probe 2","type":"number"},
      {"label":"Probe 3","type":"number"},
      {"label":"Probe 4","type":"number"}
    ],
    rows: [
      {c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
      {c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
      {c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
      {c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
    ]
  });

  var table = new google.visualization.Table(document.getElementById('chart_0'));
  table.draw(data);

  var options = {
      title: 'Recorded Temperatures',
      legend: {position: 'bottom' },
      width: 800,
      height: 600,
      hAxis: {
        format: 'hh:mm:ss'
      }
  };
  var chart = new google.visualization.LineChart(document.getElementById('chart_1'));
  chart.draw(data, options);
}
      

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_0"></div>
<div id="chart_1"></div>
      

Run codeHide result


+2


source







All Articles