Any one method either MySQLi ( Above code ) or PDO ( Below code ) is to be used to collect data and create the JavaScript array. Both scripts are avaialble inside zip file at the end of this page.
require "config-pdo.php";// Database connection
$query="SELECT id, name,class,mark,gender FROM student";
$step=$dbo->prepare($query);
if($step->execute()){
$php_data_array=$step->fetchAll();
echo "<script>
var my_2d=".json_encode($php_data_array)."
</script>";
}
2 : Data array in PHP
Before displaying records in a table we have created an array in PHP ( $php_data_array). While displaying the records in a table we store each record inside the PHP array.
$php_data_array[] = $row; // Adding to array
After displaying all the records in a table we have the $php_data_array with all the data collected from MySQL table. We can display the Json string like this.
echo json_encode($php_data_array);
3 : Transferring data from PHP to JavaScript to create the chart
Once the php aray $php_data_array is created the rest of the code remain same. Here we are reading the student.csv file to create the $php_data_array. Once the array is created same code can be used. Zip file below contains the student.csv file as data source and the index-csv.php file to display the chart.
We used fgetcsv() to read csv file
$f_pointer=fopen("student.csv","r"); // file pointer
$php_data_array = Array(); // create PHP array
while(! feof($f_pointer)){
$ar=fgetcsv($f_pointer);
if (strlen($ar[0])>0) { // to remove last line
//echo print_r($ar); // print the array
$php_data_array[] = $ar; // Adding to array
}
}
//print_r($php_data_array);
echo "<script>
var my_2d=".json_encode($php_data_array)."
</script>";