Link to home
Start Free TrialLog in
Avatar of Rodric MacOliver
Rodric MacOliverFlag for New Zealand

asked on

How to create a search field with autocomplete

Hi folks, I need to create a search file that searches in a MySql database in a certain field for something contained in it, for example:

Search for the word or partial word in a varchar field. It should complete itself on real time when typing...
Any help would be appreciated.

Cheers!
Avatar of leakim971
leakim971
Flag of Guadeloupe image

what is your current code client and server side?
what are your knowledges in jquery and php?
I may have something in my teaching library.  If I do, I will post it here.  One caution about auto-complete... you may get too many results if you start the auto-complete process before the client types about 4 or 5 characters.  Consider using LIMIT on your queries.
Avatar of Rodric MacOliver

ASKER

Ray I hope you do as usual you come to my rescue... :)

leakim971: php, unfortunately I don't have a solid knowledge in JQuery but I do know enough I think of php...
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think @leakim971 has you on the right track.  No points for this, but you might want to think about using ORDER and LIMIT clauses in the query shown on line 6.

Best to all, ~Ray
Avatar of zappafan2k2
zappafan2k2

Are you dead set on having an autocomplete?  If you're not comfortable with jQuery or Javascript, you are in for a learning curve, albeit a worthwhile one (in my opinion).  Once familiar with jQuery, though, autocompletes are pretty easy.

If you can give us a link to a page you have started, we can help.

Obviously, leakim971 has written a simple example, but I have three comments in case you aren't familiar with that aspect.
1. You should always escape your search term using mysql_escape_string() or even using PDO.
2. I would advise you to make the search case-insensitive.  See below.
3. It is generally advisable to add the following header to the search file:
header("Cache-Control: no-cache, must-revalidate");  You don't want the page to be cached.

I would modify lines 3 and 5 of @leakim971's code thusly:
$term = mysql_escape_string(strtoupper($_GET["term"]));

// init connexion database
$sql = "SELECT * FROM mytable WHERE UPPER(myfield) LIKE '%" . $term . "%'";

Open in new window

I added a second '%' in line 5.  The way it was before would only match the search term at the end of the field.  If you only want to the search term to match the beginning of the field, remove the first '%' sign.