Dilanga Thalpegama Dilanga Thalpegama - 4 months ago 35
PHP Question

How to get mysql data into a google chart using php loop?

I've created a Google chart and I've added data taken from the database itself. When getting data through php loops though, I have had some difficulty because I couldn't amend that data to the chart because of its syntax.

This is as far as I have gone. I need to get the mysql values in place of:

1170, 460, 45, 123, 456],
660, 1120, 145, 785, 658]

var data = google.visualization.arrayToDataTable([
['Term', <?php

while ($getchartrows = mysql_fetch_array($getchart))
{
echo " ' " . $getchartrows['std_ID'] . " ' " . ",";
}

?>],

<?php


$one = mysql_query("SELECT * FROM stusitting WHERE std_ID = '0001' AND subjectNo = '$subin' AND grade = '$gradein' AND termNo = '$tcheck' ");
$getone = mysql_fetch_array($one);

?>

['01', <?php echo $getone ['marks']; ?>, 400, 495, 565, 415],
['02', 1170, 460, 45, 123, 456],
['03', 660, 1120, 145, 785, 658]
]);




var options = {
title: 'Class Progress'
};

Answer

Try to tackle one problem after the other. First, get the data you need from the database. Then, create the data structure you need in PHP, and convert it to JavaScript using json_encode(). Finally, pass it to the visualization function in JavaScript:

<?php
// query data
$result = mysql_query(...);

// format data structure
$data = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
    $i += 1;
    array_push($data, array($i) + $row);
}

// convert to JavaScript
?>
var raw_data = <?php echo json_encode($data) ?>;

// visualize
var data = google.visualization.arrayToDataTable(raw_data);
Comments