1
<?php
include('classes/DB.php');
$male = DB::query('SELECT COUNT(*) AS MTOTAL FROM users WHERE gender=\'male\';');
$female = DB::query('SELECT COUNT(*) AS FTOTAL FROM users WHERE gender=\'female\';');
?>

<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', 'Number of Male and Female visitors'],
            ['Male', <?php while ($s = $male->fetch()) {echo $s ['count(*)'];}?>],
            ['Female', <?php while ($s = $female->fetch()) {echo $s ['count(*)'];}?>],
            ]);
            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>

I would like to know why i get empty data. When I call echo json_encode($male) and json_encode($female), I have true values. In this case I have one male user and three female user in my database so i see output as [{"MTOTAL":"1","0":"1"}] [{"FTOTAL":"3","0":"3"}]. I would like to know why i cant fetch these values in script.

WhiteHat
  • 59,912
  • 7
  • 51
  • 133
PBD
  • 11
  • 2
  • You can surround your query in `"` so that you don't have to escape `'` – hungrykoala May 03 '18 at 00:44
  • `fetch()) {echo $s ['count(*)'];}?>` Try to add this below `$female = DB::query` and see if it results to any error. Also enable erros by following this [guide](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) – hungrykoala May 03 '18 at 00:46
  • i got this error , Undefined index: COUNT(*) – PBD May 03 '18 at 14:59

1 Answers1

1

in your query, your naming the count result column using the AS keyword...

SELECT COUNT(*) AS MTOTAL
SELECT COUNT(*) AS FTOTAL

use the name to reference the column in the recordset...

use this...

$s ['MTOTAL']
$s ['FTOTAL']

instead of...

$s ['count(*)']
WhiteHat
  • 59,912
  • 7
  • 51
  • 133
  • I have tried this aswell. I found that problem is about the way i connect to database i think. I tried mysqli_query , $query = "SELECT gender, COUNT(*) as number FROM users GROUP BY gender"; and $result =mysqli_query($connect,$query); and inside script while($row=mysqli_fetch_array($result)) { echo "['".$row["gender"]."',".$row ["number"]."],"; } – PBD May 03 '18 at 20:03
  • They are pretty much the same but i wasn't able to fetch the data somehow. But yea mysqli_query solved that – PBD May 03 '18 at 20:09