I want to show employee data in pie chart. I'm able to make pie chart using jQuery and php. But demand is that in a page there are 12 button. Name Jan to Dec.
When user click on feb then pie chart of feb is shown to user. When click on dec the pie chart of dec. is shown to user.
In my database there is a date column where date is stored like 2015-06-23
I'm not able to get logic of SQL query here is my code but it need improvements.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows
([
<?php
$servername = "localhost";
$username = "root";
$dbname = "dat_database";
$password = "";
$conn = new mysqli($servername, $username, $password, $dbname);
$EMP_ID = 'MMUM254';
$sql = "SELECT typeof_task,hourspend from emp_dat_info where EMP_ID='" . $EMP_ID. "' ORDER BY date DESC LIMIT 10 " ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$a[] = "['" . $row["typeof_task"] . "', " . $row["hourspend"] . "]";
}
echo implode(', ', $a);
}
?>
]);
// Set chart options
var options = {'title':'How Much Hours You Spend',
'width':900,
'height':500};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
<?php echo date("Y"); ?>
`
You can try month clause in your code to get only month data
$sql = "SELECT typeof_task,hourspend
FROM emp_dat_info
WHERE EMP_ID='" . $EMP_ID. "'
ORDER BY MONTH(date) DESC LIMIT 10 " ;
$result = $conn->query($sql);
If you want to get the full name of the month then you can try MONTHNAME clause in the query. Pass the date in the MONTHNAME clause.
$sql = "SELECT typeof_task,hourspend
FROM emp_dat_info
WHERE EMP_ID='" . $EMP_ID. "'
ORDER BY MONTHNAME(date) DESC LIMIT 10 " ;
$result = $conn->query($sql);
For more reference you can visit this link : https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_month
Try MONTH with date
$sql = "SELECT typeof_task,hourspend
FROM emp_dat_info
WHERE EMP_ID='" . $EMP_ID. "'
ORDER BY MONTH(date) DESC LIMIT 10 " ;
$result= $conn->query($sql);
Related
Is there a way to count the duplicate data from mysql and
display it to a bar chart, Im trying to make a attendance report
using morris bar chart.
here my sample code:
<html >
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
</head>
<body>
<div id="chart"></div>
</body>
</html>
here is my php code:
<?php
$connect = mysqli_connect("localhost", "root", "", "sa");
$query = "SELECT year, count(*) as course FROM test group by year,course order by year ASC ";
$result = mysqli_query($connect, $query);
$chart_data = '';
while($row = mysqli_fetch_array($result))
{
$chart_data .= "{ year:'".$row["year"]."', course:".$row["course"]."}, ";
}
$chart_data = substr($chart_data, 0, -2);
?>
and this is my javascript:
<script>
Morris.Bar({
element : 'chart',
data:[<?php echo $chart_data; ?>],
xkey:'year',
ykeys:['course','course','course','course','course'],
labels:['BSIT','BSHRM','BSCS','BSTM','ABCOMM'],
hideHover:'auto',
xLabelAngle: '60',
verticalGrid: true,
resize:true,
barColors: ['red','blue','green','yellow','black'],
gridTextSize: 12
});
</script>
this is my database:
UPDATED: and this is my output so far:
as you can see in my output all courses have same value for example
the two 2018-07-12 the output should be based on my database is for BSIT = 3
the rest is zero value same with the other 2018-07-12 the output should be BSHRM =1 and the rest is zero value, is there a way to achieve that?, Hope you can help me.
You have two problems with your query:
First, the alias COUNT(*) AS course reuses the column name as the alias. You need to give it a different name.
Second, you left course out of the grouping, so you're combining the counts of all courses in your results.
It should be:
$query = "SELECT year , course , count(*) as count FROM test group by year, course order by year ASC ";
Each course will then be in a different row of the results, you'll need to regroup when you process the results.
You also shouldn't create JSON by concatenating strings. Put the results in an array and use json_encode().
$results = array();
while ($row = mysqli_fetch_assoc($result)) {
$results[$row['year']]['year'] = $row['year'];
$results[$row['year']][$row['course']] = $row['count'];
}
$chart_data = json_encode(array_values($results));
This method uses the course names as the keys in the JSON, not course1, course2, etc. So you need to change
ykeys:['course','course','course','course','course'],
to:
ykeys:['BSIT','BSHRM','BSCS','BSTM','ABCOMM'],
The JSON in $chart_data already includes the square brackets around the array, so you don't need to add it around the echo. Use:
data: <?php echo $chart_data; ?>,
I am trying to use a MySQL TimeStamp for the X Axis on a Scatter graph using Google Charts. Currently, the only way I have managed to get the graph displaying it using the strtotime() Function. This confuses the graph or me as strtotime() Function shows a number of seconds from 1st Jan 1970.
new Date(2017-03-07 02:03:12)] YYYY-MM-DD HH:ii:SS this is the format of the date coming from my timestamp if I leave it like this then I get the error. only if I change the time to the strtotime() this works. But the Graph does not show the time properly. Is there another way to display the timestamp. As the Documentation on google does not make much sense.
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Distance');
data.addColumn('datetime', 'time');
data.addRows([
<?php
$query = "SELECT * FROM iot_sensors WHERE Sensor_ID ='Ultra_Dist'";
$execute = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($execute)){
$date = strtotime($row['Time_Stamp']);
echo "[".$row['Sensor_1'].", new Date(".$date.")],";
$Trimmed = trim($row['Time_Stamp']);
//echo $Trimmed;
}
?>
]);
var options = {
width: 800,
height: 500,
chart: {
title: 'Frequency of movement by time',
subtitle: 'Frequency of movement'
},
hAxis: {title: 'Distance'},
vAxis: {title: 'time'}
};
This is my code which retrieves the Time_Stamp and other value from my table and puts it in an array for the chart to use.
<?php
$query = "SELECT * FROM iot_sensors WHERE Sensor_ID ='Ultra_Dist'";
$execute = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($execute)){
$date = ($row['Time_Stamp']);
$date2 = new DateTime($date);
$date3 = date_format($date2, 'Y,m,d,H,i,s');
echo "[new Date(".$date3."),".$row['Sensor_1']."],";
}
?>
Put the date in a new Date() object then reformat it to the accepted format and then echo the date in the array.
I'm very new to dashboard stuffs.Learning PHP & javascript. I'm trying to create a pie-chart with the help of already available google-chart. I could able to make it (Because, data is hard coded). I'm trying same to plot the pie-chart with dynamic values (querying to DB & plot the values on pie-chart). I'm trying to do it, but couldn't. Could you please help me to achieve this (MySQL, say 2 columns Name & Score).
Working code [For static data]:
<html>
<head>
<script type="text/javascript" src="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', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);**
var options = {
title: 'My Daily Activities'
};
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 understand above highlighted part does the work of loading static data.
Tried embedding above script with db related PHP. Probably, i might be missing to call it in right way. Could you please help me to provide the missing interface. I'm very new to all these technologies.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbName = "test";
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * FROM student";
$result = $conn->query($query);
$jsonArray = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['Name'];
$jsonArrayItem['value'] = $row['Scores'];
array_push($jsonArray, $jsonArrayItem);
}
}
$conn->close();
header('Content-type: application/json');
echo json_encode($jsonArray);
?>
Intoduction
Ok, if your code works correctly I suppose currently you have made a php script that spits out a JSON document in the format you need.
Now you need to actually load the data with javascript and feed it into the charting API.
So instead of feeding the hardcoded array at var data = google.visualization.arrayToDataTable you need to load it from the php script.
Have a look at the following links that solve this problem either with pure JS or with JQuery:
How to get JSON from URL in Javascript?
http://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript
Example with JQuery
Keep in mind calls are asynchronous so you need to have your charting logic triggered in ( or by ) the listener that handles the ajax call.
$.getJSON('http://localhost/myApp/myScript.php&callback', function(data) {
var data = google.visualization.arrayToDataTable(data);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});
I've been trying to retrieve data from mysql database using SELECT Count, as I got a list of countries which I want to count how many times each country is displayed in the column SovereignState, to a Google Geo Chart and by browsing around, I believe that json_encode should do the trick.
However, I have no idea how to get make a json_encode from my php code and then put it in the DataTable of the chart.
This is the php code:
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASSWORD','');
define('DB_HOST', '');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) ;
if ($conn->connect_error) {
die ('Could not connect: ' . $conn->connect_error);
}
$sql = "SELECT SovereignState, COUNT(*) FROM Data_2 GROUP BY SovereignState";
echo $sql;
//$result = $conn->query($sql);
$result = $conn->multi_query($sql);
if(!$result) {
echo "Could not successdully run query ($sql) from DB: " . mysql_error(); exit;
}
echo "<pre>";
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s - %s\n", $row[0], $row[1]);
}
$result->free();
}
} while ($conn->more_results());
echo "</pre>";
$conn->close();
And this is the html code of the google geochart:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["geochart"]});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Number'],
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
You can use json_encode() from your PHP code and use Ajax in order to get the JSON into your JS code.
Also, (not recommended) you can just call a PHP function from your JS code with <?php myFunction();?>, that function should return an echo json_encode().
I am trying to create a drill down, using Fusionchart and PHP from a MySQL database. I have worked over every error and now there are no errors but I still don't see my chart.
Please can someone tell my what could be the problem with my code. Below is are the code for the project starting with the link from the parent page.
$strXML .= "<set name = '".$row['Day']."' value = '".$row['TotOutput']."' link='" . urlencode("Detailed.php?Day=" . $row['Day']) . "'/>";
<?php
//We have included ../Includes/FusionCharts.php and ../Includes/DBConn.php, which contains
//functions to help us easily embed the charts and connect to a database.
include("Includes/FusionCharts.php");
include("Includes/DBConn.php");
?>
<HTML>
<HEAD>
<TITLE> FusionCharts XT - Database and Drill-Down Example </TITLE>
<SCRIPT LANGUAGE="Javascript" SRC="../../FusionCharts/FusionCharts.js"></SCRIPT>
</HEAD>
<BODY>
<?php
//This page is invoked from Default.php. When the user clicks on a pie
//slice in Default.php, the factory Id is passed to this page. We need
//to get that factory id, get information from database and then show
//a detailed chart.
//First, get the factory Id
//Request the factory Id from Querystring
$day = $_GET['Day'];
//Connect to database
$link = connectToDB();
//$strXML will be used to store the entire XML document generated
//Generate the chart element string
$strXML = "<graph caption='Peak Electricity Generated ---- for month April 2015' xAxisName='Day' yAxisName='MegaWatts' decimalPrecision='0' formatNumberScale='0' yaxismaxvalue='1000' showNames='1' rotateNames='1'>";
//Now, we get the data for that plant
$strQuery = "select plant_id, peak_generation from daily_report where pdate=" . $day;
$result = mysql_query($strQuery) or die(mysql_error());
//Iterate through each factory
if ($result) {
while($ors = mysql_fetch_array($result)) {
$strQuery = "plant_name from power_plant where plant_id=" . $ors['plant_id'];
$result2 = mysql_query($strQuery) or die(mysql_error());
$ors2 = mysql_fetch_array($result2);
//Here, we convert date into a more readable form for set label.
$strXML .= "<set name = '".$ors2['plant_name']."' value = '".$ors['peak_generation']."'/>";
}
}
mysql_close($link);
//Close <chart> element
$strXML .="</graph>";
//Create the chart - Column 2D Chart with data from $strXML
echo renderChart("charts/FCF_Line.swf", "", $strXML, "Daily Output", 1300, 500);
?>
</CENTER>
</BODY>
</HTML>