Go to app/Controllers and create a controller file
<?php namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
class GooglePie extends Controller
{
public function index() {
$db = \Config\Database::connect();
$builder = $db->table('users');
$query = $builder->query("SELECT COUNT(id) as count,MONTHNAME(created_at) as month_name FROM users WHERE YEAR(created_at) = '" . date('Y') . "'
GROUP BY YEAR(created_at),MONTH(created_at)");
$query1 = $builder->query("SELECT COUNT(id) as count,YEAR(created_at) as year FROM users
GROUP BY YEAR(created_at)");
$data['month_wise'] = $query->getResult();
$data['year_wise'] = $query1->getResult();
return view('home',$data);
}
}
<!Doctype html>
<html>
<head>
<title>Codeigniter 4 Google Pie Chart Month and Year Wise Tutorial Tutsmake.com</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('visualization', "1", {
packages: ['corechart']
});
</script>
</head>
<body>
<div class="row">
<div class="col-md-12">
<div id="month_pie" style="width: 900px; height: 500px; margin: 0 auto"></div>
<div id="year_pie" style="width: 900px; height: 500px; margin: 0 auto"></div>
</div>
</div>
</body>
</html>
Go to implement javascript code for showing a data on google bar chart. Now we will put the code on script tag after the closing of body tag.
<script language="JavaScript">
/* Draw the pie chart for registered users month wise */
google.charts.setOnLoadCallback(monthWiseChart);
/* Draw the pie chart for registered users year wise */
google.charts.setOnLoadCallback(yearWiseChart);
/* for month wise */
function monthWiseChart() {
/* Define the chart to be drawn.*/
var data = google.visualization.arrayToDataTable([
['Month', 'Users Count'],
<?php
foreach ($month_wise as $row){
echo "['".$row->month_name."',".$row->count."],";
}
?>
]);
var options = {
title: 'Month Wise Registered Users Of Current Year <?php echo date("Y")?>',
is3D: true,
};
/* Instantiate and draw the chart.*/
var chart = new google.visualization.PieChart(document.getElementById('month_pie'));
chart.draw(data, options);
}
/* for year wise */
function yearWiseChart() {
/* Define the chart to be drawn.*/
var data = google.visualization.arrayToDataTable([
['Year', 'Users Count'],
<?php
foreach ($year_wise as $row){
echo "['".$row->year."',".$row->count."],";
}
?>
]);
var options = {
title: 'Year Wise Registered Users Pie Chart',
is3D: true,
};
/* Instantiate and draw the chart.*/
var chart = new google.visualization.PieChart(document.getElementById('year_pie'));
chart.draw(data, options);
}
</script>