I want to dynamically display statistics with Chart.js on my page from different users.
I can already display data with a clear data query from one user, but several identical bootstrap cards with different data should be displayed. How can I pass the user variables dynamicly to the mysqli_query in playerOne.php?
playerOne.php
header('Content-Type: application/json');
include "../../../includes/db.php";
$query = "SELECT SUM(game_stats.match_stats_kills) AS Kills, SUM(game_stats.match_stats_deaths) AS Deaths FROM game_stats WHERE game_stats.user_id = 1";
$select_kd = mysqli_query($connection, $query);
$data = array();
foreach($select_kd as $row) {
$data[] = $row;
}
mysqli_close($connection);
echo json_encode($data);
stats.js
$(document).ready(function() {
showData();
});
function showData() {
{
($.post("includes/stats/playerOne.php",
function(data) {
var kills = [];
var deaths = [];
for(var i in data) {
kills.push(data[i].Kills)
deaths.push(data[i].Deaths);
}
var pieChartData = {
labels: [
'Kills', 'Deaths'
],
datasets: [
{
backgroundColor: ['#f56954', '#00c0ef'],
data: [kills, deaths]
}
]
};
var pieChartTarget = $('#playerKD').get(0).getContext('2d');
var pieChart = new Chart(pieChartTarget, {
type: 'pie',
data: pieChartData
});
}));
}
}
you can send the variable on the url, here...
($.post("includes/stats/playerOne.php?user=1", // <-- add variable here -- ?user=1
then in your php, access the value of the variable using...
$_GET['user']
e.g.
$query = "SELECT SUM(game_stats.match_stats_kills) AS Kills, SUM(game_stats.match_stats_deaths) AS Deaths FROM game_stats WHERE game_stats.user_id = " + $_GET['user'];
Related
I have a random issue while trying to reorder items in a JSON array via JS/PHP, this occurs when the array has more than 1000 items.
Example of my Users.json file:
[
{
"ID_id": "123abc",
"ST_username": "johndoe",
"ST_email": "j#example.com",
"ST_fullname": "John Doe",
},
{
"ID_id": "def345",
"ST_username": "sarahdoe",
"ST_email": "s#example.com",
"ST_fullname": "Sarah Doe",
},
{
"ID_id": "fgh567g",
"ST_username": "markdoe",
"ST_email": "mark#example.com",
"ST_fullname": "Mark Doe",
}
// + additional 1000 similar items in this array
]
So, first of all, I get the JSON file's data and decode it into a PHP array:
$tableName = $_GET['tableName']; // Lets' say $tableName is 'Users'
// fetch data from 'Users.json'
$data = file_get_contents($tableName. '.json');
$data_array = json_decode($data, true);
Then I call this function in JS:
function reorderTableData() {
var newOrderArray = [];
var data_arrayStr = JSON.stringify(<?php echo json_encode($data_array) ?>);
var jsonData = JSON.parse(data_arrayStr);
var reorderedData = JSON.stringify(jsonData, newOrderArray);
$.ajax({
url : "reorder-table-data.php",
type: 'POST',
data: 'tableName='+'<?php echo $tableName ?>'+'&reorderedData='+encodeURIComponent(reorderedData),
success: function(data) {
location.reload();
// error
}, error: function(e) {
}});
}
}
My reorder-table-data.php code:
$tableName = $_POST['tableName'];
$reorderedData = $_POST['reorderedData'];
$data_array = json_decode($reorderedData, true);
// Encode back to JSON
$data = json_encode(array_values($data_array), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents($tableName. '.json', $data);
// echo JSON object
echo json_encode($data);
?>
Sometimes this code erases everything and all you see is null in the Users.json file, all data got lost.
What am I doing wrong?
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 using XAMPP web server.
I have created folder chartexample in htdocs.
Now I want to display database data using chart js.
So I created data.php and bargraph.html files into chartexample folder. Similarly I created app.js file in js folder in chartexample folder.
But when I run this code undefined is display on chart. Below are my code :
data.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "shgreportingdatabase";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SELECT employee.FirstName, count(*) as TotalGroups from groupdetails, employee WHERE groupdetails.EmpId=employee.EmpId group by groupdetails.EmpId";
$result = $conn->query($sql);
if ($result!=null) {
// output data of each row
while($row = $result->fetch_assoc()) {
print json_encode($row);
}
}
$conn->close();
Here is bargraph.html
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<canvas id="mycanvas"></canvas>
<!-- javascript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
and app.js
$(document).ready(function(){
$.ajax({
url: "http://localhost/chartexample/data.php",
method: "GET",
success: function(data) {
console.log(data);
var emp = [];
var groups = [];
for(var i in data) {
emp.push(data[i].FirstName);
groups.push(data[i].FirstName);
}
var chartdata = {
labels: emp,
datasets : [
{
label: 'SHG Groups',
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: groups
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
I suspect the problem is with your query.
$sql = "SELECT employee.FirstName, count(*) as TotalGroups from groupdetails, employee WHERE groupdetails.EmpId=employee.EmpId group by groupdetails.EmpId";
In the above, you're using WHERE to specify a link between two tables. This is a job for JOIN. You also need to specify something concrete in WHERE unless you want to get all the rows.
$SQL = "SELECT employee.FirstName, count(*) as 'TotalGroups' FROM groupdetails g JOIN employee e ON g.EmpId = e.EmpId
If you need to use a WHERE in there to exclude some data, you'll need to specify the table. For example, WHERE g.id = 5 to return ID 5 from the groupdetails table.
If you do want to return all rows, omit the WHERE clause altogether.
I have been trying to make an autocomplete script for the whole day but I can't seem to figure it out.
<form method="POST">
<input type="number" id="firstfield">
<input type="text" id="text_first">
<input type="text" id="text_sec">
<input type="text" id="text_third">
</form>
This is my html.
what I am trying to do is to use ajax to autocomplete the first field
like this:
and when there are 9 numbers in the first input it fills the other inputs as well with the correct linked data
the script on the ajax.php sends a mysqli_query to the server and asks for all the
data(table: fields || rows: number, first, sec, third)
https://github.com/ivaynberg/select2
PHP Integration Example:
<?php
/* add your db connector in bootstrap.php */
require 'bootstrap.php';
/*
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
*/
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
Legacy Version:
In my example i'm using an old Yii project, but you can easily edit it to your demands.
The request encodes in JSON. (You don't need yii for this tho)
public function actionSearchUser($query) {
$this->check();
if ($query === '' || strlen($query) < 3) {
echo CJSON::encode(array('id' => -1));
} else {
$users = User::model()->findAll(array('order' => 'userID',
'condition' => 'username LIKE :username',
'limit' => '5',
'params' => array(':username' => $query . '%')
));
$data = array();
foreach ($users as $user) {
$data[] = array(
'id' => $user->userID,
'text' => $user->username,
);
}
echo CJSON::encode($data);
}
Yii::app()->end();
}
Using this in the View:
$this->widget('ext.ESelect2.ESelect2', array(
'name' => 'userID',
'options' => array(
'minimumInputLength' => '3',
'width' => '348px',
'placeholder' => 'Select Person',
'ajax' => array(
'url' => Yii::app()->controller->createUrl('API/searchUser'),
'dataType' => 'json',
'data' => 'js:function(term, page) { return {q: term }; }',
'results' => 'js:function(data) { return {results: data}; }',
),
),
));
The following Script is taken from the official documentation, may be easier to adopt to:
$("#e6").select2({
placeholder: {title: "Search for a movie", id: ""},
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data.movies};
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection // omitted for brevity, see the source of this page
});
This may be found here: http://ivaynberg.github.io/select2/select-2.1.html
You can optain a copy of select2 on the github repository above.
I try to understand how it work. At the beginning, I was using inside my html code a php array with db and after that I was extracting my array inside my playlist.
Here the example:
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$row['emplacement'] = str_replace("../", "../../", $row['emplacement']);
$row['poster'] = str_replace("../", "../../", $row['poster']);
$row['duration'] = str_replace("00:", "", $row['duration']);
$info = '{artist:"'.$row['artiste'].'", title:"'.$row['track'].'", album:"'.$row['album'].'", mp3:"'.$row['emplacement'].'", cover:"'.$row['poster'].'", duration:"'.$row['duration'].'"}';
array_push($fileinfo, $info);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(
[
<?php
//for each file in directory
$arrlength=count($fileinfo);
for($x=0;$x<$arrlength;$x++)
{
if ($x < ($arrlength - 1))
{
echo $fileinfo[$x].",\n\t\t";
}else
{
echo $fileinfo[$x]."\n\t\t";
}
}
//the result look like this:
//{artist:"Boy Sets Fire", title:"After the Eulogy", album:"After The Eulogy",
mp3:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/01_After_the_Eulogy-JAH.mp3",
cover:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/Folder.jpg", duration:"03:31"},
?>
],
To use everything more dynamically, I try to use JSON with PHP inside my javascript
And my code look like this:
var sourceplayer =
{
datatype: "json",
datafields: [
{ name: 'artiste' },
{ name: 'title' },
{ name: 'album' },
{ name: 'mp3' },
{ name: 'cover' },
{ name: 'duration' }
],
url: 'player.php'
};
$('#player').ttwMusicPlayer(
[
],
So afert url: 'player.php', I don't know how to work with result. It's an array of data like this: "Rows":[{"no_track":"1","track":"Grandma Dynamite","artiste":"24-7 Spyz","album":"Harder Than You","genre":"Alternative","year":"1989","duration":"00:03:44"}
And I want to use it inside the bracket of $('#player').ttwMusicPlayer(
Please give me a cue or an simple example to help me with this. I'm not using pure jplayer but a similar one.
Thanks in advance
Regards,
Eric
PHP json_encode - http://us2.php.net/json_encode
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$fileinfo[] = array(
'mp3' => str_replace("../", "../../", $row['emplacement']),
'cover' => str_replace("../", "../../", $row['poster']),
'duration' => str_replace("00:", "", $row['duration']),
'artist' => $row['artiste'],
'title' => $row['track'],
'album' => $row['album']
);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(<?php echo json_encode($fileinfo); ?>);