Creating a Form that will Search a MySQL Database

You should not use this code on a production website.

Warning: This tutorial uses old techniques. It is insecure and will leave your server vulnerable to SQL Injection attacks.This tutorials also uses mysql_ functions that are no longer support. For updated tutorials look for a PDO or MySQLi tutorial.This post will be delete or revised in the future.

In this tutorial I will show you how to add a simple search box to query a MySQL database. This tutorial is a continuation of the “How to Access a MySQL Database Using PHP” tutorial. Since writing that original tutorial I have created a local WAMP test environment. I have created the database “test” with a table “testable”. The table contains the following fields:

I have added some sample data to this table.

For our search to work we will have to create two files. One file will be the PHP script to search our form and the other will be an HTML page containing our form and passing the search variable to our PHP file.
I will start by create an search.htm file. Below you will see the basic structure of our simple HTML page.

		<title>Search the Database</title>

Next we will add the form. Notice that the action=”search.php” and the method=”post”. This is basically telling the web server to send Post variables to the search.php page. Another important thing to note is the input box name field. This field, name=”term” , this will pass whatever is in the input box on as a post variable named “term”. We also add a submit button.

		<title>Search the Database</title>


	<form action="search.php" method="post">
  	 Search: <input type="text" name="term" /><br />
    <input type="submit" name="submit" value="Submit" />


Now on to search.php . The first thing I did was to simple echo the post variable to make sure the information is getting passed from the search form.

      echo $_POST['term'];

If you variable is not being displayed then something is wrong. If your search term is displayed then you can move on. We can delete the echo code from our php file now.
First make a connection to your database


mysql_connect ("localhost", "testuser","password")  or die (mysql_error());


Now select your test database


mysql_connect ("localhost", "testuser","password")  or die (mysql_error());
mysql_select_db ("test");


Next we are going to store the post variable as $term and build our query. As you can see we are searching the first name field. We are searching for a first name like %$term%. The % character is a wild card for 0 or more charcters. So if we had ‘bob’ in our database and we entered the ‘bob’ in the search box it would return the results. With the % charcters around the term we could also search for ‘ob’ and it would return the results for bob, and any other name containing ‘ob’.

mysql_connect ("localhost", "testuser","password")  or die (mysql_error());
mysql_select_db ("test");

$term = $_POST['term'];

$sql = mysql_query("select * from testtable where FName like '%$term%'");


The next step is to execute the query and display the results.

mysql_connect ("localhost", "testuser","password")  or die (mysql_error());
mysql_select_db ("test");

$term = $_POST['term'];

$sql = mysql_query("select * from testtable where FName like '%$term%'");

while ($row = mysql_fetch_array($sql)){
	echo 'ID: '.$row['ID'];
	echo '<br/> First Name: '.$row['FName'];
	echo '<br/> Last Name: '.$row['LName'];
	echo '<br/> Phone: '.$row['Phone'];
	echo '<br/><br/>';


Now I will test it out. Since I know ‘Bob’ is in the database I will search for him.

If all goes well you should have these results returned/

So we can search for First names only. If you want to give the user the ability to enter either a first name or a last name change your query to this:

$sql = mysql_query("select * from testtable where FName like '%$term%' or LName like '%$term%' ");

To test that query I did a simple search for the letter ‘o’. Which should return several first names and last names that contain the letter.

So there you have it a simple basic database search form. I hope this all makes sense, I am writing this at 4:00am and am a bit tired. As always feel free to ask questions.

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join the TeamTutorials mailing list and get the latest tips, tricks, and special discounts for members only.

Thanks! Please click the link in the email we just sent you to confirm.

  • wow! its amazing.

  • Zippo

    Thanks mate simple yet powerful I dont know what I’d do if it wasn’t for guys like you who take time out to help others

  • Really, the form works how writes this tutorial. Many thanks to the author.

  • Ohhhhh!
    This is really working.

  • Shufi really helped me a lot, thanks to the author.

  • C

    how can i change the text style of the database results? do i need to name the page with the search form as .php or .html? thanks.

  • Franky

    Damn this works like a charm! Many thnx for the creator of this code 🙂

  • Amit


    Can anyone tell me how can i search in this above mentioned table with a full name, not just by giving first name or last name..

    ex: search criteria – “Bob Jhonson”

  • Akshaye

    As others before has pointed out, this is really a great simple explanations.

    I would like to design a searchable form for an Estate Agency whereby a person can look for example:

    (House, bungalow, appartment, studio) with price range and locations.

    I would be much grateful, if a great soul could post an explanation how to do this. Thanks.

  • Спасибо, очень понравилось!

  • mesjasz

    thanks!! 😀

  • saf

    i looked everywhere and this is the only solution that worked!

  • wspanda

    On the html/css page, the code calls for the search.php file and on the search.php file is where the results are displayed. Can you give an example where the result is displayed in the html/css page instead of the results staying on the search.php?

  • Kevin


    This is a great search form and has been a learning curve for me 🙂
    I’ve managed to change this to work with MS Access, but i would like
    to know is it possible to put this into a table with the field names
    running across the top and the correct data below in rows….
    Any help would be great

    Kind Regards,


  • ming

    thanks a lot

  • antony

    The code works fine. But, like to have the code that also gives a “Name not found” message if the Name is not present in the database.
    Can any one help?

    • Add

      if (!isset($term))
      echo "We dont seem to have a search parameter!";

    • Forgive me for my mistake :(. In order ro display messages the way u want just add


      if ($numrows == 0)
      echo "Sorry, your search: " . $term . " returned zero results";
      else {
      echo "Search Result for " . $term . "";


    • Above paste


      And then paste this code in the place you want the message to show up


      if ($numrows == 0)
      echo "Sorry, your search: " . $term . " returned zero results";
      else {
      echo "Search Result for " . $term . "";


  • ciaran pender


    This is a great tutorial and exactly what I have been looking for,although I am having a problem.At the very start of the tutorial you say to create a HTML file that links into the search.php file just to make sure that the variable entered into the search bar is displayed,well it won`t display my variable entered -it opens a new tab which remains blank.I know that it is connecting to the search.php page beacuse when I change form action=search.php in the HTML to form action = searc.php it tells me that there is an error where as when I enter the correct file name it remains blank-any ideas?

    Thanks alot

  • imran

    thanx man ….very helpfull thing for guy like me who is very new to PHP ..

  • ciaran pender

    Can anyone help my above problem,I need to fix this asap

  • mike

    thank for the help….

  • Pobuk

    Thank you so much Mr John Ward. You are doing a lovely job here. Your codes are simple and very effective.

  • Thank You very much John! It was really very Helpful.

  • al kan

    i tried this script .simple and useful.
    if u can add a code that add a picture with link.

  • octavian

    Great stuff you have here and not only this tutorial, all of them.

    Thanks, really helpfull 🙂

  • Joan

    Thank you so much for a wonderful tutorial. It really helps beginners like me.

    Is it possible to add or revise the script so if the name entered into the form is not available a message like “Sorry, no records were found” would appear?

    Thank you again.

    • I didn’t test this, but you would modify the while loop to something like this:

      mysql_connect (“localhost”, “testuser”,”password”) or die (mysql_error());
      mysql_select_db (“test”);

      $term = $_POST[‘term’];

      $sql = mysql_query(“select * from testtable where FName like ‘%$term%'”);

      while ($row = mysql_fetch_array($sql)){

      if (isset($row) or $row is null or $row == ”){
      echo ‘ID: ‘.$row[‘ID’];
      echo ‘<br/> First Name: ‘.$row[‘FName’];
      echo ‘<br/> Last Name: ‘.$row[‘LName’];
      echo ‘<br/> Phone: ‘.$row[‘Phone’];
      echo ‘<br/><br/>’;
      echo “term: $_POST[‘term’] not found”;

      What you want to do is check to see if the array is returned. If it has been echo the results, if not echo “no results found”.

  • Joan

    Thank you so much – I’ll give it a try.

  • i am having this Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\wamp\www\search demo\search.php on line 9

  • That means you have some kind of error with your query. Most likely you are not using the same variable that you stored the results to.

  • i am gettin gthe following when trying to run:
    Parse error: syntax error, unexpected ‘)’, expecting T_PAAMAYIM_NEKUDOTAYIM in C:\Inetpub\vhosts\\httpdocs\tyh\search.php on line 9

    any ideas??

  • Muhammad

    thanks.. its really help a lot..

  • rajesh

    simply superb::::::::::::::::::::::::::
    try giving more examples like these, so that we can refer easily!

    And many many thank’s for you solution.

  • Ronnie

    Thanks a lot, this was very helpfull.
    have been looking a lot for this kind of for, to develope to something bigger, the one i found so far was to complicated and i didnt know what i did wrong.

    i been working with this for just about 40 hours and i could create one to my database very simple.
    Comment, i prefer to make the connection in another file so the login to the database is not writen in the same page.

    this files just hold this

  • jefffan24

    Is there any way to make it search multiple fields in my database. Like lets say I have a database that contains the following fields:


    Is there any way I can make it so that when somebody searches for something in my database it will search all 4 of those fields?

  • Wayne

    I am still struggling.
    Please can I have a more basic step by step instruction to :
    1/ Adding search boxes to my page. 1 Box for Location and 1 Box for Keywords
    2/ Then i want to return results from mysql database table. My database table headins are :
    Location,Retailer,Keywords,Price,Product name,URL LINK

    Based on the search box the results will be displayed as per the above headings. Spent the whole day looking for a basic step by step guide but no joy

  • Thank you john for this great tutorial.
    It works great.
    I have only one question?
    How do I make my result “let’s say the FName” a link to the details page?
    Since I have a details page that shows all the field of the entry and those are to many to display in my search page.
    My detail page haves a record set filter by the variable “attrn”
    And I tried everything I could think of to link the ” echo ‘ FName:’ .$row[‘attr_id’];” to the detail page but no matter how I do it gives me an error.
    I will really appreciate some help.

  • Pingback: Computers by WEB » Blog Archive » Sending E-Mail to validate User Sign-up()

  • Mike

    PERFECT!!! Finally someone that wrote a script that didnt have to be altered! My type of fellow programmer here!! Cant wait to check out the rest of the stuff you wrote.

  • Harsha

    ‘Thanks a lot. This is very helpful.

  • Paul

    Thank you so much for this wonderful code and extremely easy to follow tutorial.

    I have been searching for this type of thing for the past few weeks and have spent many hours trying and failing to use tutorials/code found elsewhere.

    This does exactly what I was looking for and took minutes to set up.

    So, once again, thank you greatly.

  • A Chakraborty

    an endless no. of thanks 2 u man!!!gr8 job helped me a lot.thnx again…hope 2 get more help from u in future..

  • Jim Layton

    The ONLY working code on the subject I could find after days of looking….nice work.

    Now the $64,000 question is how to display the results in a form that can be edited/update when required.

    Cash and prizes for anyone who can help….seriously.

  • Falanas

    Thanks a lot I got it all. But how do we link, say Bob so that when Bob is clicked we are able to get more information about him e.g. Location, ID No., Department e.t.c.

    Thank you again.

  • Rhian

    Brilliant tutorial, thanks so much – worked first time.

  • this is a good tutorial:D it’s complete though i haven’t tried it out yet.. does anyone here knows how to generate a USERNAME from getting a user’s input (input: LAST NAME,FIRST NAME,ID) in php???thanks

  • We’re in the process of a redesign and adding a search field was vital, our new UK pub directory will have a simple search query and this turorial was very helpful

    thank you

  • Mike W

    Thanks for the tutorial. I know that I can use that effectively. Question: How would you search for a Date.. For example, I want to find records whose date is later than say 12/25/2009


  • I agree Peter.Thanks.

  • zoloo

    thank’s it is very good example hope u all good thing

  • rashoood

    Parse error: syntax error, unexpected T_WHILE in E:\wamp\www\UGHacker\search.php on line 9

    i need this help fast email me if u can
    [email protected]

    this is the full thing

    mysql_connect ("localhost", "test","test") or die (mysql_error());
    mysql_select_db ("ughacker");

    $term = $_POST['term'];

    $sql = mysql_query("select * from remote where topic like '%$term%' or author like '%$term%' ")

    while ($row = mysql_fetch_array($sql)){
    echo 'ID: '.$row['id'];
    echo ' First Name: ‘.$row[‘topic’];
    echo ‘ Last Name: ‘.$row[‘date’];
    echo ‘ Phone: ‘.$row[‘author’];
    echo ”;


    i edited some stuff in the result but thats what i want it to be

  • (because no one has said it yet)
    If you use this code in a real webpage, you’ll easily get hacked through SQL Injection. Don’t forget to escape the user input using mysql_real_escape_string()


    Hope this saves someone from an attack 😉

    • Great point Lukas, After doing some of these tutorials to get peoples feet wet, we were going to do a few on preventing SQL injections but we have been busy and have not posted them yet.

      • Holger

        Thank you for this tutorial!

        What about this detail?
        The tutorialcode above is perfect for me, and it works, but what about mysql_real_escape_string()?

  • yudi

    Awesome tutorial. Thank you.

  • Rob

    Here is my problem

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home3/arcprese/public_html/search.php on line

    Php code:


    mysql_connect("localhost", "arcprese_robert", "password") or die(mysql_error());

    $term = $_POST['term'];

    $sql = mysql_query("select * from updateform where Job_number like '$term'");

    while ($row = mysql_fetch_array($sql)){

    echo ' Work order number: ‘.$row[‘Job_number’];

    echo ”;


    When I create a simple echo to make sure the search is being passed to the search.php page it is. There is something wrong with the
    while ($row = mysql_fetch_array($sql)){
    Please help as I guess i’m blind and need a second set of eyes.

  • There is something wrong with your query. Run the query directly against the database and see if it returns results.

    • ian

      help me…..
      how if i want to show in entire row base on my searching…please… 🙂

  • Rob

    Thank you John. I had an incorrect table name. My table name was updateforms and I was missing the “s”. I swear I stared at this for about 2 hrs and over looked it every time. Thanks again.

  • marsahata

    akh,,, Parse error: parse error in C: \ xampp \ htdocs \ ok \ search.php on line13 ….
    gimana nehhh,
    ngasinya jgn stgh2 dong../?
    yg iklas…

    • ian

      please check your username and password to connect your db….

  • chris

    the script and search works fine. i need help with the . When the results return and it enlarges the table when it cannot fit on the entire screen.

  • collins

    how can i select all thats select anything instead of just Fname

  • Syed Rizvi

    This was great, I got the results right away.
    Thanks a million.

    • Syed Rizvi

      One more thing, what if the search come up blank can we place a message “sorry no suggestions”.
      How can we add this code.
      Thanks in advance.

  • myloginkey

    i am having this Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\wamp\www\demo\search.php on line 9

  • yessssssss, thank youuuuuuuuuuuuuu veryyyyyy Much.
    this tuto is very simple and too good.
    Thank you very much
    Can you ceate another one which allow Admin to modify the same DataBase ? (php)

  • Jestin

    thank uuuuuuuuuuuuuu

  • salkini

    I got some problems relating theme together. When I use the search the php code appears instead of the database info. What should I do?

    • salkini

      i worked it out. thanks

  • ashwani

    hii good work………………….

  • Hello.
    How do you get this to return a url with an image?


  • Joe

    I am using Drupal with xampp.
    I put the form code into a Drupal page.
    Then I put the php file into
    It returns:
    Page not found
    The requested page could not be found.
    Please help-I have been working on a database query for over a month now using Drupal and everything I have tried is not working!

  • Pingback: Auto Increment Prefix | jieme()

  • Nicholas Chamberlain

    Hi John,
    Another grateful person. Got it working straight away. Had to say thanks.
    However if you have the time I would like to know how to query two fields. I have played around with the AND statement and my limited knowledge but can’t figure out the code.

  • eirini

    Hello there!
    Thank you for your very useful tutorial!!!! I would like to make a question. I don’t want to use the % characters with the variable $term because i want the search to give me result only for the specific string i give. But when i try to do that
    ex. $sql = mysql_query(“select * from reservations where code like ‘$term'”);
    it sends me to a blank page while it should give me one result. Have you any ideas about this????

  • kurnianto

    how if i want make the result of searching with all entire Row..

    Thx for your help….

  • Manas

    I am adding one more thing here:
    If we have some thousand of records of data in our database. After searching the result it will display all records in one pages.Can we add pagination in the above example thats 10 pr 15 nos. of records are display per page…like this

  • Manas

    Hello kurnianto

    What do you mean by entire Row?

  • Paul

    Hi, bill tutorial. Your work is amazing. i was wondering how add thumbnail images to your data when you search for them?

  • very nice!

  • shehmen

    please i have a problem of designing a search form that queries only particular field in the database tnx

  • Thank you very much, you make my day ! Great TUT , keep on.

  • nawaz bazmi

    i need some thing like this.
    but i want to input data direct from text, or excel file to the database and then read it with this method can any one hellp me that how to insert data and read it.

  • Derwin

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in D:\xampp\htdocs\db\search.php on line 6

  • Pat

    This is seriously one of the best tutorials I’ve found! I can actually understand it. Woooo! Thanks a lot!

  • this is amazing @@

  • This solved my every problem with the search stuff.

  • Joe

    Thankyou so much! I was looking for ages for my search form to work!! You rock!

  • nice tutorial about MySql.. Thanks……

  • Aaron

    Hi, thanks a bunch, this worked great. Especially the part where you show how to search for multiple columns in your database for the same term.

  • David Martin

    Need help/guidance…

    Great script! I’ve tweaked it to work with SQL Server 2005. But I have one small problem, I can’t get it to search for and display a specific date.

    I want the user to be able to search for a specific record by entering a specific date, for example, enter “03/02/2011”. In my database, the date is displayed as 3/2/2011. I just can’t get any results to display in the search results.

    Would you mind looking at my section of PHP code to see how I could improve it and get a date to display? I’m able to search for anything except by date. I just don’t have enough PHP experience to get it to work.

    Thanks for any help or advice you can provide…

    HTML page section:

    Date(Enter dates in a 00/00/0000 format)

    PHP script section:


    $connection_string = 'DRIVER={SQL Server};SERVER=EBSPSQL3\EBSDSS2;DATABASE=PPAD';

    $user = 'PPadUser';
    $pass = 'rmot22';

    $connection = odbc_connect( $connection_string, $user, $pass );

    $term = $_POST['term'];

    $result=odbc_exec($connection,"SELECT date, serialnum FROM patriot1 WHERE date LIKE '$term'");

    while ($row = odbc_fetch_array($result)) {

    $date = substr($row['date'],0,10);

    echo "\n”;
    echo “Date\n”;
    echo “Pad ID\n”;
    echo “\n”;
    echo “\n”;
    echo “$date\n”;
    echo “$row[serialnum]\n”;
    echo “\n”;
    echo “”;


  • David Martin

    Let me try this again. The PHP code did not display correctly in my first post when I pasted it in. I’ll comment it out to see if it will display properly.

    HTML section:

    //Date(Enter dates in a 00/00/0000 format)

    PHP section:


    //$connection_string = 'DRIVER={SQL Server};SERVER=EBSPSQL3\EBSDSS2;DATABASE=PPAD';

    //$user = 'PPadUser';
    //$pass = 'rmot22';

    //$connection = odbc_connect( $connection_string, $user, $pass );

    //$term = $_POST['term'];

    //$result=odbc_exec($connection,"SELECT date, serialnum FROM patriot1 WHERE date LIKE '%$term%'");

    //while ($row = odbc_fetch_array($result)) {

    //$date = substr($row['date'],0,10);

    //echo "\n”;
    //echo “Date\n”;
    //echo “Pad ID\n”;
    //echo “\n”;
    //echo “\n”;
    //echo “$date\n”;
    //echo “$row[serialnum]\n”;
    //echo “\n”;
    //echo “”;


  • gaurav

    Great Code…thanks alot

  • harry

    Hi, i’m getting the displayed results, but how do it get the results to be displayed on my website?

    for example when someone may search food, it’ll show all items that are associated with food.


    • I am having the same problem, is there any way to query exact results? instead of LIKE use ‘=’ or something?

      $sql = mysql_query(“select * from patient where id_number like ‘%$text%'”);

      if ($row = mysql_fetch_array($sql)){
      echo ‘ID: ‘ .$row[‘id’];
      echo ‘ First Name: ‘ .$row[‘first_name’];
      echo ‘ Last Name: ‘ .$row[‘last_name’];
      echo ‘ Business Name: ‘.$row[‘business_name’];
      echo ‘ ID Number: ‘ .$row[‘id_number’];
      echo ”;
      } else{
      print “NOT FOUND”;

      • if ($row = mysql_fetch_array($sql)){

        this line is wrong. you have to use while($row=mysql_fetch_array)

  • Pingback: Access a MySQL Database Using PDO |

  • I needed help with the query and %$term% did the trick. Thanks for making this tutorial available.

  • Martin

    Thank you very much! I really needed this and I’m very grateful! 🙂

  • g

    dude I am so glad that I came across your page because I was getting desperate.

    This tutorial rocks!!!!

  • surendra

    good link………..

    thxs a lots

  • Newbiesss

    hi, im facing some problems here,when i search, it manage to display the search item, but the whole row related to the searched item in mysql fail to display.

    below is my code:


    mysql_connect("localhost", "root", "mysql") or die(mysql_error());
    mysql_select_db ("test");

    $term = $_POST['term'];
    $sql = mysql_query("SELECT * FROM testing WHERE Name LIKE '%$term%'");

    while($row = mysql_fetch_array($sql))

    echo 'ID: '.$row['ID'];
    echo ' Name: ‘.$row[‘Name’];
    echo ‘ pay: ‘.$row[‘pay];
    echo ‘ debt: ‘.$row[‘debt];
    echo ‘ hobby: ‘.$row[‘hobby’];}


    let say i enter bob, and the display is


    anyone knows why i fail to display those field?

    • Solfratara

      It looks like a couple of apostrophes are missing – namely [‘pay] should read [‘pay’]
      and [‘debt] should read [‘debt’]
      Hope this helps!

      • Newbiesss

        Thanks for helping. it works now 😀





  • ka

    Hello, it’s great, thank you… I have little problem:

    Parse error: syntax error, unexpected T_STRING in /search.php on line 2

    This is my code:

    mysql_connect ("hz-mysql1", "mysql34358", "abc")  or die (mysql_error());
    mysql_select_db ("mysql37611");
    $term = $_POST['term'];
    $sql = mysql_query("select * from cenik where katalogove_cislo like '%$term%'");
    while ($row = mysql_fetch_array($sql)){
        echo 'ID: '.$row['ID'];
        echo ' katalog: ‘.$row[‘katalogove_cislo’];
        echo ‘ Barva: ‘.$row[‘barvy’];
        echo ‘ 1_5: ‘.$row[‘Phone’];
        echo ”;

    Where is the mistake? Thank you!!

  • Ismail Shifau

    Search Results..

    Delivered Date
    Received By

    while ($row = mysql_fetch_array($result)){
    echo "”;
    echo $row[‘id’];
    echo “”;
    echo $row[‘name’];
    echo “”;
    echo $row[‘address’];
    echo “”;
    echo $row[‘orgin’];
    echo “”;
    echo $row[‘weight’];
    echo “”;
    echo $row[‘delivered_date’];
    echo “”;
    echo $row[‘received_by’];
    echo ” \n”;


    what am i doing wrong here, i’m trying to publish all the data in table.. but what i see is like this

    Int_no Name Address Orgin Weight Delivered Date Received By
    RF029895288SG AINTHU MPL SG 0.2 2016-06-20 SALEEM df sdsdf f sdfsd sdfdfdf 0000-00-00 dff a a a a

  • Ismail Shifau

    sorry missed out some there..

    below here is the code again

    Search Results..

    Delivered Date
    Received By

    while ($row = mysql_fetch_array($result)){
    echo "”;
    echo $row[‘id’];
    echo “”;
    echo $row[‘name’];
    echo “”;
    echo $row[‘address’];
    echo “”;
    echo $row[‘orgin’];
    echo “”;
    echo $row[‘weight’];
    echo “”;
    echo $row[‘delivered_date’];
    echo “”;
    echo $row[‘received_by’];
    echo ” \n”;


    Please assist.

  • Bryan

    Thanks a lot, works perfectly.

  • Newbiesss

    hi, im trying to modify this program,
    what im doing is,
    my wepage will only display many” someone’s BUTTON”
    once it is clicked, it would display all details related to someone.

    im trying to create many buttons, and assign each button for each person.
    eg: [Bob’s Button]
    [Emilio’s Button]
    [Yuko’s Button]….

    if we click one of the buttons,
    let say i click Bob’s Button, then it would link to a page display all details about Bob.

    however, i dont know how to assign each button for each person.

    below is my code, i dont think its correct, please help me write or assign in a proper way or give me some idea on how to create this function.

    Thanks !!

    • Newbiesss

      form action=”search.php” method=”post”
      ????(how to assign to bob button)???
      type=”submit” name=”submit” value=”Bob’s Button”

      form action=”search.php” method=”post”
      ????(how to assign to Emilio button)???
      type=”submit” name=”submit” value=”Emilio’s Button”

      form action=”search.php” method=”post”
      ????(how to assign to Yuko?)???
      type=”submit” name=”submit” value=”Yuko’s Button”

  • Newbiesss
  • This search script is the best !

    Thanks !

  • I change some fields, and now i can see the data on a Table

    Search the Database



    mysql_connect("localhost","database","password")or die (mysql_error());

    $term = $_POST['term'];
    $sql = mysql_query("select * from search where Prefix like '%$term%' or PartNum like '%$term%' or MfgDC like '%$term%'");

    echo "


    while ($row = mysql_fetch_array($sql)){

    echo “”;
    echo “” . $row[‘Prefix’] . “”;
    echo “” . $row[‘PartNum’] . “”;
    echo “” . $row[‘MfgDC’] . “”;
    echo “” . $row[‘Quantity’] . “”;

    echo “”;
    echo “”;


  • Great job guys.. I will surely put a link about this website in mine.. 🙂 <3 this site:)

  • Matt

    How do I change the font color of query results? Using the above tutorial as example, let’s say I wanted all phone number results to appear in red font. Would I edit the HTML file or the PHP file and what changes would I make?

    • Anonymous

      You could do this with css, javascript, or edit the php that is returned. echo ‘<br/> <span style=”color:red”> First Name: </span>’.$row[‘FName’];

    • Thoufeeqcty

      U just put font style inside the echo like this  echo’Phone: ‘.$row[‘Phone’];’;

  • Kiran Tamang

    Thanks dude..for your hard work..

    It works…I’ve googled a lot..finally got this page..I’ve tested in my PC..Hurray!!! I am helps me a lot

  • Thank you very much for searching code from mysql database….

  • LJ

    please help me how to search in textbox driven by drop down menu

  • LJ

    heres my form

    <form method="post" action="”>
    Seach for:


    can anyone give some PHP script ? thanks in advance!

  • Thanks my friend, it really works…………………..

  • u simply super,

    i have small request. this search send even with single character like when
    u type b search gives all the members in the databse contain b letter in theier name u pls pls pls pls tell me eliminate that single chracter

    • Rafiq

      only remove % symble

  • good search form thank you for supporting us..

  • Thanks John very nice tutorial for new users like me

  • Ola

    It’s interesting, thank for the tutorial

  • This is awesome, thank you for this code, it really helped me

  • Mind blowing boss. Really you seem to be a boss. I liked your work very much. please help me to build up a search box to search database as it is in the board exams of Bangladesh. That means there will be option for inserting roll no and section to search the result.How come i can do that knowing almost nothing about php and MySql.please pave me the way

  • hi

    thanks for this php search tutorial. It helps for us in php development project

  • Looking at at ..Works Magically.Smart codes

  • Pingback: Creating a Form that will Search a MySQL Database | Hitlanka()

  • This is excellent! Does anyone has a simple script like this for entire site content search?

  • Prem

    small fault dude… make it $term instead of %$term%.. then code goes welllanyway thanks for postin…..

    • Anonymous

      The % is intentional. It is a wild card character in the query so that the term will be found within other phrases.

  • BanuThangaraj

    how to display the content  from the user form after click submit button in the admin form

    • Anonymous

      That is explained above. If you are having a specific problem I’d be glad to help. 

  • Vaibhav

    Easy Method for undershand

    Thanks a Lot

  • Tapashm42

    if provide multiple search options then it would be more helpful to me.

  • Shivaraj Gowdars

     Can you give more detailed code. like searching local website?

  • Talloasis

    It worked, it worked Eureka!!! it worked, thank you very much, your existence is a blessing to me. Just the first time i tried it, it worked.
    Please i will welcome new tutorials.

  • Marie

    what should i do if i added a drop down list to have a more specific location to search? thanks. 🙂

  • Whojstall11

    why do i keep getting
    mysql_fetch_array() expects parameter 1 to be resource, boolean given in X:xampphtdocsdumbietestphp.php on line 9

     for some reason it doesnt like the $sql

    • Anonymous

      mysql_fetch_array() expects a mysql resource as input. Most likely something is wrong with your query that is causing it to fail.

      • that worked i dont have the database enter write. But how can i add more to the where clause like an OR statement

  • Mihai

    Thank you very much! I appreciate your post.

  • Null

    thanks a million lines of code!!!!

  • Yvonne

    You are a lifesaver. Thank you very much!

  • Sa1im

    thanks this is great! 😀

  • Brent Emmerich

    getting this error 

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL 

    on line 9 any help is greatly appreciated.

    • C1734321

      something is wrong with your mysql_querry. Check if you have the same table name as in the tutorial

  • ns

    How do I make this happen in WordPress?

  • dar12345

    thanks men your a php-god ,

  • dar12345

    dude can you make a simple login with database .. it so hard for me to understand those !!  I wish i could be great like you 

  • Aaa

    And if you have 2 terms you can use

    $term1 = $_POST[‘term1’]; $term2 = $_POST[‘term2’];
    $sql = mysql_query(“SELECT * FROM table WHERE firstname like ‘%$term1%’ and lastname like ‘%$term2%'” );

  • Aneeq Tariq

    This is the simplest code to select and display records from MySQL database table and display in PHP.

    $cn=mysql_connect($db_host,$db_user,$db_password) or die(mysql_error());
    mysql_select_db($db_name,$cn) or die(mysql_error());

    $sql = “SELECT field_name FROM table_name”;
    $rs = mysql_query($sql) or die(mysql_error());

    while($row = mysql_fetch_array($rs)){

    echo $field_name = $row[“field_name”];
    echo “”;




  • jonah

    Great code….
    But how would I generate an error message if the name the user enters in the textfield is not in the database.

    e.g. Search: ‘bobb’//user types bobb

    Error:sorry this name does not exist in the database….//generated error

    • Jereeth

      $sql = mysql_query(“select * from tblstu where id=’$term'”);
      if (mysql_num_rows($sql) <= 0) {
      // no results
      echo 'No results found. Check your ID';
      } else
      while ($row = mysql_fetch_array($sql)){

      • Awais

        That worked…thanks…stay blessed:-)

  • Gildas

    It worked like charm, only what to be changed is logins and DB details and you’re done.

  • Kabil M
  • Danish Farman

    simple jonah type in following:

  • Danish Farman

    simple jonah type in following:

    type in
    between div tags
    type in between php tags
    echo “Error:sorry this name does not exist in the database….generated error” ;

  • RahmanAulia

    Hi John,
    How to add a message when the result is 0?

  • Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource 

    I keep getting this ? What is wrong?

    • Generally that means that the mysql_query function didn’t return a valid mysql resource. Usually a syntax error in the query.

    • C1734321

      check if you have the same table name as in the tutorial

  • Ppchtourou

    can you please tell me how to add link
    for exemple

        echo ‘ First Name: ‘.$row[‘FName’];
     i want

        echo ‘ First Name: ‘.$row[‘FName’]; with

    to add

    thanks to help me

  • Jabousanyang113

    thanx so much. googled and came across your site and adapted the code to my database and it worked. 

  • Is there a way to have this search multiple tables within a single DB?

  • Guest

    I am getting this error message:

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
    in (location on computer) on line 9
    What does that mean?Thank you

  • vlade

    Nice post. Thanks!

  • Plana

    Great tutorial. But I have a drop down in my form – how to use the option value in the fetch_array? Help?


  • Dsbpac

    Thank you very much for the tutorial it was great. Any way you can do a little add on to this code to only display say 10 results per page because if you have massive amount of results then…

  • Tauseef

    Thanks for the tutorial was running for like an hour before getting to this page.

  • guest

    thanks and nice post.

  • Adtype99

    thank you ,Grea t

  • N3lson

    thank you

  • choyits


  • Ricky

    Really Thanks….!

    4 am whooooo!!!

  • Phamson9861

    That’s very good. 
    With person don’t known much English, The news is easy to understand.
    It’s very great to me and the people say other’ languages.

  • deuce

    i have a column of data that is a 15 digit value that i am searching . . . 

    when i use [where Roll like ‘%$term%’] it works fine . . .

    However, I’d like it to only produce the result that matches the searched term exactly, not like values . . .

    so then how come when i do this it wont work?
    [where Roll=’%$term%’] 

    • deuce

      Found my own solution right after posting 😛

      [where Roll='”.$term.”‘”]

  • Balanced Designer

    This has got to be the best code tutorial ever! Very, very simple and fast to implement. Took me less than 5 minutes to get my database searchable. thanks.

  • Dan

    Wow, this really helped me alot!! THANKS!! You explained everything really well :).

  • Kingsley

    This is the easiest PHP/MySQL search tutorial I can find online. Thank you!

  • why this code says it is error:

    while ($row = mysql_fetch_array($sql)){

    • naqeeb

      i am also having the same problem

      • rehat

        i got it. you need to check your Database name or table name

  • tnx for this tuts…

  • Todd

    What if you would like to search all fields in a row for a specific keyword?

  • Rehman

    How i can make search box suggest words match in database table fields.

  • DIllan

    Thanks very helpful now to implement it with Google maps API 🙂

  • clem


  • hi, i would like to know how to make a link in each individual record in order to display their details and how about the pagination? tq.

  • ricardo

    how to make an error message when it is return to 0

  • Joanne

    wow!! Thanks for this code, It helps a lot!!! 🙂

  • amoramore

    Nice i luv it

  • iamrich22

    i got this error when i run this script

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:xampphtdocssearch.php on line 9

    my database name is test1

    tablename is testable what does ‘term’ mean here?

  • iamrich22

    i am getting the desired result but also getting this notice

    Undefined index: ID in C:xampphtdocsphpsearch.php on line 10

    line 10 is
    echo ‘ID: ‘.$row[‘ID’];

  • Bob

    Fatte mille prove ma non va!

  • Mitch from LGP

    Thank you very much, you helped me big time. 🙂

  • Neha

    thanku thanku thanku thanku sooooooooooooo much

  • dfd


  • LiRuiKe

    Hey, John! Great tutorial. Very helpful. Well-written. You’re awesome.
    The next thing I’m trying to do is get the search result to appear on the same page as the search, rather than having a PHP echo jump to a new page. Is there an easy way to do that?

    • You would need to use an ajax request for that. Similar to what happens in this tutorial: . Instead of checking for an email adress, you pass the search params to the php page. You’ll get the results back and use JavaScript to display them on the page.

      • Jason Harris

        WRONG – run your PHP query and results on the same page as the form. For your form action, specify the same page as your form and query code.

        If your form is on multiple pages in a site (ie footer, sidebar), for your form action, call a specific page, say results.php. Whatever site page (including results.php) the script is called from, it will show on results.php.

        AJAX would be a nicer implementation, but if it is beyond you right now, not necessary.

  • AngelBello

    Hi, thanks for the tip.
    I made it just like the example but it didnt work with my localhost.
    Although I was able to make it work in my online web hosting.

    But for some odd reason, doesnt matter what you type in the search field, even if you leave it blank and hit the submit button it retrieves ALL data in that table??? Would it have something to do with the server??

  • sss


  • triskelionpopoy

    There’s a logic error guys.. because even you don’t put anything to the search field it gives you result. the bad thing is all the record will be display.. so how can i resolve that. Anyone??

    • fourcs

      write a condition that requires that something be entered in the search field.

      • jocelyn

        may i know how to write such a condition that requires something to be entered into the search field?

  • ratedpg

    wow very nice tutorial i really learned this one THANKS!!!

  • Humbled

    Great Great Great Example. Very Simple yet helpful. I’ve came across many tutorial but this has helped me. Thanks John Ward!

  • Awais

    Thanks for the great guide…worked for me like a charm…i have a question…how we are going to do in you code some addition which goes like if the query is valid(the thing which is being searched exists ) it shows up and if it does not exits then it says that there is no term of query…like that….thanks in advance…

  • Prasanna

    thanks u so much..i ve one query that how can i display the details in table ?..plz help me..

  • MarkL

    I’m receiving this error for this line: $term = $_POST[‘term’];
    Parse error: syntax error, unexpected T_VARIABLE in /home/content/
    Any ideas would be greatly appreciated.

    • MarkL

      Thanks, it has been resolved.

      • ian


  • Malinda

    Can this be used for a DELETE button? Say I want the DELETE button to search the database table to delete a record, but I don’t want the button in a loop that shows at the end of each record row. How would I do that?

    • Malinda

      I got it to work! But it displays at the top “DELETE failed: Query was empty” on the ouptput when it actually deleted the record selected for deletion. Why? How do I get rid of that incorrect error message?

  • Pedrogator

    Great tutorial, simple, step by step. Thanks a bunch

  • sykhairi

    SUPER DUPER THANKSSSSSSSS! U helped me a lot!

  • mitch

    not working, the rest of the field does not display, why???

    • mitch

      its working now 🙂 Thhhaaankkkss 🙂

  • Deena

    thanks lot… this session more useful for me…..

  • kelley

    I keep on getting this error not matter what I try. What am I doing wrong? Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in ____________on line 9

    • kelley

      got it sorted thanks

  • kelley

    Can I get the result to open on the same page rather than another window?

  • kelley

    how to display as a table?

  • Elements typically seen on movie screens were guns drawn and cleavages exposed.
    The style of a well used movie theater can be carried out using the structural arranging
    as part of your room. In some cases, surround sound is not possible in low frequency; however,
    it is not the case with Panasonic SC-PT480EB-K.

    Feel free to visit my homepage; Nos pires voisins streaming

  • Every weekend i used to pay a visit this wweb site, as i wish for enjoyment, ffor the reason thatt this this website conations
    actually pleasant funny stuff too.

  • I like the helpful info you supply to your articles.
    I’ll bookmark your blog and take a look at once more right here frequently.
    I am quite certain I’ll be told lots of new stuff proper right here!
    Best of luck for the following!

  • Hey there! Would you mind if I share your blog with myy zynga group?
    There’s a lot of folks that I think would really appreciate
    youur content. Please let me know. Thanks

  • Marvelous, what a weblog it is! This website provides useful facts to us,
    keep it up.

  • tresuno

    thanks great help:)

  • Mynvosa

    Thank you! Thank you so much!
    You have no idea how much this has helped me out!

  • shantaram mali

    when i search record from database ,, that time when I enter search data in the text box then page redirect at search.php.. but in search.php page after clicking on add to cart button then it will show again all records except those record I want..

  • ian

    not working for me I get this error

    “Notice: Undefined index: term in C:xampphtdocsNode_Searchsearch.php on line 5

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:xampphtdocsNode_Searchsearch.php on line 10

    my code is below

    Line 5
    $term = $_POST[‘term’];

    line 10

    while ($row = mysql_fetch_array($sql)){

  • Pingback: Creating An Inventory Database |()

  • nel

    you save me from getting a grade of incomplete in database subject!! THANK YOU

  • kitty mane

    my company wanted Employee Pay Stub earlier this week and came across a website that hosts a searchable database . If others need to fill out Employee Pay Stub also , here’s a


    Good article, Thanks!