Reputation: 11
<?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.
Upvotes: 1
Views: 157
Reputation: 61275
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(*)']
Upvotes: 1