1

I am using google charts (on a php webpage) with data from an sql DB. The problem i am having is that it is not display the field names and values properly it simply displays the value of the first field "expense". It should be showing two fields "expense" and "income" with the values in the db. Any ideas what i am doing wrong ?

my code below:

<?php

$dbhandle = new mysqli('localhost','root','','useraccounts');
echo $dbhandle->connect_error;

$query = "SELECT * FROM ctincome";
$res = $dbhandle->query($query);
?>


<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([
      ['expense','income'],
  <?php 
  while($row=$res->fetch_assoc())

  {
      echo "['".$row['expense']."','".$row['income']."'],";
  }

  ?>
    ]);

    var options = {
      title: 'Expenses to Income',
      pieHole: 0.4,
    };

    var chart = new 
   google.visualization.PieChart(document.getElementById
   ('donutchart'));
    chart.draw(data, options);
   }
   </script>
   </head>
   <body>
   <div id="donutchart" style="width: 900px; height: 500px;"></div>
   </body>
   </html>
WhiteHat
  • 59,912
  • 7
  • 51
  • 133
Nunes
  • 9
  • 2
  • Have a look at this link, it might help you. https://stackoverflow.com/questions/2970936/how-to-echo-out-table-rows-from-the-db-php – Madonado Apr 08 '19 at 09:40

2 Answers2

0

the values for the income column should be numbers, not strings.

remove the single quotes from the second column.

from...

echo "['".$row['expense']."','".$row['income']."'],";

to...

echo "['".$row['expense']."',".$row['income']."],";
WhiteHat
  • 59,912
  • 7
  • 51
  • 133
0

I have three suggestions based on my experience in crossbrowser or javascript bugs I solved.

First point : You are just echoing, you need to use concatenation.

<?php 
  $data = '';
  while($row=$res->fetch_assoc())

  {
      $data .= "['".$row['expense']."','".$row['income']."'],";
  }

  ?>

 var data = google.visualization.arrayToDataTable([
      ['expense','income'],
      <?php echo $data; ?>
    ]);

second point : In javascript last comma may or may not work, its best to not to append comma if it's a last row.

var data = google.visualization.arrayToDataTable([
      ['expense','income'],
  <?php 
  while($row=$res->fetch_assoc())

  {
      if(last row )
       $data .= "['".$row['expense']."','".$row['income']."']";
       else  $data .= "['".$row['expense']."','".$row['income']."'],";
  }

  ?>
    ]);

third suggestion : check data type of var data before and after the concatenation

Mangesh Sathe
  • 1,987
  • 4
  • 21
  • 40