autocomplete with MySQLi and php(via Autocomplete UI) - php

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

Related

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!

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

multiple values suggestion in textbox with jquery autocomplete

Could someone kindly help me adding some modifications to my php code so that it allows users to get more than one auto-suggestion? (Now it works fine for one value, but I would like that he/she receives auto suggest for more values, (for example after inserting a comma, again auto-complete suggestions will be shown ).
This is the HTML code:
<p><label>Actor/actress:</label><input type='text' name='name' value='' class='auto'></p>
<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 type="text/javascript">
$(function() {
//autocomplete
$(".auto").autocomplete({
source: "actorsauto.php",
minLength: 2
});
});
</script>
and this is php code:
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', 'xxxxxx');
define('DB_NAME', 'imdb');
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn=new PDO('mysql:dbname=imdb;host=localhost', 'root', 'xxxxx');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT name FROM name WHERE name LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['name'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
}
?>
I am newbie in jquery and php and appreciate all your ideas.
You can put together a where statement by spliting the search term, for example at every space the user typed. Let's say he searched for music cd. The following code would get everything that has the string cd or music in it.
$stmt = $conn->prepare('SELECT name FROM name WHERE :where');
if($_GET['term']){
$termParts = explode(' ', $_GET['term']);
$whereParts = array()
foreach($termParts as $term){
$whereParts[] "name LIKE '%".$term."%'";
}
$where = implode(' OR ', $whereParts);
} else {
$where = 1;
}
$stmt->execute(array('where' => $where));

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

Populate select box from database using jQuery

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

Categories