I'm making a timeline graph and I have problem with the data I need the result of the query to the database did not result in double quotes ("). They leave a sample of how I get the result
[{"name":"Tv Cable","data":["[1370925000000,100]"]},{"name":"Tv Satelital","data":["[1365654600000,100]","[1368505800000,200]","[1370320200000,1500]","[1370925000000,500]","[1370925000000,560]","[1370925000000,50]","[1370925000000,500]","[1370925000000,800]","[1370925000000,500]","[1373776200000,1000]"]},{"name":"Tv Internet","data":["[1371097800000,500]"]},{"name":"Tv Telefonia"}]
I need it follows
[{"name":"Tv Cable","data":[[1370925000000,100]]},{"name":"Tv Satelital","data":[[1365654600000,100],[1368505800000,200],[1370320200000,1500],[1370925000000,500],[1370925000000,560],[1370925000000,50],[1370925000000,500],[1370925000000,800],[1370925000000,500],[1373776200000,1000]]},{"name":"Tv Internet","data":[[1371097800000,500]]},{"name":"Tv Telefonia"}]
I have while trying to fix it and I have not managed to do?
I let my graphic codes to see what I do
sql.php
<?php
$fecha = date("d-m-Y"); // fecha actual
$ano = date("Y"); // A単o actual
$mes = date("m"); // Mes actual
$dia = date("d"); // Dia actual
$mes_inicio= $mes-2;
$con = mysql_connect("localhost","xyolcarx_inter","xYolcar19572059");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xyolcarx_inter", $con);
$rows = array();
for ($i=1;$i<=4;$i++){
$sth = mysql_query("SELECT monto,(unix_timestamp(fecha)*1000) FROM ventas WHERE codigo_ser = '".$i."' ORDER BY fecha ASC ");
$sth2 = mysql_query("SELECT * FROM servicio WHERE codigo_ser= '".$i."'");
while($r2 = mysql_fetch_array($sth2)) {
$rows[$i]['name'] = $r2['servicio'];
}
while($r = mysql_fetch_array($sth)) {
$rows[$i]['data'][] = '['.$r['(unix_timestamp(fecha)*1000)'].','.$r['monto'].']';
}
}
$result = array();
for ($i=1;$i<=4;$i++){
array_push($result,$rows[$i]);
}
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
</style>
<script type='text/javascript'>//<![CDATA[
$(function() {
$.getJSON('sql.php', function(data) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container'
},
rangeSelector : {
selected : 1
},
title : {
text : 'AAPL Stock Price'
},
series : data
});
});
});
//]]>
</script>
</head>
<body>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
This line
$rows[$i]['data'][] = '['.$r['(unix_timestamp(fecha)*1000)'].','.$r['monto'].']';
should look like this
$rows[$i]['data'][] = array($r['(unix_timestamp(fecha)*1000)'],$r['monto']);
Don't build the json yourself. Just build the array structure, and let json_encode do the rest of the work for you.
edit more advice:
Change this:
SELECT monto,(unix_timestamp(fecha)*1000) FROM ventas...
to this:
SELECT monto, (unix_timestamp(fecha)*1000) AS fecha_timestamp FROM ventas...
so you can access it easier in php:
$rows[$i]['data'][] = array($r['fecha_timestamp'],$r['monto']);
edit more advice:
Mysql sometimes has performance issues with unix_timestamp(fecha)*1000 because it has to turn what it thinks was an 32-bit int into a 64-bit int, and that sucks. Do that in php.
Change this:
SELECT monto, (unix_timestamp(fecha)*1000) AS fecha_timestamp FROM ventas...
to this:
SELECT monto, unix_timestamp(fecha) AS fecha_timestamp FROM ventas...
so you can do the work in php:
$rows[$i]['data'][] = array($r['fecha_timestamp']*1000,$r['monto']);
Related
I am trying to build some ZingCharts with weatherdata from a homemade weatherstation. Currently I am using Google Charts, but would rather use Zing as it seems a whole lot easier to work with. Except, I can't get it to pull data from my Database. Below I have the demo example from ZingChart git, all I did was change the variables concerning my sql server. But it just shows an empty page. Looking at the page source after loading reveals that it doesn't fill the arrays with any data at all.
<!DOCTYPE html>
<html>
<head>
<title>MySQL Demo</title>
<script type="text/javascript" src="http://cdn.zingchart.com/zingchart.min.js"></script>
</head>
<body>
<script>
<?php
$host = "localhost";
$port = 3306;
$usernm = "pi";
$passwd = "";
$dbname = "weatherDB";
$query = "SELECT timestamp, temperature from bme680 ORDER BY id ASC";
$time = [];
$temperature = [];
$mysqli = new mysqli($host, $usernm, $passwd, $dbname, $port);
if($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ')' . $mysqli->connect_error);
}
if ($result = $mysqli->query($query)) {
while( $row = $result->fetch_array(MYSQLI_NUM)){
array_push($time, $row[0]);
array_push($temperature, $row[1]);
}
$result->close();
}
?>
var dateValues = [<?php echo join($time, ',') ?>];
var seriesValues = [<?php echo join($temperature, ',') ?>];
<?php
$mysqli->close();
?>
</script>
<script>
window.onload=function(){
zingchart.render({
id:"myChart",
width:"100%",
height:400,
data:{
"type":"line",
"title":{"text":"Data Pulled from MySQL Database"},
"scale-x":{
"values": dateValues,
"transform":{
"type":"date",
"item":{
"visible":false
}
}
},
"plot":{"line-width":1},
"series":[ {"values":seriesValues}]
}
});
};
</script>
<h1>Database Data</h1>
<div id="myChart"></div>
</body>
</html>
I am trying to use a code that was flagged as working and I am not getting any results, it's just empty. Notes: The MySQL does return results if run alone, so it's not an sql thing. Any suggestions?
HTML:
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
Name: <input id="hint" />
<script type="text/javascript">
$("#hint").autocomplete({
source: function (request, response) {
$.ajax({
url: "getMedicineNames.php",
dataType: "jsonp",
data: {
name: request
},
success: function (data) {
response(data);
}
});
},
minLength: 3
});
</script>
</body>
PHP:
require 'connect.inc.php';
$mysql = mysqli_connect("$db_host", "$db_username", "$db_pass", "$db_name");
$name = $_POST['name'];
if ($name != "") {
$sql = "SELECT MedicineName FROM medicinetypes WHERE MedicineNAme LIKE '%$name%'";
echo json_encode(mysqli_fetch_all(mysqli_query($mysql, $sql), MYSQLI_ASSOC));
}
Please add dataType: "json", & type : "GET".
If not working please add your screenshot of JSON response.
Bilal Ahmed answer is correct.
Aditinoally this is a bit incorrect:
$name = $_POST['name']; // Maybe cause a PHP Warning
You can solve this creating a unset value:
$name = isset($_POST['name']) ? $_POST['name'] : "";
/* "" can be NULL, FALSE, 0 or any value */
In PHP7 you can make this:
$name = $_POST['name'] ?? "";
/* "" can be NULL, FALSE, 0 or any value */
Alright I found a better answer, but the main problem was my php code where I left the array as an assoc which is wrong.
JS:
$(function () {
$("#hint").autocomplete({
source: 'getMedicineNames.php'
});
});
PHP:
$mysql = mysqli_connect("$db_host", "$db_username", "$db_pass", "$db_name");
$name = $_GET['term'];
$sql = "SELECT MedicineName FROM medicinetypes WHERE MedicineNAme LIKE '%$name%'";
$res = mysqli_query($mysql, $sql);
$res = mysqli_fetch_all($res, MYSQLI_ASSOC);
foreach($res as $row){
$data[]=$row['MedicineName'];
}
echo json_encode($data);
I'm having a problem integrating Rgraph with PHP and MySQL data. I followed instructions from the Rgraph site.
On the Rgraph site, the example uses array data but my case does not use array.
I want to display how many pegawai attended for a month.
<?php
$query2 = "SELECT count(id_absensi) AS jumhadir FROM absensi WHERE nip_pegawai = '123040269'";
if($query2){
$data = array();
while ($row = mysql_fetch_assoc($query2)){
$data[] = $row["jumhadir"];
}
$data_string = "[".join(",", $data)."]";
} else {
print('MySQL query failed with error : '.mysql_error());
}
?>
<html>
<head>
<!-- Don't forget to update these paths -->
<script src="libraries/RGraph.common.core.js" ></script>
<script src="libraries/RGraph.line.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="js/jquery-1.11.3.min.js"></script>
</head>
<body>
<canvas id="cvs" width="600" height="250">[No canvas support]</canvas>
<script>
chart = new RGraph.Line({
id: 'cvs',
data: <?php print($data_string) ?>,
options: {
gutterLeft: 35,
gutterRight: 5,
hmargin: 10,
tickmarks: 'endcircle',
labels: <?php print("Kehadiran") ?>
}
}.draw()
</script>
</body>
</html>'
I'm not getting any errors and I've got no graph. What am I missing?
This:
$query2 = "SELECT count(id_absensi) AS jumhadir FROM absensi WHERE nip_pegawai = '123040269'";
Doesn't run the query - its just a string that contains the SQL statemennt. So you could try changing it to:
$sql = "SELECT count(id_absensi) AS jumhadir FROM absensi WHERE nip_pegawai = '123040269'";
$query2 = mysql_query($sql);
if ($query2) {
// ...
Of course before you do a query you must connect to your database:
$connection = mysql_connect('localhost', 'username', 'password');
mysql_select_db('myDatabase');
I am trying to use Google charts and integrate in my android app. Before that I tried to check my html code in Google chrome. In that code I have tried to integrate to get the data from the MYSQL.
My code as follows
<?php
$server = "localhost";
$user="root";
$password="";
$database = "mobiledb";
$connection = mysql_connect($server,$user,$password)
or
trigger_error(mysql_error(),E_USER_ERROR);
$db = mysql_select_db($database,$connection);
$sth = mysql_query("SELECT * FROM `table` WHERE `x-axis` AND `y-axis` LIMIT 0, 30 ");
while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($x-axis);
$arr1=array_values($y-axis);
}
for($i=0;$i<count($arr1);$i++)
{
$chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$(function () {
var data = new google.visualization.DataTable();
data.addColumn("string", "x-axis");
data.addColumn("number", "y-axis");
data.addRows(<?php $data ?>);
});
var options = {
title: 'Details',
is3D: 'true',
width: 800,
height: 600
};
var chart = new google.visualization.ColumnChart(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>
But I am unable to see the graph. And I was getting the following error "; $data=json_encode($chart_array); ?> And when I inspect the page I was found the following error *Uncaught SyntaxError: Unexpected token < * Please help me in solving this.
check your query
$sth = mysql_query("SELECT `x-axis`,`y-axis` FROM `table` LIMIT 0, 30 ");
if you want column x-axis and y-axis then use this
then correct this
data.addRows(<?php echo $data ?>);
You may need to correct this line probably
data.addRows(<?php $data ?>); //incorrect
data.addRows(<?php echo($data); ?>); //you forgot to echo it
There are so many problem with your PHP code
//what is this?
$sth = mysql_query("SELECT * FROM `table` WHERE `x-axis` AND `y-axis` LIMIT 0, 30 ");
//probably you want this?
$sth = mysql_query("SELECT `x-axis`, `y-axis` FROM `table` LIMIT 0, 30 ");
//this is wrong
while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($x-axis);
$arr1=array_values($y-axis);
}
//try this
while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r['x-axis']);
$arr1=array_values($r['y-axis']);
}
//where is $chart_array defined? It should be like this
$chart_array = array();
for($i=0;$i<count($arr1);$i++)
{
$chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
I am trying to populate a select box from values from a mysql database, using jQuery.
db call:
<?php
include 'db.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$tableName = "tbl_title";
$result = mysql_query("SELECT * FROM $tableName");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
//echo json_encode( $data );
?>
HTML:
<select id="a1_title">
<option>Default</option>
</select>
There are a bunch of examples that I have found, but nothing specifically related to what I am looking for, unless the force is not with me today.
Is there a link someone can point me to?
The below script will load the dropdown list from the JSON received from the PHP Page.
$(function(){
var items="";
$.getJSON("yourPHPPage.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.ID+"'>"+item.Name+"</option>";
});
$("#a1_title").html(items);
});
});
Assuming the received JSON is in this format
[ { "ID" :"1", "Name":"Scott"},{ "ID":"2", "Name":"Jon"} ]
Another thing i noticed is that you are doing SELECT * FROM table name to get the items. I do not think you should do that. You should do only two columns (ID & NAME , if you you have those columns in your table.).
Here is a JSFiddle example to show how to fetch data from the JSON.
// retrieve value and text from ajax
var html = "<option value=\""+value+"\">"+text+"</option>";
$("#a1_title").append(html);
I have same problem, your suggestion is work
HTML & JS
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
$(function(){
var items="";
$.getJSON("get-data.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.name+"</option>";
});
$("#a1_title").html(items);
});
});
</script>
<select id="a1_title">
<option>Default</option>
</select>
</body>
</html>
php
include 'configurations/db-connections.php';
$q = "select id, name from college";
$sql = mysql_query($q);
$data = array();
while($row = mysql_fetch_array($sql, true)){
$data[] = $row;
};
echo json_encode($data);