SQL Database Text Field AutoComplete Results

I am trying to create an autocomplete function in a text box, but the result should come from my SQL database.

Here is the code I'm trying to set up:
index.php

<html lang="en"> <head> <meta charset="utf-8"> <title>jQuery UI Autocomplete - Default functionality</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <link rel="stylesheet" href="/resources/demos/style.css"> <script> $(function() { var availableTags = [ "autocomplete.php"; ]; $( "#tags" ).autocomplete({ source: availableTags }); }); </script> </head> <body> <div class="ui-widget"> <label for="tags">Tags: </label> <input id="tags"> </div> </body> </html> 

EDIT : I changed the contents of the variable availableTags and turned it into var availableTags = <?php include('autocomplete.php') ?>;

Variable availableTags is a source of words, so I'm trying to change it and instead put the name of the file where the selection from my database takes place.

Here is my autocomplete.php file:

  <?php include('conn.php'); $sql="SELECT * FROM oldemp"; $result = mysqli_query($mysqli,$sql) or die(mysqli_error()); while($row=mysqli_fetch_array($result)) { echo "'".$row['name']."', "; } ?> 

EDIT : also changed the contents of the while loop and turned it into

 $name=mysqli_real_escape_string($con,$row['name']); $json[]=$name; 

How to insert extracted words from autocomplete.php into an accessible tag variable?

EDIT / UPDATE . A list is displayed there when I type text in a text box, but there is no text in it. I know that it loads, but the word itself does not appear in the list.

+6
source share
5 answers

Solved my problem.

Enter the script as follows:

 <!-- WITHOUT THESE THREE BELOW, THE AUTOCOMPLETE WILL LOOK UGLY OR WILL NOT WORK AT ALL --> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <script> $(function() { $( "#tags" ).autocomplete({ source: "autocomplete.php" }); }); </script> 

And autocomplete.php (where we get the data to fill in the autocomplete input field):

 <?php include("conn.php"); /* ESTABLISH CONNECTION IN THIS FILE; MAKE SURE THAT IT IS mysqli_* */ $stmt = $con->prepare("SELECT description FROM table"); /* START PREPARED STATEMENT */ $stmt->execute(); /* EXECUTE THE QUERY */ $stmt->bind_result($description); /* BIND THE RESULT TO THIS VARIABLE */ while($stmt->fetch()){ /* FETCH ALL RESULTS */ $description_arr[] = $description; /* STORE EACH RESULT TO THIS VARIABLE IN ARRAY */ } /* END OF WHILE LOOP */ echo json_encode($description_arr); /* ECHO ALL THE RESULTS */ ?> 
+3
source

When a string is used, the Autocomplete plugin expects the string to point to a URL resource that will return JSON data.

 source: "autocomplete.php" 

Therefore you need to return a JSON object.

 $json = false; while($row=mysqli_fetch_array($result)) { $json[] = array( 'name' => $row['name'] ); } echo json_encode($json); 
+3
source

Your autocomplete.php file,

 include('conn.php'); $sql="SELECT * FROM oldemp"; $result = mysqli_query($mysqli,$sql) or die(mysqli_error()); //Create an array $arr = Array(); while($row=mysqli_fetch_array($result)) { array_push($arr,$row['name']); } header('Content-Type: application/json'); echo json_encode($arr) ?> 

The result will be a JSON array that can be directly used in JavaScript. Consequently, the script will be something like -

 var availableTags = []; $.ajax({ url:"autocomplete.php",success:function(result){ availableTags = result }}); 
+3
source

JQuery UI autocomplete can take 3 different types of source values:

  • an array containing a list of things to fill a car filled with
  • A string containing the URL of a script that filters the list and sends us the results. The plugin will accept the text entered into it and send it as a term parameter to the query string added to the specified URL.
  • Function which retrieves data and then calls a callback with that data.

The source code uses the first, an array.

 var availableTags = [ "autocomplete.php"; ]; 

What autocomplete says is that the string "autocomplete.php" is the only thing on the list of things to autocomplete with.

I think you tried to insert it with something like this:

 $(function() { var availableTags = [ <?php include("autocomplete.php"); /* include the output of autocomplete as array data */ ?>; ]; $( "#tags" ).autocomplete({ source: availableTags }); }); 

This is likely to work fine if you assume that the list of things returned from the database will always remain short. The implementation of this method is rather fragile, because since you just push the original output from PHP to your JS. If the returned data contains " , you may need to use addSlashes to avoid it. However, you must modify the query to return a single field, not * , maybe you only need one field as a label in the autocomplete of not the entire line.

The best approach, especially if the list could potentially become very large, is to use the second method:

 $(function() { var availableTags = "autocomplete.php"; $( "#tags" ).autocomplete({ source: availableTags }); }); 

This will require changes to the back-end script that captures the list so that it performs filtering. This example uses a prepared statement to ensure that the data provided by the user in $term does not open you until the SQL injection :

 <?php include('conn.php'); // when it calls autocomplete.php, jQuery will add a term parameter // for us to use in filtering the data we return. The % is appended // because we will be using the LIKE operator. $term = $_GET['term'] . '%'; $output = array(); // the ? will be replaced with the value that was passed via the // term parameter in the query string $sql="SELECT name FROM oldemp WHERE name LIKE ?"; $stmt = mysqli_stmt_init($mysqli); if (mysqli_stmt_prepare($stmt, $sql)) { // bind the value of $term to ? in the query as a string mysqli_stmt_bind_param($stmt, 's', $term); mysqli_stmt_execute($stmt); // binds $somefield to the single field returned by the query mysqli_stmt_bind_result($stmt, $somefield); // loop through the results and build an array. while (mysqli_stmt_fetch($stmt)) { // because it is bound to the result // $somefield will change on every loop // and have the content of that field from // the current row. $output[] = $somefield; } mysqli_stmt_close($stmt); } mysqli_close($mysqli); // output our results as JSON as jQuery expects echo json_encode($output); ?> 

Some time has passed since I worked with mysqli, so this code may require some configuration, since it has not been tested.

It would be nice to get used to using prepared statements, because if used correctly, they make SQL injection impossible. Instead, you can use the usual unprepared statement, avoiding every element provided by the user, mysqli_real_escape_string , before inserting it into the SQL statement. However , this is very error prone. Just forget about avoiding one thing in order to open yourself up with attacks. Most of the main β€œhacks" in recent history are related to sloppy coding, which represents SQL injection vulnerabilities.

If you really want to stick with an unprepared statement, the code will look something like this:

 <?php include('conn.php'); $term = $_GET['term']; $term = mysqli_real_escape_string($mysqli, $term); $output = array(); $sql = "SELECT name FROM oldemp WHERE name LIKE '" . $term . "%';"; $result = mysqli_query($mysqli,$sql) or die(mysqli_error()); while($row=mysqli_fetch_array($result)) { $output[] = $row['name']; } mysqli_close($mysqli); // output our results as JSON as jQuery expects echo json_encode($output); ?> 
+3
source

Just a suggestion for an autocomplete file. Sorry, I would add a comment above, but I don't have enough information about writing this.

After successfully implementing useless code, I noticed that my server overhead went through the roof. It seemed that there were some bots, like the beginning of the script, although there were no letters entered in the input area. I did a little test in the autocomplete file and found that it would query my database, even if the term was empty.

So, I just concluded the whole autocomplete script with the if statement ... so ...

 <?php if(!empty($_GET['term'])) { include('conn.php'); $term = $_GET['term']; $term = mysqli_real_escape_string($mysqli, $term); $output = array(); $sql = "SELECT name FROM oldemp WHERE name LIKE '" . $term . "%';"; $result = mysqli_query($mysqli,$sql) or die(mysqli_error()); while($row=mysqli_fetch_array($result)) { $output[] = $row['name']; } mysqli_close($mysqli); // output our results as JSON as jQuery expects echo json_encode($output); } ?> 

... and now my server is back to normal.

0
source

All Articles