I've to show a Google Chart in a loop . Without loop my chart works fine but when i try to add it in a loop i get it only for first iterataion , how do i fix it , please review this
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Daily Report'],
['Points Achieved', <?php echo $points_achieved?>],
['Points Left', <?php echo $points_left?>]
]);
var options = {
backgroundColor: 'transparent',
title: '' ,
chartArea:{right:0,top:0,width:"90%",height:"100%" }
,height: 150
,width: 200,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<?php
$sql= "SELECT * FROM employees";
$query= mysqli_query($connection, $sql);
while($res= mysqli_fetch_assoc($query)): ?>
<div id='piechart'></div>
//other data from database comes here
<?php endwhile;?>
Since you are drawing multiple charts i would suggest to modify drawChart function to accept chart id and data as parameters:
function drawChart(chartId,data) {
var dataTable = google.visualization.arrayToDataTable(data);
var options = {
backgroundColor: 'transparent',
title: '' ,
chartArea:{right:0,top:0,width:"90%",height:"100%" },
height: 150
,width: 200,
};
var chart = new google.visualization.PieChart(document.getElementById(chartId));
chart.draw(dataTable, options);
}
Then you could iterate PHP array and invoke drawChart function:
<?php
foreach ($reports as $key => $report) {
$chartId = "piechart_$key";
//prepare chart data
$chartData = array(
array("Task", "Daily Report"),
array("Points Achieved" , $report["Points Achieved"]),
array("Points Left" , $report["Points Left"])
);
?>
<div id='<?php echo $chartId; ?>'></div>
<script type="text/javascript">drawChart('<?php echo $chartId; ?>',<?php echo json_encode($chartData); ?>)</script>
<?php
}
?>
It is assumed $reports array has the following structure:
//input data example ( replace it with data retrieved from DB)
$reports = array(
"R1" => array("Points Achieved" => 20, "Points Left" => 4),
"R2" => array("Points Achieved" => 40, "Points Left" => 14),
"R3" => array("Points Achieved" => 10, "Points Left" => 0)
);
Working example
Related
Good day to everyone, I am trying to display a barchart that show the count of 2 different attribute with the name 'Feedback' VS 'Complain' and these two attribute are based on user selection.
I have followed some tutorial to create a Json file to same the data retrieve from mysql then to be display on the bar chart. So this is the data.php that receives the data based on query
<?php
//setting header to json
header('Content-Type: application/json');
$mysqli = mysqli_connect('localhost','root','','customercaremodule');
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query1 = sprintf("SELECT FC_Category FROM fbcomplain where FC_Category ='Feedback'");
$Countsql1 = "SELECT count(FC_ID) AS total FROM fbcomplain WHERE FC_Category ='Feedback'";
//execute query
$result1 = $mysqli->query($query1);
$res1 = mysqli_query($mysqli,$Countsql1);
$value1 = mysqli_fetch_assoc($res1);
$feedbackrowcount = $value1['total'];
//loop through the returned data
$data1 = array();
foreach ($result1 as $row) {
$data1[] = $row;
}
//free memory associated with result
$result1->close();
//query to get data from the table
$query2 = sprintf("SELECT FC_Category FROM fbcomplain where FC_Category ='Complain'");
$Countsql2 = "SELECT count(FC_ID) AS total FROM fbcomplain WHERE FC_Category ='Complain'";
//execute query
$result2 = $mysqli->query($query2);
$res2 = mysqli_query($mysqli,$Countsql2);
$value2 = mysqli_fetch_assoc($res2);
$complainrowcount = $value2['total'];
//loop through the returned data
$data2 = array();
foreach ($result2 as $row) {
$data2[] = $row;
}
//free memory associated with result
$result2->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data1);
print json_encode($data2);
print json_encode($feedbackrowcount);
print json_encode($complainrowcount);
?>
Then here is the script function I am facing a lot of challenge with. I am very new to Chart JS and PHP in general, if there's any security flaw please bear with me. THANK YOU FOR ANY KIND HELPERS
$(document).ready(function(){
$.ajax({
url: "http://localhost/customercare/data.php",
method: "GET",
success: function(data1) {
console.log(data1);
var feedback = [];
var complain = [];
for(var i in data1) {
feedback.push(data1[i].$feedbackrowcount);
}
success: function(data2) {
console.log(data2);
var feedback = [];
var complain = [];
for(var i in data2) {
feedback.push(data2[i].$complainrowcount);
}
var chartdata = {
datasets : [
{
label: 'Feedback',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: feedback
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data1) {
console.log(data1);
}
});
});
you can try to push in feedback an object, for example :
var bar_chart_obj_1 = {data: data1[i].$feedbackrowcount, label: "data1", id: 0};
feedback.push(bar_chart_obj_1);
var bar_chart_obj_2 = {data: $data2[i].$complainrowcount, label: "data2", id: 1};
feedback.push(bar_chart_obj_2);
I am trying to populate a chart via the ChartJS plugin with data from my MySQL database, but while doing so I am running into a
mysqli_fetch_assoc(): Couldn't fetch mysqli_result in ...
error.Since I am using json_encode I tried to adjust the fetch array but cant seem to figure this one out.
Any help would be much appreciated.
<div class="box-body">
<div class="chart">
<canvas id="canvas_bar" style="height:250px"></canvas>
<?php
// Start MySQLi connection
$db = new MySQLi($dbhost,$dbuser,$dbpass,$dbname);
if ($db->connect_errno) { echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error; }
// count all records per month
$sql = "SELECT LOWER(MONTHNAME(mod_date)) AS mdate, count(*) AS cnt FROM qci_modreport GROUP BY LOWER(MONTHNAME(mod_date))";
if (!($result)) {
print "ERROR, something wrong with the query.";
} else {
$output = array();
while ($row = mysqli_fetch_assoc($result)) {
$output[$row['mdate']] = $row['cnt'];
}
print (json_encode($output));
}
?>
<!-- chartJS 1.0.1-->
<!-- <script src="./plugins/chartjs/Chart.js"></script> -->
<script src="../../plugins/chartjs/Chart.min.js"></script>
<script>
var barChartData = {
labels: <?php echo json_encode(array_keys($output)); ?>,
datasets: [
{
fillColor: "#03586A", //rgba(151,187,205,0.5)
strokeColor: "#03586A", //rgba(151,187,205,0.8)
highlightFill: "#066477", //rgba(151,187,205,0.75)
highlightStroke: "#066477", //rgba(151,187,205,1)
data: <?php echo json_encode(array_values($output)); ?>
}]
};
$(document).ready(function () {
new Chart($("#canvas_bar").get(0).getContext("2d")).Bar(barChartData, {
tooltipFillColor: "rgba(51, 51, 51, 0.55)",
responsive: true,
barDatasetSpacing: 6,
barValueSpacing: 5
});
});
</script>
</div>
</div>
<!-- /.box-body -->
$result is not defined. You should use
if (!($result = $db->query($sql1))) { ...
or
$result = $db->query($sql1);
and only after you do
if (!$result) { ...
and
while ($row = mysqli_fetch_assoc($result)) { ...
How do i show multiple database entries in loop ? So that it looks like this:
But with multiple markers.
I'm not able to loop javascript in php to show multiple markers. Is it possible to do so?
dataProvider: {
map: "worldLow",
images: [
<?php include ('query.php');
while($row= mysql_fetch_array($fetch)){
$cty = $row['city'];
$lat = $row['lati'];
$lon = $row['longi'];
}?>
{
zoomLevel: 5,
scale: 0.5,
title: "<?php echo $cty;?>",
latitude: <?php echo $lon;?>,
longitude: <?php echo $lat;?>
}]
}
I advise you to use json_encode function so as to avoid problems with extra quotes and other symbols:
dataProvider: {
map: "worldLow",
<?php include ('query.php');
// store all markers here
$markers = array();
while ($row= mysql_fetch_array($fetch)) {
// add new marker data
$markers[] = array(
'zoomLevel' => 5,
'scale' => 0.5,
'title' => $row['city'],
'latitude' => $row['lati'],
'longitude' => $row['longi'],
);
}?>
images: <?=json_encode($markers)?>
}
For further debugging - use developers console and/or see rendered javascript.
I am generating a chart from fetching data in my MYSQL database. The JavaScript library I am using is Fusion Charts Suite XT. I have tried the following code which only renders one chart from one single query on a page. I am having trouble rendering another chart on the same HTML page.
<html>
<head>
<script type="text/javascript" src="../fusioncharts/js/fusioncharts.js"></script>
<script type="text/javascript" src="../fusioncharts/js/themes/fusioncharts.theme.zune.js"></script>
<?php
include('assets/global/plugins/fusioncharts/fusioncharts.php');
include('resource/dashboard/rank_chart.php'); ?>
</head>
<body>
<div id="chart-1"></div>
</body>
</html>
This is the code inside the fusioncarts.php include in the page.
<?php
class FusionCharts {
private $constructorOptions = array();
private $constructorTemplate = '
<script type="text/javascript">
FusionCharts.ready(function () {
new FusionCharts(__constructorOptions__);
});
</script>';
private $renderTemplate = '
<script type="text/javascript">
FusionCharts.ready(function () {
FusionCharts("__chartId__").render();
});
</script>
';
// constructor
function __construct($type, $id, $width = 400, $height = 300, $renderAt, $dataFormat, $dataSource) {
isset($type) ? $this->constructorOptions['type'] = $type : '';
isset($id) ? $this->constructorOptions['id'] = $id : 'php-fc-'.time();
isset($width) ? $this->constructorOptions['width'] = $width : '';
isset($height) ? $this->constructorOptions['height'] = $height : '';
isset($renderAt) ? $this->constructorOptions['renderAt'] = $renderAt : '';
isset($dataFormat) ? $this->constructorOptions['dataFormat'] = $dataFormat : '';
isset($dataSource) ? $this->constructorOptions['dataSource'] = $dataSource : '';
$tempArray = array();
foreach($this->constructorOptions as $key => $value) {
if ($key === 'dataSource') {
$tempArray['dataSource'] = '__dataSource__';
} else {
$tempArray[$key] = $value;
}
}
$jsonEncodedOptions = json_encode($tempArray);
if ($dataFormat === 'json') {
$jsonEncodedOptions = preg_replace('/\"__dataSource__\"/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
} elseif ($dataFormat === 'xml') {
$jsonEncodedOptions = preg_replace('/\"__dataSource__\"/', '\'__dataSource__\'', $jsonEncodedOptions);
$jsonEncodedOptions = preg_replace('/__dataSource__/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
} elseif ($dataFormat === 'xmlurl') {
$jsonEncodedOptions = preg_replace('/__dataSource__/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
} elseif ($dataFormat === 'jsonurl') {
$jsonEncodedOptions = preg_replace('/__dataSource__/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
}
$newChartHTML = preg_replace('/__constructorOptions__/', $jsonEncodedOptions, $this->constructorTemplate);
echo $newChartHTML;
}
// render the chart created
// It prints a script and calls the FusionCharts javascript render method of created chart
function render() {
$renderHTML = preg_replace('/__chartId__/', $this->constructorOptions['id'], $this->renderTemplate);
echo $renderHTML;
}
}
?>
Inside the rank_chart.php file.
<?php
require_once('database.php');
// Form the SQL query that returns.
$strQuery = "SELECT `rank_code`, COUNT(*) AS rank_cnt FROM `personel` WHERE rank_code!='' GROUP BY rank_code ORDER BY rank_code='2/LT',rank_code='LT',rank_code='CAPT',rank_code='MAJOR',rank_code='LT COL',rank_code='COL',rank_code='BRIG',rank_code='MAJ GEN',rank_code='LT GEN'";
// Execute the query, or else return the error message.
$result = $conn->query($strQuery);
// If the query returns a valid response, prepare the JSON string
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption"=> "",
"xAxisname"=> "Officer Ranks",
"yAxisName"=> "Number of Personnel",
"plotFillAlpha"=> "80",
"paletteColors"=> "#0075c2,#0e948c",
"baseFontColor"=> "#333333",
"baseFont"=> "Helvetica Neue,Arial",
"captionFontSize"=> "14",
"subcaptionFontSize"=> "14",
"subcaptionFontBold"=> "0",
"showBorder"=> "0",
"bgColor"=> "#ffffff",
"showShadow"=> "0",
"canvasBgColor"=> "#ffffff",
"canvasBorderAlpha"=> "0",
"divlineAlpha"=> "100",
"divlineColor"=> "#999999",
"divlineThickness"=> "1",
"divLineIsDashed"=> "1",
"divLineDashLen"=> "1",
"divLineGapLen"=> "1",
"usePlotGradientColor"=> "0",
"showplotborder"=> "0",
"valueFontColor"=> "#ffffff",
"placeValuesInside"=> "1",
"showHoverEffect"=> "1",
"rotateValues"=> "1",
"showXAxisLine"=> "1",
"xAxisLineThickness"=> "1",
"xAxisLineColor"=> "#999999",
"showAlternateHGridColor"=> "0",
"legendBgAlpha"=> "1",
"legendBorderAlpha"=> "0",
"legendShadow"=> "0",
"legendItemFontSize"=> "10",
"legendItemFontColor"=> "#666666"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result)) {
array_push($arrData["data"], array(
"label" => $row["rank_code"],
"value" => $row["rank_cnt"]
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
/*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is ` FusionCharts("type of chart", "unique chart id", width of the chart, height of the chart, "div id to render the chart", "data format", "data source")`. Because we are using JSON data to render the chart, the data format will be `json`. The variable `$jsonEncodeData` holds all the JSON data for the chart, and will be passed as the value for the data source parameter of the constructor.*/
$columnChart = new FusionCharts("column2d", "Rank Chart" , "100%", "100%", "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
// Close the database connection
}
?>
i'm trying to make line chart in laravel using google chart and get data from database mysql.
Question:
how can i passing variable $bmi and $visits in data.addRows? so that i can showing the data using line chart.
here my code (php):
public function graphBmi($childName){
$name = DB::table('tm_child')->select('Child_Name')->distinct()
->where('Child_ID', 'LIKE', '%' . $childName . '%')->first();
$visit = DB::table('tm_Child')
->join('tr_visit', 'tm_child.Child_ID', '=', 'tr_visit.Child_ID')
->where('tr_visit.Child_ID', 'LIKE', '%' . $childName . '%')
->select('Visit_Date', 'tr_visit.Child_ID', 'Bmi_anak')
->distinct()->get();
if (!is_null($visit)) {
$visits = [];
$bmi = [];
$data[0] = array('day','counts');
foreach ($visit as $tgl) {
array_push($visits, $tgl->Visit_Date);
array_push($bmi, $tgl->Bmi_anak);
}
}
// return $visit;
echo json_encode($bmi); //number
echo json_encode($visits); //date visit
return View::make('ProfilAnak.BmiAnak.seeBmi')->with('visits',$visits)->with('bmi',$bmi);
}
here script for showing the chart
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
<script>
google.load('visualization', '1', {packages: ['corechart', 'line']});
google.setOnLoadCallback(drawBackgroundColor);
function drawBackgroundColor() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Visit');
data.addColumn('number', 'X');
data.addRows([
[new Date{{$visits}},{{$bmi}}]
]);
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Popularity'
},
backgroundColor: '#f1f8e9'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>