I'm trying to make graphs in PHP and MySQL using jQuery, specifically with Highcharts library, I have managed to make the chart with data from MySQL database, but these data show some data if they are in the databases but not others, for example, a query that yields 10 results 5 are good, but the other five did not, I have done some research on the web and I understand it is due to a problem when I pass the result of my query in MySQL by json_encode, I hope some of you can tell me because I have this error or if I'm misusing the JSON, thank you very much.
Code:
index.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Incidencias</title>
<script type="text/javascript" src="../js/jquery-1.7.1.min.js" ></script>
<script type="text/javascript" src="../js/highcharts.js" ></script>
<script type="text/javascript" src="../js/themes/grid.js"></script>
<script type="text/javascript" src="../js/export.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'pieClientes',
defaultSeriesType: 'pie',
marginRight: 10,
marginBottom: 25
},
title: {
text: 'top 10. Clientes con m\u00e1s incidencias',
x: -10
},
subtitle: {
text: '',
x: -20
},
tooltip: {
formatter: function() {
return '<b>'+ this.point.name +'</b>: <b>'+ this.y +' incidencias</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
type: 'pie',
name: 'Browser share',
data: []
}]
}
$.getJSON("datosCliente.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<div style="font-size: 12p; font-family: Calibri, Candara, Segoe, Segoe UI, Optima, Arial, sans-serif; align="left" >
<h1>Dashboard incidencias SCI</h1>
<div>
<div id="pieClientes" style="width: 770px; height: 450x; margin: 0"></div>
</body>
</html>
datosCliente.php
<?php
include"../clases/conexion.php";
$result = mysql_query("SELECT
clientes.cliente,
COUNT(incidencias.idIncidencia) AS nIncidencias
FROM incidencias
INNER JOIN clientes ON incidencias.idCliente = clientes.idCliente
GROUP BY incidencias.idCliente
ORDER BY nIncidencias DESC
LIMIT 0,10");
$rows = array();
while($r = mysql_fetch_array($result))
{
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
//print json_encode($rows, JSON_PRETTY_PRINT);
echo json_encode($rows, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
mysql_close($con);
?>
The error is for example when I want to show 10 row of the database in the graph, it show me the results of this form:
1st. row-> show me "slice"
2nd. row-> the registerok,
3th. row-> show me "slice"
4. row-> the registerok,
5. row-> the registerok,
6.row-> show me "slice"
7.row->the registerok,
8.row-> show me "slice"
9.row->the registerok,
10.row-> show me "slice"
The problem is that in the graph (pie) displays correct data but not others, it is as if some records or tubiese skipped a limit of 5 registrros, not I do not know where I'm wrong. :(
thanks for helping :)
First of all I would try to give the array elements a value, instead of using the index. Give your array key a name. As well remove all the uppercase letters from your encode. I am on an ipad and unable to code, but let me know if you have questions.
Related
I am looking forward chart like this https://i.stack.imgur.com/a6dAq.png with this code
php + html:
$sql = "SELECT val1 , val2 ,t
FROM DvojeHodnoty
INNER JOIN Pristroje ON DvojeHodnoty.dev_name = Pristroje.dev_name
WHERE t>'$startdate2' AND t< '$enddate2' AND Pristroje.nazev_pristroje='$pristroj' order by val1 asc;";
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_array($result))
{
$t = $t.'"'.date('d.m.y H:i:s', $row['t']/1000).'",';
$hodnota = $hodnota.'"'.$row['val1'].'",';
$hodnota2 = $hodnota2.'"'.$row['val2'].'",';
}
$start = date('d.m.y', $startdate2/1000);
$end = date('d.m.y', $enddate2/1000);
$t = trim($t,",");
$hodnota = trim($hodnota,",");
$hodnota2 = trim($hodnota2,",");
}
<div id="chart-container" style="background: white">
<canvas id="chart"></canvas>
<script>
var ctx =document.getElementById("chart").getContext('2d');
var myChart = new Chart(ctx, {
type:'line',
data: {
labels: [<?PHP echo $hodnota2; ?>],
datasets:
[
{
label: '<?PHP echo $start;?> - <?PHP echo $end; ?> Přístroj: <?PHP echo $pristroj;?> ',
data: [<?PHP echo $hodnota; ?>],
backgroundColor:'transparent',
borderColor:'rgba(255,99,132)',
borderWidth: 3
}]
},
options: {
scales: {
yAxes:[{
scaleLabel: {
display: true,
labelString: 'σ',
fontSize: 20
}
}],
xAxes:[{
scaleLabel: {
display: true,
labelString: 'ε',
fontSize:20
}
}]
}
}
})
</script>
</div>
but so far I got only this https://i.stack.imgur.com/Ri8Ho.png.
I don't know how to create chart with two variables, I tried scatter but so far I am stuck with no ability to create graph with x,y line as values. Is there any easy way to create chart with two variables? If so can you help me/ give me some documentation? (I've seen one scatter chart with fix values, but I am not able to do it with php echo (with values from database) since I need to have variable values since user will choose values depends on chosen date. So far I got only 1 value (y) and two values but with text (numbers counted as text not as value) so chart looks weirdly (0,1,-1 still on same line not like normal graph showned up).
The problem was that data type was VARCHAR and for sorting it I need INT. Problem solved
I'd like to know if is possible to do that with Flot chart, because I'm not sure...
I have a table on a database with 3 rows: Date Start, Date End, Medication
Mi PHP code:
$sql = "SELECT * FROM medications ORDER BY DateStart";
$stmt = $PDO -> query($sql);
$result=$stmt -> fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row){
$dateini= $row['DateStart'];
$datend= $row['DateEnd'];
$medic= $row['Medication'];
$data1 = array(strtotime($dateini)*1000,$medic);
$data2 = array(strtotime($datend)*1000,$medic);
$data3[] = array($data1,$data2);
}
If I do:
echo json_encode($data3);
I get the array:
[[[1456531200000,"12"],[1456704000000,"12"]],[[1456531200000,"16"],[1456704000000,"16"]],[[1456617600000,"13"],[1456790400000,"13"]],[[1456704000000,"14"],[1457049600000,"14"]]]
<script>
var data3 = <?php echo json_encode($data3)?>;
$(function() {
var datasets = [
{
label: "Medication",
data: data3,
yaxis: 1,
color: "Yellow",
points: { symbol: "diamond", fillColor: "Yellow",show: true, radius: 6}
}
];
$.plot($("#flot-placeholder"), datasets ,options);
</script>
This: $.plot($("#flot-placeholder"), datasets ,options) don't plot anything, but if I do:
$.plot($("#flot-placeholder"), data3,options);
I get
It would be possible to get the graphic writing datasets (in $.plot) instead data3?
Two issues with your datasets array:
Your data3 array has multiple data series but you try to put it all into one data set object in the datasets array. Put each data series in a separate object (with its own options where neccessary).
var datasets = [{
label: "Medication",
data: data3[0],
yaxis: 1,
color: "Yellow",
points: {
symbol: diamond,
fillColor: "Yellow",
show: true,
radius: 6
}
}, {
label: "Medication",
data: data3[1],
yaxis: 1,
color: "red",
points: {
symbol: diamond,
fillColor: "red",
show: true,
radius: 6
}
}, ... ]
Flot has no build-in diamond symbol, you have to provide a function which draws a diamond.
function diamond(ctx, x, y, radius, shadow) {
var size = radius * Math.sqrt(Math.PI) / 2;
ctx.moveTo(x - size, y);
ctx.lineTo(x, y + size);
ctx.lineTo(x + size, y);
ctx.lineTo(x, y - size);
ctx.lineTo(x - size, y);
}
See this fiddle for a full working example.
How to make a border around the chart and title bar over it in ZingChart. I tried with plotarea border but that is around the graph not the complete chart. I want the black border and title but i am only able to make the red border like in this image.
Here is the code
{
"type":"bar",
"plotarea":{
"border-color" : "#0ff",
"border-width" : "2px"
},
"series":[
{
"values":[11,26,7,44,11]
},
{
"values":[42,13,21,15,33]
}
]
}
Accomplishing this look can be achieved by using border attributes for specific sides of different objects. In this case, setting borders for the right and left of the chart, and the bottom of the title.
Here is an example that shows this approach in action, with the key parts for you to use in your own code.
var myConfig = {
type: "bar",
borderRight: "6px solid #000",
borderLeft: "6px solid #000",
borderBottom: "6px solid #000",
title: {
text: "My Title",
height: 40,
borderBottom: "6px solid #000" //needs to be added to title or will be hidden underneath
},
series : [
{
values : [35,42,67,89,25,34,67,85]
}
]
};
zingchart.render({
id : 'myChart',
data : myConfig,
height: 400,
width: 600
});
<html>
<head>
<script src= 'https://cdn.zingchart.com/zingchart.min.js'></script>
<script> zingchart.MODULESDIR = 'https://cdn.zingchart.com/modules/';
ZC.LICENSE = ['569d52cefae586f634c54f86dc99e6a9','ee6b7db5b51705a13dc2339db3edaf6d'];</script>
</head>
<body>
<div id='myChart'></div>
</body>
</html>
I'm on the ZingChart team, so please let me know if you need additional clarification or if this isn't quite what you were looking for.
I am using the chartist.js library for making graphs. I didn't found a single example of it with MYSQL example. So, taking help different libraries codes available online I am trying to insert numerical values as array as in labels(which is static though). But not able to generate graph.
Hoew to solve this problem.
The page is filled with values of X and Y axis but no line is getting drawn when entered in browser.
The debugger says
TypeError: this.data.series[i][m] is undefined chartist.min.js:7:17185
Use of Mutation Events is deprecated. Use MutationObserver instead.
code:
<head>
<script src="../_js/chartist.min.js"></script>
<link href="../_css/chartist.min.css" rel="stylesheet" type="text/css" />
<meta charset="utf-8">
<title>Daily performance-- Aspect ratio containers</title>
<?php
$con=mysqli_connect("// due connectn attributes");
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * from Score_result");
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$player1 = array_column($row,"Player1");
$player2 = array_column($row,"Player2");
mysqli_close($con);
?>
</head>
<body>
<div class="ct-chart ct-golden-section"></div>
<script>
new Chartist.Line('.ct-chart', {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
series: [
[<?php echo implode(',',$player1); ?>],
[<?php echo implode(',',$player2); ?>]
]
});
</script>
</body>
</html>
I've used ChartJS before, however, i did not use json so i'm unsure what might be wrong with your code.
I pulled this out of the script i wrote where I implemented a bar chart. In this code the variable video_statistics is a multidimensional array contains data in the following form:
Month | Premium Users | Total Users
___________________________________
March | 8 | 12
April | 15 | 32
May | 13 | 27
Code:
<?php
$months = array_column($video_statistics,"month");
$premium_users = array_column($video_statistics,"premium_users");
$total_users = array_column($video_statistics,"total_users");
?>
<script type="text/javascript">
$( document ).ready(function() {
var data = {
labels: [<?php echo implode(',',$months);?>],
datasets: [
{
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [<?php echo implode(',',$total_users); ?>],
title : 'Total Users'
},
{
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [<?php echo implode(',',$premium_users); ?>],
title : 'Premium Users'
}
]
}
var cht = document.getElementById('videoChart');
var ctx = cht.getContext('2d');
var barChart = new Chart(ctx).Bar(data);
});
</script>
<canvas id="videoChart" width="400" height="400"></canvas>
The code was working in the script but i haven't tested it in this form. I hope it helps.
Really new to Highcharts and PHP. Trying to use date from my SQL database but can get the X-axis to recognise the data as dates.
My PHP request looks like this:
<?php
mysql_connect('xxxxxxxxxxxxx.ipagemysql.com', 'xxxxx', 'xxxxxxxx') or die(mysql_error());
mysql_select_db("history") or die(mysql_error());
$result = mysql_query("SELECT * FROM eur_weekly")
or die(mysql_error());
WHILE ($row = mysql_fetch_array( $result )) {
$EUR1 [] = $row ['price'];
$EUR2 [] = $row ['date'];}
?>
Where "date" is my date column organised as follow:
31.01.2014
31.12.2013
30.11.2013
31.10.2013
30.09.2013
31.08.2013
In my HTML code I use this function that works with the rest of the data but it wont recognise the "dates" as dates data for the x-axis:
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
zoomType: 'x'
},
title: {
text: 'EUR/USD '
},
xAxis: [{
type: 'datetime',
categories: [<?php echo join($EUR2,',') ?> ],
}],
yAxis: [{
labels: {
format: '{value} price',
style: {
color: '#CC33FF',
lineWidth: 0.5
}
},
}],
tooltip: { },
series: [{
name: 'EUR/USD',
color: '#4572A7',
type: 'spline',
marker:{ enabled: false},
zIndex:1,
data: [ <?php echo join($EUR1, ',') ?> ],
}]
});
});
</script>
Is there a transformation I should do? Can't find a simple example of dates from MySQL imported into Highcharts..
Thank you and best regards!
You need to parse your dates, to achieve that you can transform time to unix and multiply by 1000 in the php, other solution is parse dates in javascript.
I advice to use json_encode(), which return json in php (then load it by getJSON() in javascript), instead of inject php inside javascript.