Zingchart not pulling data from MariaDB - php

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>

Related

Update PHP content every 5s using Ajax or Jquery

I'm trying to UPDATE my php page every 5 seconds so the new data can come in into a .json file, so basically what it does, is, it gets the data from the database, and creates a .json file with this data, I need this php file to update every 5 seconds, so the .json file is updating too.
The code (JsonfileAPI.php):
<!DOCTYPE html>
<html lang="pt-br">
<head>
</head>
<body>
<?php
function get_data()
{
$servername = "nps";
$dBUsername = "nps";
$dBPassword = "nps";
$dBname = "nps";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword,
$dBname);
if ($conn->connect_error){
die ("Connection failed". $conn->connect_error);
}
$sql = "SELECT * FROM dados;";
$result = mysqli_query($conn, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = array(
'AutoIncrement' => $row["AutoIncrement"],
'Aparelho' => $row["aparelho"],
'Status' => $row["Status"],
);
}
return json_encode($json_array);
}
$file_name = 'dadosjson' . '.json';
if (file_put_contents($file_name, get_data()))
{
echo $file_name. ' file created';
}
else
{
echo 'There is some error';
}
?>
<script>
$(document).ready(function () {
setInterval(function(){
$.ajax({
url: "JsonfileAPI.php",
type: 'post',
dataType: 'json',
success: function(response) {
$('.time').html(response);
}
});
}, 5000);
});
</script>
You can use this code in your application, I suggest to use separate files like index.php (for your html code) and action.php for PHP script. and don`t need .json file.
Try this, in index.php html part and javascript part like this
$(document).ready(function () {
setInterval(function(){
$.ajax({
url: "action.php",
type: 'post',
// dataType: 'json',
success: function(response) {
console.log(response);
$('.time').html(response);
}
});
}, 5000);
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="time">
</div>
</body>
</html>
Then your action.php file should be like this,
<?php
$localhost = "nps";
$username = "nps";
$password = "nps";
$dbname = "nps";
// db connection
$connect = new mysqli($localhost, $username, $password, $dbname);
// check connection
if ($connect->connect_error) {
die("Connection Failed : " . $connect->connect_error);
} else {
// echo "Successfully connected".$dbname;
}
$sql = "SELECT * FROM dados";
$result = $connect->query($sql);
$output = array('data' => array());
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()) {
$output['data'][] = array(
$row[0],
$row[1],
$row[2]
);
}
}
$connect->close();
echo json_encode($output);
I have checked and it work fine. Think it will be help.

How to get data from a DB(MySQL) and draw real-time graphs from a highcharts

I'm going to use the real-time temperature values stored in MariaDB server to show real-time graphs on the web.
(Temperature values continue to accumulate in real time once every 5 seconds.)
Through a lot of trial and error, I decided that Highcharts.js would be the best tool for drawing graphs.
https://www.highcharts.com/stock/demo/dynamic-update
The link above is the demo source I used.
What I've been trying to do in the most
I've been putting a lot of things into the bar y.
I tried various things in the data.push of series.
(I'm a beginner on coding......)
I didn't know what I typed wrong, so I entered everything. I'm sorry.
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<script type="text/javascript"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
<script>
Highcharts.stockChart('container', {
chart: {
events: {
load: function() {
var series = this.series[0];
setInterval(function() {
$(document).ready(function() {
var url = "https://---include json---.php";
$.getJSON(url, function(json) {
var val= json;
var temp1=(json['temp'][(Object.keys(json['temp']).length)-1]['temp1']);
console.log(json['temp'][(Object.keys(json['temp']).length)-1]['temp1']);
})});
var x = (new Date()).getTime() // current time
var y = temp1;
Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);//연속
}, 1000);
}
}
},
time: {
useUTC: false
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title: {
text: 'TEST test'
},
exporting: {
enabled: true
},
credits:{
enabled:false
},
series: [
{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
y;
for (i = -999; i <= 0; i += 1) {
data.push([
//time + i * 1000,
//Math.round(Math.random() * 100)
]);
}
return data;
}())
}]
});
</script>
The following php code is the php code for json data.
<?php
//Creating Array for JSON response
$response = array();
$servername = "localhost";
$username = "";
$password = "!";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM temp2 order by id asc";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
$response["temp"] = array();
while($row = mysqli_fetch_array($result)) {
$temp = array();
$temp["temp1"] = $row["temp1"];
array_push($response["temp"], $temp);
}
echo json_encode($response,JSON_NUMERIC_CHECK);
} else {
echo json_encode("0 results",JSON_NUMERIC_CHECK);
}
mysqli_close($conn);
?>
The above code values are output as shown below.
{"temp":[
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.82},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":18.05},{"temp1":17.93},{"temp1":17.82},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.82},{"temp1":18.05},{"temp1":17.93},{"temp1":17.93},
{"temp1":17.93}
]}
If you run the code, the graph won't appear on the screen.
I don't know how to print out json's value on the graph.
I translated it using Google translation because I am not good at English. I would like to thank you all for your reply.
Add a content type to the header:
<?php
header("Content-type: application/json; charset=utf-8");
You can use chart.js library. Simple and powerful
https://www.chartjs.org
Here are some example how to use:
https://tobiasahlin.com/blog/chartjs-charts-to-get-you-started/
First of all: Wellcome to SO :)
I think you have the wrong Dataformat for your Data. You have a Array of Objects
[{"temp1":17.93},....]
But the example say:
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
An Array of Array. Try this:
<?php
//Creating Array for JSON response
$response = array();
$servername = "localhost";
$username = "";
$password = "!";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM temp2 order by id asc";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
$response["temp"] = array();
while($row = mysqli_fetch_array($result)) {
$response["temp"][] = array("temp1", $row["temp1"]); // <-- change this line
}
echo json_encode($response,JSON_NUMERIC_CHECK);
} else {
echo json_encode("0 results",JSON_NUMERIC_CHECK);
}
mysqli_close($conn);
?>

Jquery error needs to be fixed: Error of invalid string JSON

Trying to generate a piechart using dropdown menu and api but there is a json error for table showing invalid string.
Pie file
<?php
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'techyari_demos';
// Create connection and select db
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart,table package.
google.load('visualization', '1', {'packages':['corechart','table']});
function drawItems(num) {
var jsonPieChartData = $.ajax({
url: "getpiechartdata.php",
data: "q="+num,
dataType:"json",
async: false
}).responseText;
var jsonTableData = $.ajax({
url: "gettabledata.php",
data: "q="+num,
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var piechartdata = new google.visualization.DataTable(jsonPieChartData);
var tabledata = new google.visualization.DataTable(jsonTableData);
// Instantiate and draw our pie chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(piechartdata, {
width: 700,
height: 500,
chartArea: { left:"5%",top:"5%",width:"90%",height:"90%" }
});
// Instantiate and draw our table, passing in some options.
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(tabledata, {showRowNumber: true, alternatingRowStyle: true});
}
</script>
</head>
<body>
<form>
<select name="pt" onchange="drawItems(this.value)">
<option value="">Select a server:</option>
<?php
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'techyari_demos';
// Make a MySQL Connection
$con = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName) or die(mysql_error());
mysqli_select_db($con,"techyari_demos") or die(mysqli_error());
// Create a Query
$sql_query = "SELECT id, servername FROM server ORDER BY servername ASC";
// Execute query
$result = mysqli_query($con,$sql_query) or die(mysqli_error());
while ($row = mysqli_fetch_array($result)){
echo '<option value='. $row['id'] . '>'. $row['servername'] . '</option>';
}
mysqli_close($con);
?>
</select>
</form>
<div id="chart_div"></div>
<div id="table_div"></div>
</body>
</html>
getpiechartdata
<?php
$q=$_GET["q"];
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'techyari_demos';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
$sql_query="SELECT * from entry";
// $sql_query = "SELECT nickname, name, j2.label, j2.pointsum FROM user JOIN ( SELECT j1.user_id, j1.label, name, hover, j1.pointsum FROM activityfield JOIN ( SELECT user_id, activity_id, label, field_id , SUM( points.points ) AS PointSum FROM points JOIN activity ON points.activity_id = activity.id WHERE points.user_id=" . $q . " GROUP BY points.user_id, points.activity_id, activity.label, activity.field_id ORDER BY points.activity_id ASC ) AS j1 ON activityfield.id = j1.field_id ) AS j2 ON j2.user_id = user.id WHERE pointsum > 0 ORDER BY j2.pointsum DESC;";
$con = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName)or die(mysql_error());;
if (!$con){ die('Could not connect: ' .mysqli_error());}
mysqli_select_db($con,"techyari_demos");
$result = mysqli_query($con,$sql_query);
echo "{ \"cols\": [ {\"id\":\"\",\"label\":\"Name-Label\",\"pattern\":\"\",\"type\":\"string\"}, {\"id\":\"\",\"label\":\"PointSum\",\"pattern\":\"\",\"type\":\"number\"} ], \"rows\": [ ";
$total_rows = mysqli_num_rows($result)or die(mysqli_error());;
$row_num = 0;
while($row = mysqli_fetch_array($result)){
$row_num++;
if ($row_num == $total_rows){
echo "{\"c\":[{\"v\":\"" . $row['date'] . "-" . $row['sname'] . "\",\"f\":null},{\"v\":" . $row['status'] . ",\"f\":null}]}";
} else {
echo "{\"c\":[{\"v\":\"" . $row['date'] . "-" . $row['sname'] . "\",\"f\":null},{\"v\":" . $row['status'] . ",\"f\":null}]}, ";
}
}
echo " ] }";
mysqli_close($con);
?>
gettabledata
<?php
$q=$_GET["q"];
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'techyari_demos';
$sql_query="SELECT date,sname,dbs,status,updatedby from entry";
$con = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName);
if (!$con){ die('Could not connect: ' . mysql_error()); }
mysqli_select_db($con,"techyari_demos");
$result = mysqli_query($con,$sql_query);
echo "{\"c\":[{\"v\":\"" .'date'. "\",\"f\":null},{\"v\":\"" .'sname' . "\",\"f\":null},{\"v\":\"" .'dbs' . "\",\"f\":null},{\"v\":\"" .'status'. "\",\"f\":null},{\"v\":\"".'updatedby'."\",\"f\":null}]}, ";
$total_rows = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)){
echo "{\"c\":[{\"v\":\"" . $row['date'] . "\",\"f\":null},{\"v\":\"" . $row['sname'] . "\",\"f\":null},{\"v\":\"" . $row['dbs'] . "\",\"f\":null},{\"v\":\"" .$row['status']."\",\"f\":null},{\"v\":\"" . $row['updatedby']. "\",\"f\":null}]}, ";
}
/* $result = mysqli_query($sql_query2);
while($row = mysqli_fetch_array($result)){
echo "{\"c\":[{\"v\":\"" . $row['servername'] . "\",\"f\":null},{\"v\":\"" . "\",\"f\":null},{\"v\":\"" . "\",\"f\":null},{\"v\":\" Total \",\"f\":null},{\"v\":\"" . $row['dbs'] . "\",\"f\":null}]}";
}
echo " ] }";*/
mysqli_close($con);
?>
Further to my comments (and others comments), create some classes for re-use and readability, create a config for storage of re-usables, and then finally use json_encode() on arrays to create json strings for your ajax. I don't know if they are correctly formed, but they will be valid json strings:
/config.php
<?php
# Used for universal directory separator compatibility
define('DS',DIRECTORY_SEPARATOR);
# Store absolute paths for easy referencing
define('ROOT_DIR',__DIR__);
define('VENDOR_DIR',ROOT_DIR.DS.'core'.DS.'vendors');
# Store database connection credentials this one spot only
define('DB_HOST','localhost');
define('DB_NAME','techyari_demos');
define('DB_USER','root');
define('DB_PASS','');
# Start user session
session_start();
# Create class autoloader so you don't have to worry about including manually
spl_autoload_register(function($class) {
$path = str_replace(DS.DS,DS,VENDOR_DIR.DS.str_replace('\\',DS,$class).'.php');
if(is_file($path))
include_once($path);
});
/core/vendors/Database.php
<?php
class Database
{
private static $con;
private $query;
# Assign database
public static function init()
{
$db = new Database();
return $db->getConnection();
}
# Creates database connection
public function getConnection()
{
if(self::$con instanceof \PDO)
return $this;
try {
self::$con = new \PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,DB_NAME);
}
catch(\PDOException $e) {
}
return $this;
}
# Used to query database
public function query($sql,$bind=false)
{
if(!empty($bind)) {
foreach($bind as $key => $value) {
$skey = ":$key";
$setBind[$skey] = $value;
$this->query = self::$con->prepare($sql);
$this->query->execute($setBind);
}
}
else {
$this->query = self::$con->query($sql);
}
return $this;
}
# Used to fetch results from database
public function getResults($single=false)
{
$row = array();
while($result = $this->query->fetch(\PDO::FETCH_ASSOC)) {
$row[] = $result;
}
if(empty($row))
return $row;
return ($single)? $row[0] : $row;
}
}
/core/vendors/App.php
<?php
class App
{
# Easily return post values even if they don't exist without drawing errors
public function getPost($key=false)
{
if(!empty($key))
return (isset($_POST[$key]))? $_POST[$key] : false;
return $_POST;
}
# Easily return get values even if they don't exist without drawing errors
public function getGet($key=false)
{
if(!empty($key))
return (isset($_GET[$key]))? $_GET[$key] : false;
return $_GET;
}
# Easily return session values even if they don't exist without drawing errors
public function getSession($key=false)
{
if(!empty($key))
return (isset($_SESSION[$key]))? $_SESSION[$key] : false;
return $_SESSION;
}
# Used to render pages
public function render($file)
{
ob_start();
# Create instance of database
$db = Database::init();
# Include page to render
include($file);
# Assign view
$data = ob_get_contents();
ob_end_clean();
# Return for echo
return $data;
}
}
/index.php
<?php
if(!isset($this)) {
include_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
echo (new App())->render(__FILE__);
exit;
}
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart,table package.
google.load('visualization', '1', {'packages':['corechart','table']});
function drawItems(num) {
var jsonPieChartData = $.ajax({
url: "getpiechartdata.php",
data: "q="+num,
dataType:"json",
async: false
}).responseText;
var jsonTableData = $.ajax({
url: "gettabledata.php",
data: "q="+num,
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var piechartdata = new google.visualization.DataTable(jsonPieChartData);
var tabledata = new google.visualization.DataTable(jsonTableData);
// Instantiate and draw our pie chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(piechartdata, {
width: 700,
height: 500,
chartArea: { left:"5%",top:"5%",width:"90%",height:"90%" }
});
// Instantiate and draw our table, passing in some options.
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(tabledata, {showRowNumber: true, alternatingRowStyle: true});
}
</script>
</head>
<body>
<form>
<select name="pt" onchange="drawItems(this.value)">
<option value="">Select a server:</option>
<?php
$servers = $db->query("SELECT id, servername FROM server ORDER BY servername ASC")->getResults();
foreach($servers as $row) { ?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['servername'] ?></option>
<?php
}
?>
</select>
</form>
<div id="chart_div"></div>
<div id="table_div"></div>
</body>
</html>
/getpiechartdata.php
<?php
if(!isset($this)) {
include_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
echo (new App())->render(__FILE__);
exit;
}
# Internally retrieve the get value
$q = $this->getGet("q");
# Run your general query
$results = $db->query("SELECT * from entry",array($q))->getResults(true);
# Set base array/object
$base = array(
'cols'=>array(
array(
'id'=>'',
'label'=>'Name-Label',
'pattern' => '',
'type'=>'string'
),
array(
'id'=>'',
'label'=>'PointSum',
'pattern' => '',
'type'=>'number'
)
)
);
# Create default array
$base['rows'] = array();
# Loop results, building on base array/object
foreach($results as $row) {
$base['rows'][] = array(
'c'=>array(
array(
'v'=>$row['date'].' - '.$row['sname'],
'f'=>NULL
),
array(
'v'=>$row['status'],
'f'=>NULL
)
)
);
}
# Return results
echo json_encode($base);

How to integrate Rgraph with PHP and MySQL?

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

Livesearch php and ajax

I'm having some troubles with my code, I want it to execute the php file whenever I enter something but it isn't working
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function getStates(value) {
$.post("search.php", {name:value},function(data)
$("#results").html(data);
});
}
</script>
</head>
<input type="text" onkeyup="getStates(this.value)"/>
<br>
<div id="results"></div>
<body>
</body>
</html>
php
<?php
mysqli_connect("localhost", "#", "#") or die(mysqli_connect_errno());
mysql_select_db("#") or die(mysql_error());
$search = $_POST["name"];
$players = mysql_query("SELECT firstname FROM players WHERE firstname LIKE '%search%'");
while($player = mysql_fetch_array($players)) {
echo "<div>" . $players["firstname"] . "</div>";
}
?>
From what I can see,you should change this
'%search%'
to
'%{$search}%'
in
$players = mysql_query("SELECT firstname FROM players WHERE firstname LIKE '%search%'");
EDIT
#user3187651 Assuming you've done everything right on the server side.
Change your javascript to:
function getStates(value) {
$.post("search.php", {name:value},function(data){
$("#results").html(data);
}
);
}
This should get rid of the error in the client side.
You are missing {. Just do:
function xyx(name) {
$.post("search.php", { name: value }, function(data) {
$("#results").html(data);
});
}
There's something that is missing in your code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> //ur getting the jquery via online
<script>
$(document).ready(function(){
$("#textBoxId").change(function() //triggers when you change the value in your textbox
{
var value = $(this).val(); //gets the value of your textbox
$.post("search.php", {id:value},function(data)
$("#results").append(data);
});
}
});
</script>
</head>
<body>
<input type="text" id="textBoxId"/>
<br>
<div id="results"></div>
</body>
</html>
And in your php:
<?php
mysqli_connect("localhost", "#", "#") or die(mysqli_connect_errno());
mysql_select_db("#") or die(mysql_error());
$search = $_POST['id'];
$returnData = "";
$players = mysql_query("SELECT firstname FROM players WHERE firstname LIKE '%search%'");
while($player = mysql_fetch_array($players)) {
$returnData .= "<div>" . $players["firstname"] . "</div>";
}
echo $returnData;
For more secure and creative back-end code, you can use this.
<?php
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'dev_testing';
$mysqli = new mysqli($host, $user, $password, $database);
$username = $_GET['username'];
$username = trim(htmlspecialchars($username));
$like = '%' . strtolower($username) . '%';
$statement = $mysqli -> prepare('
SELECT name, picture, description
FROM users
WHERE lower(name) LIKE ?
ORDER BY INSTR(title, ?), title
LIMIT 20'
);
if (
$statement &&
$statement -> bind_param('ss', $like, $username) &&
$statement -> execute() &&
$statement -> store_result() &&
$statement -> bind_result($name, $picture, $description)
) {
$array = [];
while ($statement -> fetch()) {
$array[] = [
'name' => $name,
'picture' => $picture,
'description' => $description
];
}
echo json_encode($array);
exit();
}
Advantages of the code
Prevents SQL Injection
Orders results from the best match
Sends a JSON response (JSON is light-weight)
Full Tutorial:
Live Search with AJAX, PHP, and MYSQL

Categories