Pages

Auto complete text box with PHP, jQuery and MySql

Thursday, May 17, 2012
In this tutorial I want to show you how easy to do a auto complete text box with PHP, jQuery and MySql.

Firstly download the autocomplete jQuery plugin and extract it to your hard drive.
And then create a folder in your localhost. Copy jquery.autocomplete.css and jquery.autocomplete.js file to your project folder. And you will also need jquery.js. Now we can start our project.

Creating database table


We need to create a table in our database before writing our script. I also add some data for this table. Import following SQL statement via phpMyAdmin or any other MySQL tool.

CREATE TABLE `tag` (
  `id` int(20) NOT NULL auto_increment,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

INSERT INTO `tag` (`id`, `name`) VALUES
(1, 'php'),
(2, 'php frameword'),
(3, 'php tutorial'),
(4, 'jquery'),
(5, 'ajax'),
(6, 'mysql'),
(7, 'wordpress'),
(8, 'wordpress theme'),
(9, 'xml');

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Auto Complete Input box</title>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script>
 $(document).ready(function(){
  $("#tag").autocomplete("autocomplete.php", {
        selectFirst: true
  });
 });
</script>
</head>
<body>
<label>Tag:</label>
<input name="tag" type="text" id="tag" size="20"/>
</body>
</html>

autocomplete.php

This file is called from our jquery script. This php script is easy to follow.
<?php
 $q=$_GET['q'];
 $my_data=mysql_real_escape_string($q);
 $mysqli=mysqli_connect('localhost','username','password','databasename') or die("Database Error");
 $sql="SELECT name FROM tag WHERE name LIKE '%$my_data%' ORDER BY name";
 $result = mysqli_query($mysqli,$sql) or die(mysqli_error());

 if($result)
 {
  while($row=mysqli_fetch_array($result))
  {
   echo $row['name']."\n";
  }
 }
?>
We have done. Run your project and type in your text box you will see following screenshot.

By the way, I use the old jquery plug in this project. If you want to learn new thing, you can learn here and here. I create this tutorial because it is still useful and easy, although it is too old. I will also write about new jquery ui later.
Download Source Code

145 comments:

  1. Thank you for sharing... great job ! would be cool explain how to improve some css customization

    ReplyDelete
  2. Thanks for sharing really cool work

    ReplyDelete
  3. he please, on mouse click event this code is not working properly please can any one help me.

    thanks.

    ReplyDelete
  4. How do you increase the number of items in the list?

    ReplyDelete
  5. Embu Tido: You make a "Limit 20" or another number, in the end of your SQL-statement, I quess.

    ReplyDelete
  6. Hello everyone, I would like to know how to implement urls results by searching the database, so that when clicked, open the reference page. Could you help me?

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. hi thank you for your code but this code does not work for table that contains larger records.

    ReplyDelete
  9. please provide jquery.autocomplete.js,jquery.js,jquery.autocomplete.css files

    ReplyDelete
  10. Sorry but it is not working for me as well , maybe large amount of Data

    can you provide some suggestions Plz !

    ReplyDelete
  11. Hi,
    Amount of data is a problem. I thing "JQuery" should come up with a solution to this problem. Meanwhile you can try a work around. You can assign a value to the "minLength:" method to filter the data extracted from the database and help JQuery's AJAX method function properly. It also makes sense. If number of rows fetched is more than the screen length, it might look awkward. So I suggest, that you assign a value like "minLength: 4". I am sure this will come as a great relief for everyone.

    Arun @ http://www.encodedna.com


    ReplyDelete
  12. sorry dear its not working properly .. please provide another code..
    thanks for try

    ReplyDelete
  13. Is there a way to add autosend form after selecting from dropdown generated by autoselect?

    ReplyDelete
  14. Good job man...
    But I have 2 Questions. What would be edited if
    1. I want to perform search after typing 6 or 8 characters?
    2. And typed character automatically changed into upper case?

    ReplyDelete
  15. Ok I got the solution of first question that is in "minChars:" and trying for finding solution of next question.

    ReplyDelete
  16. hi i have a question i want to send id with this how can it possible ....

    ReplyDelete
  17. please tell me and i want to get this id in hidden field after sending so please tell me the solution for that i m in trouble . :(

    ReplyDelete
  18. how can I more than one auto suggest in a a single page.Please suggest.

    ReplyDelete
  19. Thanks for sharing
    Sharing is caring

    ReplyDelete
  20. hey guys how can i submit form when i select one of the autocomplete result help me..

    ReplyDelete
    Replies
    1. just call a function on onClick

      $(document).ready(function{
      -----do--something------
      });

      Delete
  21. finally i found solution for above problem
    find and hide the following lines in your jquery.js

    // stop default to prevent a form submit, Opera needs special handling
    //event.preventDefault();
    // blockSubmit = false;
    // return false;

    /* var blockSubmit;

    // prevent form submit in opera when selecting with return key
    $.browser.opera && $(input.form).bind("submit.autocomplete", function() {
    if (blockSubmit) {
    blockSubmit = false;
    return false;
    }
    }); */

    ReplyDelete
  22. i need the value for other page what i selected any one can help

    ReplyDelete
  23. Notice: Undefined index: kkk in C:\xampp\htdocs\myfiles\auto.php on line 2
    ajax jquery mysql php php frameword php tutorial wordpress wordpress theme xml

    ReplyDelete
  24. Great coding. Great job. I am learn for many information about your article. Thank you for sharing...
    http://www.dreamdestinations.in/

    ReplyDelete
  25. In autocomplete.php the third line is: $my_data=mysql_real_escape_string($q);
    Mysql_real_escape_string() is deprecated function. But this autocomplete don't
    work properly with mysqli_real_escape_string() function, can't find upper case
    letters. Is there some solution?

    ReplyDelete
  26. Thanks friend. Working Good.

    ReplyDelete
  27. good tutorial thanks-

    ReplyDelete
  28. This comment has been removed by the author.

    ReplyDelete
  29. how to do the sategory and sucategory in php.help me

    ReplyDelete
  30. Great tutorials. nice explanations. Thanks for sharing this information.
    http://www.dreamdestinations.in/

    ReplyDelete
  31. hi please tell me how to implement this in a form
    I mean you are entering data in one text box and dta willl be entered automatically in next text box.
    I am entering the zip code of a specific city in one text box and automatically the respective city will come in the city text box.
    Please tell me the code in PHP connected with MYSQL database as the above one .
    Thanks

    City


    State


    Zip


    ReplyDelete
  32. Thank you friend, very helpful, there is another example, it may help you:
    http://www.bewebdeveloper.com/tutorial-about-autocomplete-using-php-mysql-and-jquery

    ReplyDelete
  33. php code for photo tagging with demo and database

    http://www.lessonwithdemo.com/205/ajax/photo-tagging-like-facebook-without-page-refresh-with-ajax-without-jquery.php/

    ReplyDelete
  34. You can refer to the source code here
    http://www.kythuatmang.net/

    ReplyDelete
  35. buddy great.. its working.thank u

    ReplyDelete
  36. It's Working Great... That's exact I am searching for. Thanks a lot. Thanks again.

    ReplyDelete
  37. itz not working with firefox and explorer....only works with chrome.

    ReplyDelete
  38. try this simple code

    http://freephphtml.blogspot.in/2014/11/textbox-autocomplete-with-jquery-and.html

    ReplyDelete
  39. It's great code thanku so much,
    can you help me for two text filed serach in one table of database plz

    ReplyDelete
  40. hai, its working fine. but if my need is to autocomplete the characters which starts with what i entered.and also dosent matter about lower/upper. how it could be achived. please help my to resolve

    ReplyDelete
  41. i need a slight change in this code..i need a prediction for each user...have a column "user" in my table

    ReplyDelete
  42. how can i add <a href="""... to redirect it to another page, with the value?
    please help me!

    ReplyDelete
  43. How to send extra parameter in your code ?

    ReplyDelete
  44. How to send extra parameter in your code ?

    ReplyDelete
  45. how can i add this feature to angularjs file app.js ..can u plzz send me the code as soon as possible

    ReplyDelete
  46. How can we get variable 'q' in autocomplete.php

    ReplyDelete
  47. What is the value of 'q' here.? It is showing undefined symbol warning and didnt get any suggestions in the textbox..

    ReplyDelete
  48. in my SQL database, my PHP codes, all are defined with UTF-8, but when querying in your script, it appears that problem. Thanks again

    ReplyDelete
  49. hi. i am using this code in my application. its working fine. but my client is asking how to search first letter of word only. like if enter letter 'a' it will display words starting with 'a'. but not with matching letters. is this possible? pls help me.

    ReplyDelete
    Replies
    1. In your autocomplete.php update the %$my_data% in the sql query to $my_data%

      Delete
  50. I was looking for an online writer who offers Master’s Thesis Literature Review errors Correcting Help before I landed on this page. I have enjoyed reading the article and the comments and I will bookmark this site and visit occasionally to read both new and old articles. Thanks for posting this interesting and intriguing article.

    ReplyDelete
  51. take a look at this autocomplete, it's awesome, http://justwebcode.blogspot.com/2017/07/autocomplete-textbox-with-jquery.html

    ReplyDelete
  52. One of the best blog post regarding the Tutorials for Web development and design I would like to know more on these I completed my PMP in Bangalore While I was in Bangalore there were huge set of sub oriented sessions on technology and web developemet

    ReplyDelete
  53. Nice Info about blog Can this be integrated to various platfroms in connecting queries realted to database by opting microsoft dynamics crm training online

    ReplyDelete
  54. This “php ustad” tutorial blog is designed for beginners – to learn php at home step by step using simple programming examples

    ReplyDelete
  55. Thanks for sharing with us that awesome article you have amazing blog.

    Best Linux training in Noida
    Linux Training Institute in Noida

    ReplyDelete
  56. Thanks for sharing information..it is very useful..nice blog
    web designing online training

    ReplyDelete
  57. This is the information i have been looking for man. Great work keep it up.
    http://www.writersonlineessay.org/social-crm-with-ms-dynamics-crm/

    ReplyDelete
  58. Outstanding blog thanks for sharing such wonderful blog with us ,after long time came across such knowlegeble blog. keep sharing such informative blog with us. Machine learning training in chennai
    machine learning with python course in Chennai

    ReplyDelete
  59. Useful information.I bookmarked it.Lucky me I discovered your website accidentally.
    FIND YOUR JOBS HERE : Hyseplacements

    ReplyDelete
  60. This comment has been removed by the author.

    ReplyDelete
  61. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well.

    Telephony System
    Mobile Device
    ted

    ReplyDelete
  62. Superb blog I visit this blog it's extremely marvelous. Interestingly, in this blog content composed plainly and justifiable. The substance of data is exceptionally instructive.
    oracle fusion financials classroom training
    Workday HCM Online Training
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training
    Oracle Fusion HCM Classroom Training

    ReplyDelete
  63. Superb blog I visit this blog it's extremely marvelous. Interestingly, in this blog content composed plainly and justifiable. The substance of data is exceptionally instructive.
    oracle fusion financials classroom training
    Workday HCM Online Training
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training
    Oracle Fusion HCM Classroom Training

    ReplyDelete
  64. This comment has been removed by the author.

    ReplyDelete
  65. Excellent blog I visit this blog it's really awesome. The important thing is that in this blog content written clearly and understandable. The content of information is very informative.
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training
    oracle Fusion Technical online training

    ReplyDelete
  66. Great post! I am actually getting ready to across this information, It's very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.

    Health Care Tipss
    All Time With You
    Article Zings
    Article Zings
    Article Zings
    Article Zings
    Article Zings
    Article Zings
    Health Carinfo

    ReplyDelete
  67. This comment has been removed by the author.

    ReplyDelete
  68. Thank you for your informative article, I have been doing research on this subject, and for three days I keep entering sites that are supposed to have what I am searching for, only to be discouraged with the lack of what I needed. Thank you again.
    Data Science Training in Hyderabad
    Hadoop Training in Hyderabad
    selenium Online Training in Hyderabad
    Devops Online Training in Hyderabad
    Informatica Online Training in Hyderabad
    Tableau Online Training in Hyderabad
    Talend Online Training in Hyderabad

    ReplyDelete

  69. I am really happy to say it’s an interesting post to read . I learn new information from your article , you are doing a great job . Keep it up and a i also want to share some information regarding selenium course and selenium training videos

    ReplyDelete
  70. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.
    Hadoop Training in Hyderabad

    ReplyDelete

  71. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    microservices online training
    best microservices online training
    top microservices online training


    ReplyDelete
  72. I loved the information given above, I appreciate the writing. And yes it’s true that online tuitions can very in a vast way in saving time and money! To get the best Online tutors, visit us on our online website. we teach more them Great information. I really appreciate this great website. 40 other languages. Please Visit!

    Online Tutoring Jobs UK

    ReplyDelete
  73. I must thank you for the efforts you have put in penning this site. I am hoping to check out the same high-grade content by you later on as well. Keep up the good work
    Amazing web journal I visit this blog it's extremely marvelous. Interestingly, in this blog content composed plainly and reasonable. The substance of data is educational
    Java training in Chennai

    Java Online training in Chennai

    Java Course in Chennai

    Best JAVA Training Institutes in Chennai

    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Training

    Java Online Training

    ReplyDelete
  74. The website is looking bit flashy and it catches the visitors eyes. Design is pretty simple and a good user friendly interface. https://autopartsgh.com/

    ReplyDelete
  75. I blog often and I truly thank you for your content! This great article has truly piqued my interest! I will bookmark your site and keep checking for new information about once a week!

    Math Tutors UK

    ReplyDelete
  76. I feel really happy to have seen your webpage.I am feeling grateful to read this.you gave a nice information for us.please updating more stuff content...keep up!!

    Android Training in Chennai

    Android Online Training in Chennai

    Android Training in Bangalore

    Android Training in Hyderabad

    Android Training in Coimbatore

    Android Training

    Android Online Training

    ReplyDelete
  77. Am really impressed about this blog because this blog is very easy to learn and understand clearly.This blog is very useful for the college students and researchers to take a good notes in good manner,I gained many unknown information.


    Data Science Training In Chennai

    Data Science Online Training In Chennai

    Data Science Training In Bangalore

    Data Science Training In Hyderabad

    Data Science Training In Coimbatore

    Data Science Training

    Data Science Online Training

    ReplyDelete
  78. Thank you for sharing with us.






    _____________________________________________________________________
    Online Thesis Help

    ReplyDelete
  79. I am really happy to say it’s an interesting post to read . I learn new information from your article , you are doing a great job . Keep it up

    Devops Training in USA

    Hadoop Training in Hyderabad

    Python Training in Hyderabad

    ReplyDelete
  80. We are well established IT and outsourcing firm working in the market since 2013. We are providing training to the people ,
    like- Web Design , Graphics Design , SEO, CPA Marketing & YouTube Marketing.Call us Now whatsapp: +(88) 01537587949
    : Digital Marketing Training
    Free bangla sex video:careful
    good post outsourcing institute in bangladesh

    ReplyDelete
  81. "Thanks for the Information.Interesting stuff to read.Great Article.
    I enjoyed reading your post, very nice share.data science training"

    ReplyDelete
  82. Thank you for sharing this useful article with us. This blog is a very helpful to me in future. Keep sharing informative articles with us.
    https://www.paygonline.site/

    ReplyDelete
  83. Thank you for sharing this useful article. This blog is a very helpful to me. Keep sharing informative articles with us.

    https://www.france-collectivites.fr/

    ReplyDelete
  84. Great sources for knowledge. Thank you for sharing this helpful article. It is very useful for me.

    https://www.ahmedabadcomputereducation.com/course/laravel-training-course/

    ReplyDelete
  85. Thank you for sharing this useful article with us. This blog is a very helpful to me. Keep sharing informative articles with us.

    https://www.sdsfin.in/services/project-finance-consultants-in-ahmedabad/

    ReplyDelete
  86. Its very informative blog and I am exactly looking this type of blog. Thank you for sharing this beautiful blog.

    https://superurecoat.com/titanium-iso-propoxide/

    ReplyDelete
  87. Thank you for the great information. Keep Sharing it!

    https://saroitapes.com/

    ReplyDelete
  88. Thanks for the Valuable information.Really useful information. Thank you so much for sharing. It will help everyone.

    SASVBA is one of the leading training providers in the country. We provide AI training Course in Delhi accordance with current industry standards, allowing students to find their dream job in the world's leading companies. SASVBA specializes in teaching services, artificial lighting training that imparts practical knowledge through live project-based learning.
    FOR MORE INFO:

    ReplyDelete
  89. Thanks for sharing informative article.

    https://web30india.com/

    ReplyDelete
  90. Thank you for your post, I look for such article along time, today i find it finally. this post give me lots of advise it is very useful for me.
    AWS Training in Chennai

    ReplyDelete
  91. We help students to prepare the research and writing papers which cover both broad and specific course concepts. Our writers are able to help you throughout the entire process of coursework writing, from the selection of your topic, all the way to the submission process.
    http://www.dissertationhomework.com

    ReplyDelete
  92. . Being a custom writing service, we write papers from scratch. Our writers will strictly follow your instructions to create a perfect custom written assignment.

    ReplyDelete
  93. Good blog very informative. I am expecting many more, thanks for this useful blog. We are also providing the best services click on below links to visit our website.
    Oracle Fusion HCM Training
    Workday Training
    Okta Training
    Palo Alto Training
    Adobe Analytics Training

    ReplyDelete
  94. Wow very nice blog .And your post is informative and helpful.Thank you so much for sharing this post .Online Shopping Market

    ReplyDelete
  95. We appreciate you sharing this informative post with us. Continue providing us with helpful content.

    https://www.ownuxglobal.com/

    ReplyDelete