How to integrate Rgraph with PHP and MySQL? - php

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');

Related

Using arrays to feed Google datetime chart plot

I have meteorological data that I am retrieving through MySQL and can see it through phpMyAdmin. I am trying to plot stuff but I get no data in the plot.
My code is
<?php
// connect to database
$conn = mysqli_connect('localhost', 'root', 'station', 'meteobridge');
// check connection
if(!$conn){
echo 'Connection error: ' . mysqli_connect_error();
}
// write query for data
$sql = 'SELECT ID,TempInCur,TempOutCur FROM mystation';
$dateFormat = 'SELECT DateTime FROM mystation';
// make query & get result
$result = mysqli_query($conn, $sql);
$dtresult = mysqli_query($conn, $dateFormat);
// fetch the resulting rows as an array
$dailyMeasurements = mysqli_fetch_all($result, MYSQLI_ASSOC);
$dtArray = mysqli_fetch_all($dtresult, MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html>
<?php include('templates/header.php'); ?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'TempIn');
data.addColumn('number', 'TempOut');
data.addRows([
[ <?php $dtArray[0]['DateTime'] ?>, <?php echo $dailyMeasurements[0]['TempInCur'] ?>,<?php echo $dailyMeasurements[0]['TempOutCur'] ?>],
[ <?php $dtArray[1]['DateTime'] ?>,<?php echo $dailyMeasurements[1]['TempInCur'] ?>,<?php echo $dailyMeasurements[1]['TempOutCur'] ?>],
[ <?php $dtArray[2]['DateTime'] ?>,<?php echo $dailyMeasurements[2]['TempInCur'] ?>,<?php echo $dailyMeasurements[2]['TempOutCur'] ?>]
]);
var options = {
title: 'Temperaturas',
//curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
<?php include('templates/footer.php'); ?>
</html>
The values for $dailyMeasurements[*]['TempInCur'] are 27.1, and 28.7 for $dailyMeasurements[*]['TempOutCur']. And the values of $dtArray[0]['DateTime'] are 2020-12-27 16:58:26, 2020-12-27 17:03:28, 2020-12-27 17:08:31.
The reason I am adding data with only the first few indexes of my arrays is because when I tried using the whole array (a long time ago), I would have more errors without understanding the problems. I tried making a simple example where I could try to figure out as a beginner what's going on and what is wrong. That made it possible to even get the following image of the resulting dataless plot.
If you have a way to feed the arrays directly to Google charts then that's even better! My intention was to figure out that after I am able to produce a plot.
I'm not sure but you get an associative array.
You should convert this array to an object
const objDatas = JSON.parse($dtArray);
then
GoogleCharts.load("current", { packages: ['corechart'], callback: drawChart });
function drawChart() {
//use objDatas.yourProperty
It worked for me
first, the sql. it looks like all columns are coming from the same table,
so why not include them all in the same query...?
from...
$sql = 'SELECT ID,TempInCur,TempOutCur FROM mystation';
$dateFormat = 'SELECT DateTime FROM mystation';
to...
$sql = 'SELECT DateTime,TempInCur,TempOutCur FROM mystation';
next, build your array in php...
// make query & get result
$result = mysqli_query($conn, $sql);
$rows = array();
while($row = mysqli_fetch_array($result)){
$rows[] = array($row['DateTime'], $row['TempInCur'], $row['TempOutCur']);
}
then write it to the page in the addRows method...
data.addRows(<?php echo json_encode($rows); ?>);
see following snippet...
<?php
// connect to database
$conn = mysqli_connect('localhost', 'root', 'station', 'meteobridge');
// check connection
if(!$conn){
echo 'Connection error: ' . mysqli_connect_error();
}
// write query for data
$sql = 'SELECT DateTime,TempInCur,TempOutCur FROM mystation';
// make query & get result
$result = mysqli_query($conn, $sql);
$rows = array();
while($row = mysqli_fetch_array($result)){
$rows[] = array($row['DateTime'], $row['TempInCur'], $row['TempOutCur']);
}
?>
<!DOCTYPE html>
<html>
<?php include('templates/header.php'); ?>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'TempIn');
data.addColumn('number', 'TempOut');
data.addRows(<?php echo json_encode($rows); ?>);
var options = {
title: 'Temperaturas',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
<?php include('templates/footer.php'); ?>
</html>

How can I return the ID based from its first name and last name in autocomplete in PHP?

Here is the index.php code (I've got this online, credits to the owner):
<HTML>
<HEAD>
<TITLE> Ajax php Auto Suggest </TITLE>
<link href="css/style.css" rel="stylesheet" type="text/css">
<SCRIPT LANGUAGE="JavaScript" src="js/jquery.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript" src="js/script.js"></SCRIPT>
</HEAD>
<BODY>
<center>
<div class="main">
<div class="">scriptime</span></div>
<div id="holder">
Enter Keyword : <input type="text" id="keyword" tabindex="0"><img src="images/loading.gif" id="loading">
</div>
<div id="ajax_response"></div>
</div>
</center>
</BODY>
</HTML>
And here is the .php code (the config is working just fine).
<?php
include("config.php");
$keyword = $_POST['data'];
$sql = "select idPerson, firstName, middleName, lastName from ".$db_table." where ".$db_column." like '".$keyword."%'";
//$sql = "select name from ".$db_table."";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result))
{
echo '<ul class="list">';
while($row = mysql_fetch_array($result))
{
$str = ($row['idPerson']);
$str1 = ($row['firstName']);
$str2 = ($row['middleName']);
$str3 = ($row['lastName']);
//$start = strpos($str,$keyword);
//$end = similar_text($str,$keyword);
//$last = substr($str,$end,strlen($str));
//$first = substr($str,$start,$end);
$final = '-'.$str.' '.$str2;
echo '<li><a href=\'javascript:void(0);\'>'.$str.' - '.$str1.' '.$str2.' '.$str3.'</a></li>';
}
echo "</ul>";
}
else
echo 0;?>
THIS IS THE OUTPUT:
If I click the value, I want that the textbox would return its ID only. How can I do that? I really need help. I still suck at this.
Well it is a bad practice to show the ID in the text field itself. What if the user wants to type in again? Of course you can do anything with jQuery, but I would suggest you to display the id in front of the field after it's selected.
Try the code below, where we have our first name last name in a div, with a unique id retrieved from the database, and whenever this div is clicked, we append the id and display it to the user.
Your PHP code:
<?php
include("config.php");
$keyword = $_POST['data'];
$sql = "select idPerson, firstName, middleName, lastName from ".$db_table." where ".$db_column." like '".$keyword."%'";
//$sql = "select name from ".$db_table."";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result))
{
echo '<ul class="list">';
while($row = mysql_fetch_array($result))
{
$str = ($row['idPerson']);
$str1 = ($row['firstName']);
$str2 = ($row['middleName']);
$str3 = ($row['lastName']);
//$start = strpos($str,$keyword);
//$end = similar_text($str,$keyword);
//$last = substr($str,$end,strlen($str));
//$first = substr($str,$start,$end);
$final = '-'.$str.' '.$str2;
echo "<li><a href='javascript:void(0);'><div class='nameHolder' id='".$str."'>".$str1." ".$str2."</div></a></li>";
}
echo "</ul>";
}
else
echo 0;?>
Add this JavaScript (rather, jQuery) to your page:
<script type="text/javascript">
$(document).ready(function(){
$(".nameHolder").click(function(){ //check if any of the names is clicked
if ($(".showID")[0])
{
$('.showID').remove(); //remove if an id was shown before
}
var selectedID = $(this).attr('id'); //get the 'id' of the selected name
$(".list").append("<b class='showID'>ID: "+selectedID+"</b>"); //append it to our HTML
});
});
</script>
Although, this merely depends on the way you are doing the autocomplete function, and it could be manipulated easily using jQuery. But well, this is an approach to achieve what you're thinking of!

autocomplete with MySQLi and php(via Autocomplete UI)

I am trying to make an autocomplete php interacts with database, but find more than 10 online resource, cannot make it work with my database.
Here is the index.php code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script>
$(function() {
//autocomplete
$("#model").autocomplete({
source: "search.php",
minLength: 1
});
});
</script>
</head>
<body>
<form action='' method='post'>
<p><label>Model:</label><input type='text' id="model" name='model' class='model'/></p>
</body>
</html>
Here is the search.php:
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '123456');
define('DB_NAME', 'inventory');
if (isset($_GET['term'])){
$return_arr = array();
$conn = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME);
$stmt = $conn->stmt_init();
$term = '%'.$_GET['term'].'%';
$stmt = $conn->prepare("SELECT name from items WHERE name like ?");
$stmt->bind_param("s", $term);
$stmt->execute();
$stmt->bind_result($models);
while( $row = $models){
$return_arr[] = $row['name'];
}
echo json_encode($return_arr);
}
?>
And some tutorial use fetch_array() that is not working on my script why? It only work with regular loop such as while loop to store array from database and then use foreach to echo every rows. I am using $mysqli->fetch_array().
Which part is wrong?
You should do this:
Replace the "bind_result" line with this (just for convenience):
$stmt->bind_result($name);
Then replace your while loop with this:
while ($stmt->fetch()) {
$return_arr[] = $name;
}
And it should work.
Basically for each column in your query you add a variable in the bind_result statement and use those when iterating over the results;
use below codes and go through the url#,
http://www.codexworld.com/autocomplete-textbox-using-jquery-php-mysql/
//get matched data from skills table
$query = $db->query("SELECT * FROM skills WHERE skill LIKE '%".$searchTerm."%' ORDER BY skill ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['skill'];
}
//return json data
echo json_encode($data);

Highcharts and JSON problems

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']);

Unable to run my HTML code in google chrome

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]));
}

Categories