I have the following bit of code that draws graphs, in a loop, using google.visualisation based on values from a SQL table which I store in 3 arrays(i.e. $TotalView
, $TotalFemaleView
and $TotalMaleView
) in the PHP portion. I use json_encode(referred this link) so I can use these arrays in JavaScript. But I am unable to access the array elements to draw the graphs. I have tried displaying the values of the arrays and they are correct.
<?php
$servername = "localhost";
$username = "root";
$password = "root123";
$dbname = "test";
$AdName=[];
$TotalView=[];
$TotalMaleView=[];
$TotalFemaleView=[];
$rowcount=0;
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$result=mysqli_query($con,"SELECT `Ad Name`,`Total View Count`, `Total Female Viewers`, `Total Male Viewers` FROM `addata` WHERE `Disp Id`=1");
$rowcount=mysqli_num_rows($result);
if(!$result) {
die('Could not get data: ' . mysql_error());
}
// output data of each row
for($x = 0; $x < $rowcount; $x++)
{
$row = $result->fetch_assoc();
$TotalView[$x]=$row["Total View Count"];
$TotalFemaleView[$x]=$row["Total Female Viewers"];
$TotalMaleView[$x]=$row["Total Male Viewers"];
$AdName[$x]=$row["Ad Name"];
}
$con->close();
?>
<html>
<body>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<ul id="stats"></ul>
<script type="text/javascript">
var array1 = <?php echo json_encode($TotalView);?>;
var array2 = <?php echo json_encode($TotalFemaleView);?>;
var array3 = <?php echo json_encode($TotalMaleView);?>;
var array4 = <?php echo json_encode($AdName);?>;
google.charts.load('current',
{ callback: function ()
{
for ( y = 0; y < <?php echo $rowcount ?>; y++)
{
var data = new google.visualization.DataTable();
data.addColumn('string', 'list');
data.addColumn('number', 'Viewers');
data.addRows([
['TotalViewers',array1[y]],
['Female Viewers', array2[y]],
['Male Viewers', array3[y]]
]);
var options = {title:array4[y],width:400,height:300};
var container = document.getElementById('stats').appendChild(document.createElement('div'));
var chart = new google.visualization.ColumnChart(container);
chart.draw(data, options);
}
},
packages: ['corechart']
});
</script>
</body>
</html>
Can anyone point me towards the right direction?