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; ?>,
Related
I want to display a score coming from my database through a json dataset (from the table "score"), which works fine, but my quiz_id is the foreign key, which means the dataset will contain the id, and not the name of the quiz. Which doesn't look good on the CanvasJS graph. The quiz_name is located in the quiz table, with the primary key quiz_id. How would i make the json dataset include the quiz_name instead of quiz_id?
my test.php, which is creating the json:
<?php
header('Content-Type: application/json');
$con = mysqli_connect("123.123.123.123", "Seba0702", "", "kayeetdb");
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM score");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['quiz_id'] , "y" => $row['quiz_score']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
My tables:
Quiz Table:
Score Table:
I want the json to include the quiz_name and quiz_score.
For retrieve infor from another table you need a join
SELECT score.quiz_id, score.student_id, score.quiz_score, quiz.name
FROM score
INNER JOIN quiz on quiz.quiz_id = score.quiz_id
I have the following the html/php code :
<!DOCTYPE html>
<html>
<head>
<title>Voiture</title>
</head>
<body>
Welcome<br>
<form method="post" action="">
Liste de voiture<select name="selected" id="selected">
<?php
$sql = 'select Type from voiture';
$result = $conn->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
if(!in_array($row['Type'], $json)){
$json[] = $row['Type'];
echo '<option name = "'.$row['Type'].'">'.$row['Type'].'</option>';
}
}
?>
</select> <br>
<span id="sel" name="sel"></span>
<table border="1">
<tr id="header">
<td>Type</td>
<td>Model</td>
<td>Couleur</td>
<td>Prix</td>
<td>User</td>
<td>Action</td>
</tr>
</table>
<input type="submit" name="submit" hidden>
</form>
<script src="jquery-3.2.1.js"></script>
<script>
$(function(){
$('#selected').on('change',function(){
$('#sel').text(document.getElementById('selected').value);
$.getJSON('phpVoiture.php',function(data){
for (var x = 0 ; x < data.length ; x++){
$('<tr><td>'+data[x]['type']+'</td>'+'<td>'+data[x]['Model']+
'</td><td>'+data[x]['Couleur']+'</td>'+
'<td>'+data[x]['Prix']+'</td>'+'<td></td></tr>').insertAfter($('#header'));
}
});
});
});
</script>
</body>
</html>
And the following php page :
<?php
require_once ('./dbConnect.php');
include ('./Voiture.php');
$sel = $_POST['selected'];
$conn = mysqli_connect(servername, username, password, db ,port);
$query = "select * from voiture where Type = '".sel."'";
$result = mysqli_query($conn, $query);
$json = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$json[] = [
'type' => $row['Type'],
'model' => $row['Model'],
'couleur' => $row['Couleur'],
'prix' => $row['Prix']
];
}
}
else{
echo mysqli_num_rows($result);
}
echo json_encode($json);
The problem is that when I select an option in the drop down list nothing happens. I want the query in the second php page to select the cars that have the type that I selected in the drop down list. I tried troubleshooting by echo an alert in both pages that have the value of the selected option, but this step also failed, so I think there is an issue with retrieving the value of the selected option. Any help would be appreciated.
You're not sending the selected value to the server. Add it to the AJAX call:
$.getJSON('phpVoiture.php', { selected: $('#selected').val() }, function(data){
//...
});
Also, your <option> elements don't have values. You used name instead, but that belongs on the <select>. Use value:
echo '<option value="'.$row['Type'].'">'.$row['Type'].'</option>';
Additionally, you're using a GET request instead of a POST request. So you need to look for the value in the $_GET array:
$sel = $_GET['selected'];
You have other typos too, such as an incorrect use of a variable in PHP:
"...".sel."..."
would be:
"...".$sel."..."
Though this brings up a point about SQL injection. You really shouldn't be directly concatenating the variable like that at all. Instead, use prepared statements with query parameters.
It's entirely possible that there continue to be other mistakes in the code I simply haven't spotted yet. You'll want your debugging to include two things:
Looking at your PHP logs for errors.
Using your browser's debugging tools to observe the AJAX request/response.
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>
I'm trying to get a simple javascript popup script going anytime the database is updated in real-time. I'm not sure as to what to do next, because I'm still a newbie with jQuery and ajax, but the following code is what I have right now:
PHP MySQL query page:
<?php
$con = mysqli_connect('localhost','root','root','mydb');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"mydb");
$sql = "SELECT * FROM incoming_calls";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
//$callArray = array('phonenumber' => $row['phone_number'], 'id' => $row['phone_login_id']);
if(!empty($row)) {
$number = $row['phone_number'];
}
}
$sql="SELECT Username, Password FROM tblUsers WHERE PhoneHome='$number' OR PhoneCell='$number' OR PhoneWork='$number'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$userArray = array("username" => $row['Username'], "password" => $row['Password']);
//echo json_encode($userArray);
}
echo json_encode($userArray);
mysqli_close($con);
?>
HTML page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Phone calls</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
function getCall(){
$.get("phonecall.php", function(data){
var loginInfo = jQuery.parseJSON(data);
var user = loginInfo.username;
var pass = loginInfo.password;
$('#username').html(user);
$('#password').html(pass);
});
/*$.getJSON("phonecall.php", function(data){
for (var i=0, len=data.length; i < len; i++) {
$('#username').html(data);
}
});*/
}
setInterval(getCall,5000);
</script>
<div id="username"></div>
<div id="password"></div>
</body>
</html>
One of the problems I am having is that when there are 2 or more users with the same phone number for say like a house phone, depending on where the json_encode is, will either return the last entry in the table, or return nothing at all. If the json_encode is in the while loop, I can check the console, it says the information is being retrieved, but something must not be right with my "$.get" syntax to allow more than one entry to be displayed. Any ideas?
You're only ever saving one row of data:
while($row = mysqli_fetch_array($result)) {
$userArray = array("username" etc...
^^^^---here
If you have multiple rows of data, each row you fetch will overwrite the previous row in $userArray.
You probably want
$userArray[] = array("username" etc...
^^---- note these
so you're creating an array of results.
You'll also have to modify your JS code to accept an array of arrays, since right now you only handle one username/password.
I have a scenario like this:
I will take a number as input and will store in the database along with other information. And will display the data from the database as per the number position that have been taken as input. For example: if the input is 4, the display order will be in fourth position.
I want to make this using PHP/Mysql.
Thanks for the suggestions...
suppose you have field serial_number in your table iserted for serial by input, then firstlly you have to fetch table in array and then sort the table according to the serial number the code is like follow
<?php
$con=mysql_connect("localhost","root","");
$sql="select * from sort.data";
$result=mysql_query($sql,$con);
$data=array();
while($row=mysql_fetch_assoc($result))
{
$data[]=$row;
}
echo '<br />content of data before sorting';
echo '<pre>';
print_r($data);
echo '</pre>';
$final = array();
foreach($data as $key=>$item)
{
for($i=0;$i<$key;$i++)
{
if($data[$i]['serial_number']>$data[$key]['serial_number'])
{
$temp = $data[$key];
$data[$key] = $data[$i];
$data[$i] = $temp;
}
}
}
echo '<br />content of data after sorting';
echo '<pre>';
print_r($data);
echo '</pre>';
?>
here lastly $data containing the sorted array as per your requirement then you applay the table and td on it for formatting
as Saurabh Sinha commented. I am describing his comment.
store your input value in table such as position
$position = $_REQUEST['position']; // position submit by your form eg:4
insert record with position
mysql_query("INSERT INTO `your_table`(field1, field2,....,position) VALUES('$field1_value', '$field2_value',.....,'$position')");
now when ever you retrive your records and be sort according to the position. using ORDER BY like this
$sql = "SELECT * FROM `your_table` WHERE [YOUR CONDITIONS] ORDER BY position [DESC/ASC]";
in [] optional.
eg : if you have no condition to apply and want to order in Descending use given query
$sql = "SELECT * FROM `your_table` ORDER BY position DESC";