I have a table called end_users. I am showing number of registered users per month of current year. I fetch the data from database and show data from January to December of current year in a bar chart form. For example, current year is 2019, thus the bar chart will show how many users registered each month of 2019.
What I want to do is show past year data based on year input given users rather than showing just current year. The idea is the user will choose year from drop down list and pass that year into the sql query.
My model
public function registered_user_graph(){
//This query fetch number of registered users from jan to dec of current year
$query = $this->db->query('SELECT (DATE_FORMAT(created_at,"%M")) AS "Month", COUNT(*) AS Number_of_registered_users FROM end_users WHERE year(created_at)= year(CURRENT_DATE) GROUP BY (DATE_FORMAT(created_at,"%M")) ORDER BY "Month" ASC');
if($query->num_rows() > 0){
return $query->result_array();
}else
return false;
}
My view
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<?php
$userPoints = array();
foreach ($userschart as $key => $value) {
$userPoints[$key]['label'] = $value['Month'];
$userPoints[$key]['y'] = $value['Number_of_registered_users'];
}
?>
<script type="text/javascript">
//for chart and graph
window.onload = function () {
//Chart of monthly registered user data
var charts = new CanvasJS.Chart("user_container", {
animationEnabled: true,
exportEnabled: true,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{
text: "Monthly registered Users"
},
data: [{
type: "column", //change type to bar, line, area, pie, etc
//indexLabel: "{y}", //Shows y value on all Data Points
indexLabelFontColor: "#5A5757",
indexLabelPlacement: "outside",
dataPoints: <?php echo json_encode($userPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
charts.render();
}
</script>
I don't think controller is need but just in case, here is my controller
//Looping monthly registered users data got from model
$userschart = $this->dashboard_model->registered_user_graph();
$monthlyusers = array();
foreach($userschart as $row){
$monthlyusers[] = $row;
}
$this->data['userschart'] = $monthlyusers;
$this->template->admin_render('admin/dashboard/index',$this->data);
Try this, add past year to $userInput
function registered_user_graph($userInput = "") {
if(empty($userInput)) {
$userInput = date("Y");
}
//This query fetch number of registered users from jan to dec of current year
$query = $this->db->query('SELECT (DATE_FORMAT(created_at,"%M")) AS "Month", COUNT(*) AS Number_of_registered_users FROM end_users WHERE year(created_at)= ' . $userInput . ' GROUP BY (DATE_FORMAT(created_at,"%M")) ORDER BY "Month" ASC');
if($query->num_rows() > 0){
return $query->result_array();
}else
return false;
}