Pages Navigation Menu
 

Creating a Form that will Search a MySQL Database

Beautiful WordPress Themes

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.

<html>
	<head>
		<title>Search the Database</title>
	</head>
	
	<body>
	
		
	
	</body>
</html>

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.

<html>
	<head>
		<title>Search the Database</title>
	</head>

	<body>

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


	</body>
</html>

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.


<?php
      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


<?php

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

?>

Now select your test database


<?php

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’.

<?php
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.

<?php
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.

235 Comments

  1. wow! its amazing.

  2. 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

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

  4. Ohhhhh!
    This is really working.

  5. yeahh..it really helped me a lot, thanks to the author.

  6. 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.

  7. Damn this works like a charm! Many thnx for the creator of this code :)

  8. Hi,

    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”

  9. Hello
    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.

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

  11. thanks!! :D

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

  13. Hello,
    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?
    Thanks

  14. Hi,

    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,

    Kev

  15. thanks a lot

  16. 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!";
      exit;
      }

    • 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

      $numresults=mysql_query($sql);
      $numrows=mysql_num_rows($numresults);

      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 . "";
      }

      ?>

  17. Hello

    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

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

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

  20. thank for the help….

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

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

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

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

    Thanks, really helpfull :)

  25. 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:

      <?php
      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/>’;
      }else{
      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”.

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

  27. 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
    s

  28. 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.

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

    any ideas??
    Thanks

  30. thanks.. its really help a lot..

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

    And many many thank’s for you solution.

  32. 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

  33. 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:

    CustomerName
    HomePhone
    WorkPhone
    CellPhone

    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?

  34. 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

  35. 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.

  36. 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.

  37. ‘Thanks a lot. This is very helpful.

  38. 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.

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

  40. 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.

  41. 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.

  42. Brilliant tutorial, thanks so much – worked first time.

  43. 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

  44. 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
    Peter

  45. 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

    Thanks,
    Mike

  46. I agree Peter.Thanks.

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

  48. 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
    samurai-hacker@live.com

    this is the full thing

    <?php
    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

  49. (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()

    See:
    http://php.net/manual/en/function.mysql-real-escape-string.php
    http://en.wikipedia.org/wiki/SQL_injection

    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.

      • 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()?

  50. Awesome tutorial. Thank you.

  51. 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:

    <?php

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

    mysql_select_db("updateform");
    $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.

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

    • John…
      help me…..
      how if i want to show in entire row base on my searching…please… :)

  53. 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.

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

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

  55. 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.

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

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

    • 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.

  58. 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
    s

  59. 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)

  60. thank uuuuuuuuuuuuuu

  61. 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?

    • i worked it out. thanks

  62. hii good work………………….

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

    Thanks!
    Amanda

  64. I am using Drupal with xampp.
    I put the form code into a Drupal page.
    Then I put the php file into
    C:\xampp\htdocs>
    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!

  65. 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.

  66. 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????

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

    Thx for your help….

  68. 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

  69. Hello kurnianto

    What do you mean by entire Row?

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

  71. very nice!

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

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

  74. 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.

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

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

  77. this is amazing @@

  78. This solved my every problem with the search stuff.

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

  80. nice tutorial about MySql.. Thanks……

  81. 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.

  82. 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:

    <?php

    $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 “”;
    }

    ?>

  83. 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:

    //<?php

    //$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 “”;
    //}

    //?>

  84. Great Code…thanks alot

  85. 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.

    Thanks.

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

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

  87. Thank you very much! I really needed this and I’m very grateful! :)

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

    This tutorial rocks!!!!

  89. good link………..

    thxs a lots

  90. 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:

    <?php

    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

    ID:
    Name:Bob
    pay:
    debt:
    hobby:

    anyone knows why i fail to display those field?

    • Newbiesss,
      It looks like a couple of apostrophes are missing – namely ['pay] should read ['pay']
      and ['debt] should read ['debt']
      Hope this helps!

      • Thanks for helping. it works now :D

  91. THANKS THANKS THANKS A LOT……….
    THIS QUERY IS WORKING…..

    IT IS VERY HELPFUL TO MY PROJECT WORK….

    THANK U MAN….

    GOD BLESS U
    BY
    DILJITH FROM INDIA

  92. 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:

    <?php
    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!!

  93. Search Results..

    Int_no
    Name
    Address
    Orgin
    Weight
    Delivered Date
    Received By

    <?php
    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

  94. sorry missed out some there..

    below here is the code again

    Search Results..

    Int_no
    Name
    Address
    Orgin
    Weight
    Delivered Date
    Received By

    <?php
    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.

  95. Thanks a lot, works perfectly.

  96. 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 !!

    • 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”

  97. This search script is the best !

    Thanks !

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

    Search the Database

    Search:

    <?php

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

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

    echo "

    Prefix:
    PartNum:
    MfgDC:
    Quantity:
    “;

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

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

    echo “”;
    }
    echo “”;

    ?>

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

  100. 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?

    • 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'];

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

  101. 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 happy..it helps me a lot

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

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

  104. heres my form

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

    Title
    Author

    can anyone give some PHP script ? thanks in advance!

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

  106. 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

    • only remove % symble

  107. good search form thank you for supporting us..

  108. Thanks John very nice tutorial for new users like me

  109. It’s interesting, thank for the tutorial

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

  111. 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

  112. hi

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

  113. Looking at at ..Works Magically.Smart codes

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

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

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

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

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

  117. Easy Method for undershand

    Thanks a Lot

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

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

  120. 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.

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

  122. 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

    • 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

  123. Thank you very much! I appreciate your post.
     

  124. thanks a million lines of code!!!!

  125. You are a lifesaver. Thank you very much!

  126. thanks this is great! :D

  127. getting this error 

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

    on line 9 any help is greatly appreciated.

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

  128. How do I make this happen in WordPress?

  129. thanks men your a php-god ,

  130. 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 

  131. 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%’” );

  132. 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 “”;

    }
    mysql_free_result($rs);

    Source:
    http://phphelp.co/2012/04/26/how-to-select-and-display-mysql-records-data-in-php/

    OR

    http://addr.pk/acfd
     

  133. 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

    • $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)){

      • That worked…thanks…stay blessed:-)

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

  135. simple jonah type in following:

  136. 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” ;

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

  138. 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.

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

  139. Hello
    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 domain.com/Fname

    thanks to help me

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

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

  142. 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

  143. Nice post. Thanks!

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

    Thanks!

  145. 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…

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

  147. thanks and nice post.

  148. thank you ,Grea t

  149. thank you

  150. THANK YOU SO MUCH!

  151. Really Thanks….!

    4 am whooooo!!! :)

  152. 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.

  153. 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%'] 

    • Found my own solution right after posting :P

      [where Roll='".$term."'"]

  154. 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.

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

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

  157. why this code says it is error:

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

    • i am also having the same problem

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

  158. tnx for this tuts…

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

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

  161. Thanks very helpful now to implement it with Google maps API :)

  162. salamat

  163. 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.

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

  165. wow!! Thanks for this code, It helps a lot!!! :)

  166. Nice i luv it

  167. 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?

  168. 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'];

  169. Fatte mille prove ma non va!

  170. Thank you very much, you helped me big time. :)

  171. thanku thanku thanku thanku sooooooooooooo much

  172. fd

  173. 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: http://teamtutorials.com/web-development-tutorials/validating-email-address-with-php-and-ajax . 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.

      • 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.

  174. 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??

  175. ssssss

  176. 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??

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

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

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

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

  179. 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…

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

  181. 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.

    • Thanks, it has been resolved.

  182. 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?

    • 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?

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

  184. SUPER DUPER THANKSSSSSSSS! U helped me a lot!

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

    • its working now :) Thhhaaankkkss :)

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

  187. 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

    • got it sorted thanks

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

  189. how to display as a table?

  190. 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

  191. 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.

  192. 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!

  193. 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

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

Trackbacks/Pingbacks

  1. Computers by WEB » Blog Archive » Sending E-Mail to validate User Sign-up - [...] July 16, 2008 — Creating a Form that will Search a MySQL Database (37) [...]
  2. Auto Increment Prefix | jieme - [...] Creating a Form that will Search a MySQL Database | Team Tutorials [...]
  3. Access a MySQL Database Using PDO | WebDino.net - [...] Creating a Form that will Search a MySQL Database [...]
  4. Creating a Form that will Search a MySQL Database | Hitlanka - [...] For our search to work we will have to create two files. One file will be the PHP script …

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>