<html> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'], <?php $query = "SELECT name, score FROM `Users` order by score desc limit 5"; $result = mysqli_query($conn, $query); if ($result->num_rows > 0) { while($row = mysqli_fetch_array($result)) { echo "['".$row['name']."', '".$row['score']."'],"; } } ?> ]); var options = { title: 'My Daily Activities' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script> </head> <body> <div id="piechart" style="width: 900px; height: 500px;"></div> </body> </html>
What is wrong with my code? i have read that my values are stored as string so that the chart is showing 100% other.
How do i make it work? i tried with (int)$var
PHP function, but that does not make it work yet..
while($row = mysqli_fetch_array($result)) { $score = $row['score']; $int = (int)$score; echo "['".$row['name']."', '".$row['score']."'],"; } }
Advertisement
Answer
Do not generate json by yourself. Use json_encode
always:
<?php $query = "SELECT name, score FROM `Users` order by score desc limit 5"; $result = mysqli_query($conn, $query); $chartData = [ ['Task', 'Hours per Day'], ]; if ($result->num_rows > 0) { while($row = mysqli_fetch_array($result)) { $chartData[] = [$row['name'], $row['score']]; } }?> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable(<?php echo json_encode($chartData)?>); var options = { title: 'My Daily Activities' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script>