AcademiaAgriculture & FarmingHumanitiesSocial SciencesSTEM

Simple Search Using PHP and MySQL

Updated on April 30, 2016

I'm going to show you how to create simple search using PHP and MySQL. You'll learn:

  • How to use GET and POST methods
  • Connect to database
  • Communicate with database
  • Find matching database entries with given word or phrase
  • Display results

Preparation

You should have Apache, MySQL and PHP installed and running of course (you can use XAMPP for different platforms  or  WAMP for windows, MAMP for mac) or a web server/hosting that supports PHP and MySQL databases.

Let's create database, table and fill it with some entries we can use for search:

  • Go to phpMyAdmin, if you have server on your computer you can access it at http://localhost/phpmyadmin/
  • Create database, I called mine tutorial_search
  • Create table I used 3 fields, I called mine articles.
  • Configuration for 1st field. Name: id, type: INT, check AUTO_INCREMENT, index: primary

INT means it's integer
AUTO_INCREMENT means that new entries will have other(higher) number than previous
Index: primary means that it's unique key used to identify row

  • 2nd field: Name: title, type: VARCHAR, length: 225

VARCHAR means it string of text, maximum 225 characters(it is required to specify maximum length), use it for titles, names, addresses
length means it can't be longer than 225 characters(you can set it to lower number if you want)

  • 3rd field: Name: text, type: TEXT

TEXT means it's long string, it's not necessary to specify length, use it for long text.

  • Fill the table with some random articles(you can find them on news websites, for example: CNN, BBC, etc.). Click insert on the top menu and copy text to a specific fields. Leave "id" field empty. Insert at least three.

It should look something like this:


  • Create a folder in your server directory and two files: index.php and search.php (actually we can do all this just with one file, but let's use two, it will be easier)
  • Fill them with default html markup, doctype, head, etc.

<!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>
	<title>Search</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>

</body>
</html>
  • Create a form with search field and submit button in index.php, you can use GET or POST method, set action to search.php. I used "query" as name for text field

GET - means your information will be stored in url (http://localhost/tutorial_search/search.php?query=yourQuery)
POST - means your information won't be displayed it is used for passwords, private information, much more secure than GET

<form action="search.php" method="GET">
	<input type="text" name="query" />
	<input type="submit" value="Search" />
</form>

Ok, let's get started with php.

  • Open search.php
  • Start php (<?php ?>)
  • Connect to a database(read comments in following code)

<?php
	mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
	/*
		localhost - it's location of the mysql server, usually localhost
		root - your username
		third is your password
		
		if connection fails it will stop loading the page and display an error
	*/
	
	mysql_select_db("tutorial_search") or die(mysql_error());
	/* tutorial_search is the name of database we've created */
	
	
	
?>

You can go and check if there is no errors.

  • Now go to the <body></body> part of the page
  • I'm using GET method, if you want to use POST, just use $_POST instead of $_GET
  • Also some functions to make it more secure. Read comments in the code
  • Send query to database
  • Check if there is any results
  • If there is any, post them using while loop

<?php
	$query = $_GET['query']; 
	// gets value sent over search form
	
	$min_length = 3;
	// you can set minimum length of the query if you want
	
	if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
		
		$query = htmlspecialchars($query); 
		// changes characters used in html to their equivalents, for example: < to &gt;
		
		$query = mysql_real_escape_string($query);
		// makes sure nobody uses SQL injection
		
		$raw_results = mysql_query("SELECT * FROM articles
			WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%')") or die(mysql_error());
			
		// * means that it selects all fields, you can also write: `id`, `title`, `text`
		// articles is the name of our table
		
		// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
		// it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
		// or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
		
		if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
			
			while($results = mysql_fetch_array($raw_results)){
			// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
			
				echo "<p><h3>".$results['title']."</h3>".$results['text']."</p>";
				// posts results gotten from database(title and text) you can also show id ($results['id'])
			}
			
		}
		else{ // if there is no matching rows do following
			echo "No results";
		}
		
	}
	else{ // if query length is less than minimum
		echo "Minimum length is ".$min_length;
	}
?>

Done!

Now it works. Try different words, variations, editing code, experiment. I'm adding full code of both files in case you think you've missed something. Feel free to ask questions or ask for tutorials.

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>
	<title>Search</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
	<form action="search.php" method="GET">
		<input type="text" name="query" />
		<input type="submit" value="Search" />
	</form>
</body>
</html>

search.php

<?php
	mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
	/*
		localhost - it's location of the mysql server, usually localhost
		root - your username
		third is your password
		
		if connection fails it will stop loading the page and display an error
	*/
	
	mysql_select_db("tutorial_search") or die(mysql_error());
	/* tutorial_search is the name of database we've created */
?>

<!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>
	<title>Search results</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<?php
	$query = $_GET['query']; 
	// gets value sent over search form
	
	$min_length = 3;
	// you can set minimum length of the query if you want
	
	if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
		
		$query = htmlspecialchars($query); 
		// changes characters used in html to their equivalents, for example: < to &gt;
		
		$query = mysql_real_escape_string($query);
		// makes sure nobody uses SQL injection
		
		$raw_results = mysql_query("SELECT * FROM articles
			WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%')") or die(mysql_error());
			
		// * means that it selects all fields, you can also write: `id`, `title`, `text`
		// articles is the name of our table
		
		// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
		// it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
		// or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
		
		if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
			
			while($results = mysql_fetch_array($raw_results)){
			// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
			
				echo "<p><h3>".$results['title']."</h3>".$results['text']."</p>";
				// posts results gotten from database(title and text) you can also show id ($results['id'])
			}
			
		}
		else{ // if there is no matching rows do following
			echo "No results";
		}
		
	}
	else{ // if query length is less than minimum
		echo "Minimum length is ".$min_length;
	}
?>
</body>
</html>

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      sherin 5 years ago

      very nice coding

    • profile image

      adam 4 years ago

      very nice coding thanks

    • profile image

      shahab 4 years ago

      very good

    • profile image

      Kyra 4 years ago

      Thanks...

      Very helpful of you :)

    • profile image

      Vlad 4 years ago

      Access denied for user 'u589737042_maxi'@'10.1.2.7' to database 'search_bar'. :( please help

    • profile image

      gvssi 4 years ago

      thanks lot nice coding

    • profile image

      dockster 4 years ago

      Thank you this is very useful!

    • profile image

      Eoin H 4 years ago

      This is just what I needed, a simple way to help me create a search page on my site... and it works perfectly. Thanks for posting it!

      I would expect as my websites database get filled up more, the search results page would start to get very long. Is there a way to paginate the results so only say 10 results are shown on each page?

      Again, thanks for the above code, many will benefit and learn from it.

    • csk157 profile image
      Author

      csk157 4 years ago from Denmark

      In order to paginate you would use "LIMIT".

      Which would look like:

      SELECT * FROM articles

      WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%') LIMIT 0, 5

      Where 0 is row to start with (offset), and 5 is amount. 0, 5 would get first 5 rows that matched the query.

      so the next page would be: 5, 5

      then 10, 5 - 15, 5 ... etc...

      You will find plenty information about pagination on google, but that's basically how it works :)

    • csk157 profile image
      Author

      csk157 4 years ago from Denmark

      Thank you all for nice comments :)

      You may also want to look into PDO statements (newer stuff) as this article is a bit outdated already :)

    • profile image

      Tejinder Singh 4 years ago

      thank you very much for giving this great info.

    • profile image

      ALEX 4 years ago

      You are the MAN! Thank you!

    • profile image

      foluso 4 years ago

      Please what is happening when your search is only responding to only one search term

    • csk157 profile image
      Author

      csk157 4 years ago from Denmark

      You can do

      ... LIKE '%term1%' OR LIKE '%term2%' OR LIKE '%term3%' ....

      or something similar, is that what you wanted?

    • profile image

      dikimgl 4 years ago

      very useful... add more queries good luck!

    • profile image

      chandan pandey 4 years ago

      nice code..

      thank u dear.....

    • profile image

      fng 4 years ago

      Access denied for user 'root'@'%' to database 'Database_name'

      i got this error whilst connecting and i have put all the correct connection details.. Any help?

    • profile image

      binesh 4 years ago

      Very nice code for searching with any word.

    • profile image

      Patrick 4 years ago

      Hi, i used the code to search and it works very well, but when i asking the system to give me a few fields as a result of the search, i do not get a space between each field, consequently everything ends up as one very long word

      thank you in anticipation for your assistance

    • profile image

      omarluces05 4 years ago

      thank you so much for this simple but great tutorial. :)

    • profile image

      Lasha 4 years ago

      Thank you very much... I done it at first try and it's great script thank you very much again again and again :DDD

    • profile image

      Sumair 4 years ago

      superb work..! its easier and excellent

    • profile image

      omarluces05 4 years ago

      Hi csk157,

      This tutorial really works for me.

      but can you help me on my concern? :)

      Example:

      I'm searching for a NAME.

      "Mary Josephine S. Cruz"

      *when I input 'Mary' it shows the result.

      *when I input 'MARY JOSEPHINE' it shows result.

      **but when I input 'MARY JOSEPHINE CRUZ', without the Middle Initial it shows NO RESULTS.

      What can I do with this? that when I input 'MARY JOSEPHINE CRUZ', it should search either 'MARY' / 'JOSEPHINE' / 'CRUZ' ?

      Hope you can help me. :)

      Thanks.

    • csk157 profile image
      Author

      csk157 4 years ago from Denmark

      omarluces05

      you could either try adding 'OR' between all possible variations which would be kind of sloppy

      or by doing full-text search, some information about it:

      http://dev.mysql.com/doc/refman/5.5/en//fulltext-s...

      so in the end it would be something similar to this:

      SELECT *, MATCH(name) AGAINST ('Mary Josephine Cruz') AS score FROM users WHERE MATCH(name) AGAINST ('Mary Josephine Cruz') ORDER BY score DESC

      results will contain one more column called `score`. The higher the number in that column, the more relevant row it is (better match).

      P.S. you have to add full-text index to the columns you want to match against (please google it)

    • profile image

      Mr Akheel 4 years ago

      Thank you So much Bro.. I was searching script exactly like this.. U r Gr8.. Nice Tutorial.. easy to understand... i'm doing Local Search Project..

    • profile image

      Algis 4 years ago

      good stuff for the begginer :) Thanks a lot!!!

    • profile image

      jenn 4 years ago

      please help am using the code but when i try to search anything i get an error:"minimum legth" and the page is just blank

    • profile image

      lerry 4 years ago

      can i put together a 2 tables in one search button ? :)

    • profile image

      broglah 4 years ago

      hey i've implemented this, search query.

      one question I have modified it so that I have 3 images per row stored in the database(I know this is bad practace but I'm a noob), how could I return these images in the search, i'm going to paginate this also.

      I only want the images returned with the value of the rowID

      any help will be much appreciated.

    • csk157 profile image
      Author

      csk157 4 years ago from Denmark

      I would store images in your website folder (for example in "images" directory), and then would save path to images in database (images/superimage.png)

      If you want to search for them, you need some tags, or titles or any text to differentiate between them.

      When you do something like this, you use LIKE, or MATCH to find rows. (for pagination use look up LIMIT function in SQL and use math for to calculate which entries to get. For instance: first page - LIMIT 0, 5; second page - Limit 5, 5 and so on...)

      To show images just use

      img src="$image_path_from_database"

      I hope that helps

    • profile image

      Manjinder Singh 4 years ago

      Very usefull Post for me,

    • profile image

      Mr Dilip Wijayabahu 4 years ago

      so thanks for this tutorial .it's so help full to my web developing knowledge .

    • profile image

      skr 4 years ago

      thanks boSSSSSSS

    • profile image

      Dermot 4 years ago

      Great tutorial - I finally managed to get text searching working on my forms!

      Im wondering though, how do I implement multi multi form field searching? My SQL command is:

      $result=mysql_query("SELECT * FROM tablename WHERE (firsttablecol LIKE '%".$query['firstformfield']."%') AND (secondtablecol LIKE '%".$query['secondformfield']."%') ", $connection) or die ("Cannot run query");

      but this returns all entries in my MySQL database. I want people to be able to search on either one or both fields, so a form field may also contain empty entries? Thanks

    • profile image

      pals10 4 years ago

      This tutorial was really very helpful for a beginner like myself. Great stuff. :) Could you also help me with the code for inserting/modifying/deleting records from my database where whatever modifications are to be made would be entered via an html form?

    • profile image

      Philip 3 years ago

      How to make exact search? If I search word "Book" I need the result with word "Book" in MySQL row, using this code if I look "Book" it gives me all results with this word like "Books for children", "Books for adults" etc.

    • profile image

      aya adel 3 years ago

      how can i make an search text in data base

    • profile image

      Kemal 3 years ago

      Code is running.. Thank you so much :D

    • profile image

      spyrosL 3 years ago

      Access denied for user 'apache'@'localhost' (using password: NO)

    • profile image

      Nomer 3 years ago

      thanks tro your code its runnig..

      thank you sir

    • profile image

      muziek 3 years ago

      Thanks for the code. But my question is how can i make the info clickable? the search shows my products en their categories but want that if you click on the name that you go to the page of the product

    • profile image

      Mohammad Murad Hosen 3 years ago

      Awesome.Awesome .Awesome

      Thanks bro very very much

    • profile image

      billy miaron 3 years ago

      waoh great tutorial. can you add links to the search results? for example a link to that persons full profile?

      am looking for that.

    • profile image

      Richard 3 years ago

      Hi.

      Thanks for this solution! It is great! I`m new at mysql and php. I did everything as said but stucked at the article making. Where did You make those aticles. Did You made new tables or just made those articles under some "edit0" option?

    • profile image

      Sabbir Jaman 3 years ago

      fine thanks

      i try this carefully...

      thanks this committee

    • profile image

      Selim Alamo 3 years ago

      Hey, perfect code!!!! Thank you!!!

      How can I clear the search field after pressing send button?

      thank you again

    • profile image

      Selim Alamo 3 years ago

      Ah, and one more question please.

      I am using this search plugin for passport number.

      For example, the pass number is 12345678-5 and if I search 12345678- (without the 5) the plugin show me anyway the result, I mean, it searches the whole words, and I would like to search for exact words.

      Thank you!

    • csk157 profile image
      Author

      csk157 3 years ago from Denmark

      @Selim

      For exact search you better use simple comparison. For example:

      SELECT * FROM persons WHERE passport_number = '12345678-5'

      numbers being the query. In this case if it does not find exact match - it won't return any results.

      Regarding clearing the search field after sending form - it should happen automatically after the form is submitted (page is reloaded), if not check that you are not printing $_GET['query'] into value attribute of the text field.

      I hope this helps

    • profile image

      Selim Alamo 3 years ago

      @csk157, thank you very much!

      Last question.

      If you open in your browser the file search.php, you will see an alert message (Minimum length is...). Also, I wanted to make the search just in 1 file, but i have the same message.

      I hope you can help me!

    • csk157 profile image
      Author

      csk157 3 years ago from Denmark

      It has something to do with

      if(strlen($query) &gt;= $min_length){ ... search here... }

      else{ // if query length is less than minimum

      echo "Minimum length is ".$min_length;

      }

      so check if it is correct, and also check that your query is longer that $min_length (if you don't need check - remove 'if' sentence, or if you don't want to print any message, remove 'else' part of 'if')

      make sure that you're not opening (before you submit the form) your page with ?query=something attached in the link

    • profile image

      Alexandre 3 years ago

      Well done and well comment. Thanks!

    • profile image

      Selim Alamo 3 years ago

      Hi csk157!, thank you again for your answer!

      I tried it, but it doesn't work :(

      I mean, everything work fine less the line:

      echo "Minimum length is ".$min_length;

      So, in one file called passport.php I have the passport number search. If it's less than 9 symbols, it means that it is wrong.

      The problem is that when I open the file (passport.php) it shows me the message "Minimum length is..." before I start the search.

      Hope you can help me, and thanks again!

    • csk157 profile image
      Author

      csk157 3 years ago from Denmark

      Ok, try to change

      if(strlen($query) &gt;= $min_length)

      to

      if(isset($_GET['query']) && strlen($query) &gt;= $min_length)

    • profile image

      Lindsay 3 years ago

      Hi csk157,

      Great tutorial here, as you stated above "use PDO statements". Why don't you create a new article that replaces all those mysql_* statements in the above article with PDO statements?

      I'm sure there are many people, including me, who are frustrated in finding tutorial on how to integrate PDO to create search page.

      I've been searching around for days and not a single tutorial explaining how to create a search page with PHP PDO.

      oh, one more thing, thanks for the great article ;)

      waiting for the PDO edition.

    • csk157 profile image
      Author

      csk157 3 years ago from Denmark

      Selim, it would be easier to help you if you attached your code (use http://pastebin.com/ or simillar, as in comment it will be messy)

      Hi, Lindsay. Thanks, but I am not planning to write anything anytime soon though :). I have moved from PHP to other languages (and I don't have much interest in it).

      P.S. if you are doing a serious website (and not just for learning purposes), you may want to use some framework, such as Laravel :)

    • profile image

      dsbpac 3 years ago

      Can you give us an example of this amazing code with paginate?? Please!! Thank you

    • profile image

      sally 3 years ago

      wow perfect code.

      it's work.

      but can i know how to display the searched result in the same page with the index.php?

      I want to create a page which is the search form(search button) is at the top and the searched result will display below it.

      Hope you can help me :)

      Thank you.

    • profile image

      dev 3 years ago

      thanks very helpful codding

    • profile image

      skip 3 years ago

      How do you get the results that you searched for in the database displayed in a table

    • profile image

      mladen88 3 years ago

      Hi

      thanx for tutorial

      Question: How to search from 2 database tables ? (same database)

    • profile image

      Nikolay 3 years ago

      Hello. Script works fine. Could you please tell me which code should I add to "search.php" to realise sorting by 1 column of database using dropdown menu (like sorting by cities here: http://www.phpjabbers.com/free-scripts/mysql-searc... ). Thank you!

    • profile image

      shyam bahadur sunari magar 3 years ago

      really useful.. thanks a lot once & infinity.........

    • profile image

      karun 3 years ago

      good

    • profile image

      Cyrus Besabella 3 years ago

      thanks for this wonderful articles! simple and easy to understand tut!

    • profile image

      Karl Jennings 3 years ago

      Just what I was looking for.

    • profile image

      Sarfaraz 3 years ago

      Very nice tutorial because everything has been explained in detail. Sir one question if I wanted to display only 100 words in with a read more link and when clicking the link display the whole text.

      Thank you

      Sarfaraz

    • profile image

      karthick 3 years ago

      100% working thanks ...

    • profile image

      Akash kumar 3 years ago

      Very Nice explained

    • profile image

      Qwerty 3 years ago

      That was really useful, thank you very much )

    • profile image

      milanj82nis 2 years ago

      Thanks for script.

    • profile image

      Alex Alvarez 2 years ago

      wow, i really love this tutorial! but tell us how to make it for categories?

    • profile image

      Athirah 2 years ago

      Hi. great tutorial you have here. but i wonder. If i would like to make them both in a single page, there'd be an error that says "Undefined index: query" could you help me? thanks

    • profile image

      Zac 2 years ago

      Thank you! Had so much trouble before and this tutorial worked like a charm!

    • profile image

      özkan 2 years ago

      good example

    • profile image

      Nabilah 2 years ago

      Thank you for this code. Its work :) .but if i wanna put image or pdf for download also what should I do then?

    • profile image

      Gandalf 2 years ago

      Thnx!

    • profile image

      Kprinja 2 years ago

      thnx a ton for coding... working properly..:)

    • profile image

      dw 2 years ago

      thank u sooooooooo much, u helped me a lot and i think ur awesome for taking the time to do this

    • profile image

      Burhan 2 years ago

      you are amazing!

    • profile image

      Gurpreet Singh 2 years ago

      Great explanation. Thank you.

    • profile image

      jayanta deb 2 years ago

      thanks a lots

    • profile image

      STAN 2 years ago

      Thank You.

    • profile image

      Adam 2 years ago

      Very nice and very simple.....i love man

    • profile image

      Ben 2 years ago

      Hey, i just want to say your codes help me with my work. Thanks alot!

    • profile image

      cosmicdisco 2 years ago

      hey super cool code, i have a question. how is possible to emphasize only the search words? thanks

    • profile image

      ricky 2 years ago

      its good

    • PKreturns profile image

      Pradeep PK 2 years ago from Bangalore, India

      Your only hub but very much informative particularly for web developer like me

    • profile image

      pinnaclei 23 months ago

      nice coding , very useful , thank you

    • profile image

      dk45516 22 months ago

      is it possible to code for a search for numerical values, such that entering the number in the search box will return values that are less than the entered value available in the database in a particular column.

    • profile image

      kumar 22 months ago

      nice coding thank you.

    • profile image

      sino 21 months ago

      Bless u i was tired for days trying to this

    • profile image

      Rajan 21 months ago

      nice coding !

    • profile image

      Bwire sedrick 21 months ago

      Thanks sooooooooooo much

    • profile image

      arun gautam 19 months ago

      Great Code thanks and God Bless you

    • profile image

      vk 18 months ago

      error

      Notice: Undefined index: query in _____________.php on line 14

    • profile image

      Vladimaire 18 months ago

      it always show:

      "Parse error: syntax error, unexpected '$query' (T_VARIABLE) in C:\xampp\htdocs\newWebProg\search.php on line 13"

      line 13 is:

      "    $query = $_GET["query"]; "

      what might be the problem?

    • profile image

      Ayesha Ch 15 months ago

      i cannot run my search engine queury

    • profile image

      chimfwembe 15 months ago

      After the sql select statement the number of open curly braces does not match the closing curly braces hencing making display diffcult for me, unless there is something am missing, please help

    • profile image

      True 12 months ago

      thank you so much :) I've been in a lot of tutorials and none of them works like the way I wanted to

    • profile image

      gids 12 months ago

      this is the error i get... You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'info1 '%gistoncelebrities%')' at line 2

    • profile image

      gids 12 months ago

      thanks again.. how can i make this work if what i'm searching for is a file say (.mp3) that i need to download?? will really like your help on these..

    • profile image

      opanga Richard 10 months ago

      Great article!!!!!!!!

    • profile image

      JimG 10 months ago

      Hi. I have keywords in a column in my database separated by a space. If I try putting spaces around my search term like, "$vidhints LIKE '% $search_each %'" the search misses some records because there's a space at the front of some of my keywords in the table. E.g., my keyword column has: "recurring services software" So, when I do a search for "recurring" it works, but if I do a search for "services" the search only works if I put a space before the word services. I guess because that's how it is in the database? How do I get around this if I only want to match the word? E.g., if I search for "recurring services" zero results display.

    • profile image

      MArk 9 months ago

      When i tried your code, it displayed : error .. undefined' query'.

      The query is already defined by name.

      So any idea?

    • profile image

      Maxime 8 months ago

      Why not just use PDO and HTML5 to begin with instead of outdated stuff. This is absolutely no help.

    • profile image

      shahdab 8 months ago

      i want search in complete database

    • profile image

      seng 7 months ago

      what does it mean? please help me solve.tq

      Parse error: syntax error, unexpected 'Â Â Â Â Â ' (T_STRING) in C:\xampp\htdocs\RTest1\users\sear.php on line 10

    • profile image

      Manolis 7 months ago

      nice code..

      thank you

    • profile image

      Shawn 6 months ago

      Thankyou!

    • profile image

      Diya 6 months ago

      Error connecting to database: Access denied for user 'root'@'localhost' (using password: YES)

      How to Connect the cpanel database

      Please help Me

    • profile image

      Diya 6 months ago

      Access denied for user 'npdassoc'@'localhost' to database 'tutorial_search'

      Please Help Me

    • profile image

      Mohammed Shamshid 6 months ago

      How can i highlight all the keyword given in the text field to search, in result page?

    • profile image

      Gary WHY 6 months ago

      Thank you so much....

    • profile image

      Nizaka 5 months ago

      At least, wonderfull ! Thanks a lot

    • profile image

      Sujon 5 months ago

      If I wrote

      $query = $_POST['query'];

      Showing Length :

      Minimum length is 3

    • profile image

      AS 5 months ago

      thanks

    • profile image

      abhi 5 months ago

      helped alot thnx :)

    • profile image

      Passenger 4 months ago

      It works perfectly, thank you very much! I just edited with the newer MSQLi commands (it needs only littel adjustments) and it still works fine :)

    • profile image

      peter 4 months ago

      Thank you, it works! One little thing..When I write a " ' " it converts to a " \' " e.g. " 'search' " converts to "\'search\' ". How does it happen and how can I prevent this?

    • profile image

      Frazier 4 months ago

      Hi.

      I'm 'NEW' at coding.

      When I input the code, i keep getting blank results. What does this mean?

    • profile image

      sreylak 4 months ago

      so nice code , thanks

    • profile image

      Hussein Sarkar 3 months ago

      hey, awesome coding and well explained. Thanks alot!

    • profile image

      Hussein Sarkar 3 months ago

      Hello, please can u guide me on how i can use the code posted above to delete a record in the mysql database using the ID? Thanking in advance.

    • profile image

      Manav Kharat 3 months ago

      Thanks

      Your article helped me a lot...

    • profile image

      Jaffer 3 months ago

      simple bt powerful

    • profile image

      vinit 3 months ago

      Hi I am getting an Error "

      Parse error: syntax error, unexpected end of file in /home/indiantravels/public_html/bus_tkt/search.php on line 57

      "

      I removed else close from the end of code.

    • profile image

      bakhtawar komal 2 months ago

      Notice: Undefined index: text in E:\xamp\htdocs\LETS TRY\SEARCH.php on line 53

      please guide me to solve this error

    • profile image

      Deepak Saini 2 months ago

      Thx Man For Helping me its simple and nice codeing

    • profile image

      Ashfaq 2 months ago

      thanks for nice Post. And my wish is ?

      i wants search display result in Column & rows plzzzzzzzzz help me

    • profile image

      azlan 2 months ago

      very good coding

    • profile image

      Simon 2 months ago

      thanks man a lot 6 :)

    • Bonan Conan profile image

      Bonan Conan 7 weeks ago

      Can someone can explain this :

      Unknown column 'text' in 'where clause'

      I got this in result page and dont know what next! I done everything the same as this guy.... so please!

    • profile image

      mmullally 7 weeks ago

      This was an amazingly helpful tutorial. I have one ask i am hoping you will be able to answer. I am searching a db and displaying the results in a table for the user. I want to add a checkbox and qty field to the table and make it an "order form" like system where they can select the items they want. I am having issues creating the names for the checkboxes. I want to check to only include the items checked. what function can i use to dynamically name the checkboxes ie. name="checkbox1" name="checkbox2"

      i know it will be using the mysql_num_rows somehow to tell it to use an index of somekind.

    • profile image

      Joseph 7 weeks ago

      Nice but how can I select from multiple tables like I tried doing this = mysql_query("SELECT * FROM all_post AND p_post

      WHERE (`tittle` LIKE '%".$query."%') OR (`summary` LIKE '%".$query."%')") or die(mysql_error());

      but its not working.

    • profile image

      how insert search word into mysql 6 weeks ago

      how can i input the search word into mysql? if i search using a "word" for that word to be inserted into a table in mysql, for new search word to create new table.

    • profile image

      aswini ravella 6 weeks ago

      excellent post thak u for helping me

    • profile image

      Rads 5 weeks ago

      Thanks a lot for this coding. it works Perfect.

    • profile image

      chen chen nue 5 weeks ago

      very nice coding

    • profile image

      DököllSocial 5 weeks ago

      Great use of code separation- Thank you for posting and making available to public...

    • profile image

      dev 5 weeks ago

      useful code

    • profile image

      LAMINE 4 weeks ago

      thanks you very much.But i have this errors :Parse error: syntax error, unexpected '$query' (T_VARIABLE) in C:\wamp\www\test\teste des class\search.php on line 24

      can you help me please thanks

    • profile image

      cisn 4 weeks ago

      Thanks for this code !!!

      But only one column shows not all fields, which i really need to.

      for example i search onne column but it just show only the first column.. even if it is not what i search. it just show because beacuse they have same row.

    • profile image

      flamboyantandy 2 days ago

      First of all, thank you very much for such a nice coding. Can you please help me drop empty or NULL row's so that result should display only filled options and not all. I mean if in any record, text field is not filled then in result text option should not be visible. Result should display only id and title option.

      Thank You

    • profile image

      shivani 16 hours ago

      thank you soo much for this perfect coed, i really need this.

    • profile image

      Afrosith 10 hours ago

      Awesome... Its really did it..

    Click to Rate This Article