I am trying to populate a chart via the ChartJS plugin with data from my MySQL database, but while doing so I am running into a
mysqli_fetch_assoc(): Couldn't fetch mysqli_result in ...
error.Since I am using json_encode I tried to adjust the fetch array but cant seem to figure this one out.
Any help would be much appreciated.
<div class="box-body">
<div class="chart">
<canvas id="canvas_bar" style="height:250px"></canvas>
<?php
// Start MySQLi connection
$db = new MySQLi($dbhost,$dbuser,$dbpass,$dbname);
if ($db->connect_errno) { echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error; }
// count all records per month
$sql = "SELECT LOWER(MONTHNAME(mod_date)) AS mdate, count(*) AS cnt FROM qci_modreport GROUP BY LOWER(MONTHNAME(mod_date))";
if (!($result)) {
print "ERROR, something wrong with the query.";
} else {
$output = array();
while ($row = mysqli_fetch_assoc($result)) {
$output[$row['mdate']] = $row['cnt'];
}
print (json_encode($output));
}
?>
<!-- chartJS 1.0.1-->
<!-- <script src="./plugins/chartjs/Chart.js"></script> -->
<script src="../../plugins/chartjs/Chart.min.js"></script>
<script>
var barChartData = {
labels: <?php echo json_encode(array_keys($output)); ?>,
datasets: [
{
fillColor: "#03586A", //rgba(151,187,205,0.5)
strokeColor: "#03586A", //rgba(151,187,205,0.8)
highlightFill: "#066477", //rgba(151,187,205,0.75)
highlightStroke: "#066477", //rgba(151,187,205,1)
data: <?php echo json_encode(array_values($output)); ?>
}]
};
$(document).ready(function () {
new Chart($("#canvas_bar").get(0).getContext("2d")).Bar(barChartData, {
tooltipFillColor: "rgba(51, 51, 51, 0.55)",
responsive: true,
barDatasetSpacing: 6,
barValueSpacing: 5
});
});
</script>
</div>
</div>
<!-- /.box-body -->
$result is not defined. You should use
if (!($result = $db->query($sql1))) { ...
or
$result = $db->query($sql1);
and only after you do
if (!$result) { ...
and
while ($row = mysqli_fetch_assoc($result)) { ...
Related
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'];
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've to show a Google Chart in a loop . Without loop my chart works fine but when i try to add it in a loop i get it only for first iterataion , how do i fix it , please review this
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Daily Report'],
['Points Achieved', <?php echo $points_achieved?>],
['Points Left', <?php echo $points_left?>]
]);
var options = {
backgroundColor: 'transparent',
title: '' ,
chartArea:{right:0,top:0,width:"90%",height:"100%" }
,height: 150
,width: 200,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<?php
$sql= "SELECT * FROM employees";
$query= mysqli_query($connection, $sql);
while($res= mysqli_fetch_assoc($query)): ?>
<div id='piechart'></div>
//other data from database comes here
<?php endwhile;?>
Since you are drawing multiple charts i would suggest to modify drawChart function to accept chart id and data as parameters:
function drawChart(chartId,data) {
var dataTable = google.visualization.arrayToDataTable(data);
var options = {
backgroundColor: 'transparent',
title: '' ,
chartArea:{right:0,top:0,width:"90%",height:"100%" },
height: 150
,width: 200,
};
var chart = new google.visualization.PieChart(document.getElementById(chartId));
chart.draw(dataTable, options);
}
Then you could iterate PHP array and invoke drawChart function:
<?php
foreach ($reports as $key => $report) {
$chartId = "piechart_$key";
//prepare chart data
$chartData = array(
array("Task", "Daily Report"),
array("Points Achieved" , $report["Points Achieved"]),
array("Points Left" , $report["Points Left"])
);
?>
<div id='<?php echo $chartId; ?>'></div>
<script type="text/javascript">drawChart('<?php echo $chartId; ?>',<?php echo json_encode($chartData); ?>)</script>
<?php
}
?>
It is assumed $reports array has the following structure:
//input data example ( replace it with data retrieved from DB)
$reports = array(
"R1" => array("Points Achieved" => 20, "Points Left" => 4),
"R2" => array("Points Achieved" => 40, "Points Left" => 14),
"R3" => array("Points Achieved" => 10, "Points Left" => 0)
);
Working example
So i just found out about the jquery auto complete and i would like to add it to my web-page. I want to hook it up to my php code so i can search my sql database. However Whenever i try to run my auto complete,it doesnt seem to find the php array im passing ( im just trying to get an array to work for now) . Can someone help?
Jquery Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#tags" ).autocomplete({
source: "test.php"
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
PHP code
<?php
$data[] = array(
'c++','Java','JavScript',"c#" );
echo json_encode($data);
?>
This is an updated version of your answer which should resolve the deprecated SQL driver and the injection issue. You need to replace the SECOND_COLUMNNAME with your actual column's name. Aside from that I think this should work.
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=DB','username','password');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
if(empty($_REQUEST['term']))
exit();
//require_once('connect.php'); connection to db is in this file so connection is not needed
$query = 'SELECT name, SECOND_COLUMNNAME FROM locations
WHERE name
LIKE ?
ORDER BY id ASC
LIMIT 0,10';
$stmt = $dbh->prepare($query);
$stmt->execute(array(ucfirst($_REQUEST['term']) . '%'));
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'label' => $row['name'],
'value' => $row['SECOND_COLUMNNAME']
);
}
echo json_encode($data);
flush();
Links:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.connections.php
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
How can I prevent SQL injection in PHP?
Also not sure if there was anything else inside connect.php, you might need to bring that back.
The array pattern used here should be as below.
<?php
$data = array(
array("value"=>'C++'),
array("value"=>'Java'),
array("value"=>'Javascript'),
array("value"=>'C#'),
);
echo json_encode($data);
If you're using PHP >= 5.4:
$data = [
[ 'value' => 'C++' ],
[ 'value' => 'Java' ],
[ 'value' => 'Javascript' ],
[ 'value' => 'C#' ]
];
echo json_encode( $data );
Here's a working example of my autocomplete code:
function get_data(type, target, min_length )
{
$(target).autocomplete({
source: function( request, response ) {
var submit = {
term: request.term,
type: type
};
$.ajax({
url: '/request/get',
data: { thisRequest: submit},
dataType: "json",
method: "post",
success: function( data ) {
response($.map( data.Data, function( item ) {
return {
label: item.label,
value: item.label
}
}));
}
});
},
minLength: min_length
})
}
<?php
$data = array(
'c++',
'Java',
'JavScript',"c#" );
echo json_encode($data);
?>
So i want with Pratik Soni advice and did a search. Here is the php code if anyone wants to use it
<?php
// Connect to server and select databse.
$dblink = mysql_connect('localhost','username','password') or die(mysql_error());
mysql_select_db('DB');
?>
<?php
if(!isset($_REQUEST['term']))
exit();
require('connect.php');
$term =
$query = mysql_query('
SELECT * FROM locations
WHERE name
LIKE "'.ucfirst($_REQUEST['term']).'%"
ORDER BY id ASC
LIMIT 0,10', $dblink
);
$data = array();
while($row = mysql_fetch_array($query, MYSQL_ASSOC)){
$data[] = array(
'label' => $row['name'],
'value' => $row['name'],
);
}
echo json_encode($data);
flush();
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); ?>);