How to create a search functionality with php mysql

Hi,

Many days you can come around a Situation where you want to search the database for a particular string. Like you may want to list all the information from your database where user name contains “am”. Like “Ram” , “Shyam”, “Balaram” etc.

So how do you implement it? Lets see,

Pre-requisites: PHP, MySQL and a Web Server capable of parsing PHP pages, like Apache or IIS. This search script does not spider all your pages by crawling the links, so the content you want to be searchable must be within the database. Knowledge of PHP and MySQL is also necessary because this script is just the bones of a working solution. Numerous edits must take place upon this script before it is a usable solution.
Lets get started.

Just after the <body> tag of your page, place the following HTML. This is for the form which will contain the textfield to enter our search string in.
<form name=”form” action=”search.php” method=”get”>
  <input type=”text” name=”q” />
  <input type=”submit” name=”Submit” value=”Search” />
</form>
Now, enter the following PHP. Follow the PHP comments for what the script is doing, if you get stuck, tell us in the forums!

<?php
  // Get the search variable from URL  $var = @$_GET['q'] ;
  $trimmed = trim($var); //trim whitespace from the stored variable

 // rows to return
  $limit=10;

 // check for an empty string and display a message.
  if ($trimmed == ""){
   echo "<p>Please enter a search...</p>";
   exit;
  }

 // check for a search parameter
 if (!isset($var)){
   echo "<p>We dont seem to have a search parameter!</p>";
   exit;
  }

//connect to your database ** EDIT REQUIRED HERE **
 mysql_connect("localhost","username","password"); //(host, username, password)

//specify database ** EDIT REQUIRED HERE **
 mysql_select_db("database") or die("Unable to select database");
//select which database we're using

// Build SQL Query
 $query = "select * from the_table where 1st_field like \"%$trimmed%\" order by 1st_field";
 // EDIT HERE and specify your table and field names for the SQL query

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

 // If we have no results, offer a google search as an alternative

if ($numrows == 0)
  {
   echo "<h4>Results</h4>";
   echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";

   // google
   echo "<p><a href=\"http://www.google.com/search?q="
   . $trimmed . "\" target=\"_blank\" title=\"Look up
   " . $trimmed . " on Google\">Click here</a> to try the
   search on google</p>";
  }

 // next determine if s has been passed to script, if not use 0
  if (empty($s)) {
 $s=0;
  }

 // get results
  $query .= " limit $s,$limit";
  $result = mysql_query($query) or die("Couldn't execute query");

 // display what the person searched for
 echo "<p>You searched for: "" . $var . ""</p>";

 // begin to show results set
 echo "Results";
 $count = 1 + $s ;

// now you can display the results returned
  while ($row= mysql_fetch_array($result)) {
  $title = $row["1st_field"];

  echo "$count.) $title" ;
  $count++ ;
  }

$currPage = (($s/$limit) + 1);

//break before paging
  echo "<br />";

  // next we need to do the links to other results
  if ($s>=1) { // bypass PREV link if s is 0
  $prevs=($s-$limit);
  print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
  Prev 10</a>  ";
  }

 // calculate number of pages needing links
  $pages=intval($numrows/$limit);

 // $pages now contains int of pages needed unless there is a remainder from division

  if ($numrows%$limit) {
  // has remainder so add one page
  $pages++;
  }

 // check to see if last page
  if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {

  // not last page so give NEXT link
  $news=$s+$limit;

  echo " <a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 >></a>";
  }

  $a = $s + ($limit) ;
  if ($a > $numrows) { $a = $numrows ; }
  $b = $s + 1 ;
  echo "<p>Showing results $b to $a of $numrows</p>";
 
?>

Three major areas are covered in this script, the first is selecting data from the database which matches your entered keyword, the second is displaying the results on the web page and the last is generating the paging, which displays results in chunks of 10 with next/previous links where they are necessary.
Important: This script requires numerous edits before it can be adapted for use. The SQL query in this example is only selecting 1 field from a hypothetical database which doesn't pre-exist . Further down the script, the value of that field is being displayed on the page. The major amendments that need to be performed are 1.) The SQL statement, and 2.) The PHP which displays the results.

Lets Look at another example:

  • trim() -  Strip whitespace (or other characters) from the beginning and end of a string
  • explode() -  Split a string by string
  • array_unique() -   Removes duplicate values from an array
  • preg_replace() -  Perform a regular expression search and replace

Other functions used include common database access functions like mysql_connect, mysql_num_rows, etc. Please see code comments for more detailed explanation of the script. If you have questions or suggestions please use the comment box on the bottom of the page. Open your favorite editor and create search.php file as shown below.

<?php
//This is a working script
//Make sure to go through it and edit database table filelds that you are seraching
//This script assumes you are searching 3 fields

$hostname_logon = "localhost" ;   
$database_logon = "databaseName" ;  
$username_logon =
"databaseUser" ;  
$password_logon =
"databasePass" ;   
//open database connection
 $connections =
mysql_connect($hostname_logon, $username_logon, $password_logon) or die ( "Unabale to connect to the database" );
 
//select database
 
mysql_select_db($database_logon) or die ( "Unable to select database!" );

//specify how many results to display per page

$limit =
10;

// Get the search variable from URL
  $var = @$_GET['q'] ;
//trim whitespace from the stored variable
  $trimmed = trim($var); 
//separate key-phrases into keywords
  $trimmed_array =
explode(" ",$trimmed); // check for an empty string and display a message.
if ($trimmed == "") {
  $resultmsg =  
"<p>Search Error</p><p>Please enter a search...</p>" ;
  }
// check for a search parameter
if (
!isset($var)){
  $resultmsg =  
"<p>Search Error</p><p>We don't seem to have a search parameter! </p>" ;
  }
// Build SQL Query for each keyword entered
foreach ($trimmed_array as $trimm){
     
// EDIT HERE and specify your table and field names for the SQL query

     $query =
"SELECT * FROM tablename WHERE field1 LIKE \"%$trimm%\" OR field2 LIKE  \"%$trimm%\" OR field3 LIKE \"%$trimm%\" ORDER BY field1   DESC"
     // Execute the query to  get number of rows that contain search kewords
     $numresults=
mysql_query ($query);
     $row_num_links_main =
mysql_num_rows ($numresults);     // next determine if 's' has been passed to script, if not use 0.
     // 's' is a variable that gets set as we navigate the search result pages.
     if (empty($s)) {
         $s=
0;
     }
      // now let's get results.
      $query .= " LIMIT $s,$limit" ;
      $numresults =
mysql_query ($query) or die ( "Couldn't execute query" );
      $row=
mysql_fetch_array ($numresults);

      //store record id of every item that contains the keyword in the array we need to do this to avoid display of duplicate search result.
     
do{
 //EDIT HERE and specify your field name that is primary key
          $adid_array[] = $row[ 'fieldid' ];
      }
while( $row= mysql_fetch_array($numresults));
 }
//end foreach

if($row_num_links_main == 0 && $row_set_num == 0){
   $resultmsg = 
"<p>Search results for:" . $trimmed  ."</p><p>Sorry, your search returned zero results</p>" ;
}
  
//delete duplicate record id's from the array. To do this we will use array_unique function
   $tmparr = array_unique($adid_array);
   $i=0;
  
foreach ($tmparr as $v) {
       $newarr[$i] = $v; 
       $i++;
   }
// now you can display the results returned. But first we will display the search form on the top of the page
?>

<form action="search.php" method="get" name="search">
  <div align="center">
     
<input name="q" type="text" value=" <?php echo $q; ?> " size="15">
     
<input name="search" type="submit" value="Search">
  </div>
</form>

<?php
// display what the person searched for.
 if( isset ($resultmsg)){
  
echo $resultmsg;
  
exit();
 }else{
 
echo "Search results for: " . $var;
 }
 
foreach($newarr as $value){
 
// EDIT HERE and specify your table and field names for the SQL query
$query_value =
"SELECT * FROM tablename WHERE fieldid = '$value'";
 $num_value=
mysql_query ($query_value);
 $row_linkcat=
mysql_fetch_array ($num_value);
 $row_num_links=
mysql_num_rows ($num_value);

//now let's make the keywods bold. To do that we will use preg_replace function.
//EDIT parts of the lines below that have fields names like $row_linkcat[ 'field1' ]
//This script assumes you are searching only 3 fields. If you are searching more fileds make sure that add appropriate line. 
 
$titlehigh = preg_replace ( "'($var)'si" , "<b>\\1</b>" , $row_linkcat[ 'field1' ] );
  $linkhigh =
preg_replace ( "'($var)'si" , "<b>\\1</b>" , $row_linkcat[ 'field2' ] );
  $linkdesc =
preg_replace ( "'($var)'si" , "<b>\\1</b>" , $row_linkcat[ 'field3' ] );foreach($trimmed_array as $trimm){
   
if($trimm != 'b' ){
//IF you added more fields to search make sure to add them below as well.
        $titlehigh =
preg_replace( "'($trimm)'si" "<b>\\1</b>" , $titlehigh);
        $linkhigh =
preg_replace( "'($trimm)'si""<b>\\1</b>" , $linkhigh);
        $linkdesc =
preg_replace( "'($trimm)'si" "<b>\\1</b>" , $linkdesc); 
     }
//end highlight?>
 <p>
<?php echo $titlehigh; ?><br>
<?php echo $linkhigh; ?><br>
<?php echo $linkhigh; ?>
</p>
 
<?php
}   //end foreach $trimmed_array 
   if($row_num_links_main > $limit){
  
// next we need to do the links to other search result pages
      if ($s>=1) { // do not display previous link if 's' is '0'
        $prevs=($s-$limit);
         
echo "<div align='left'><a href='$PHP_SELF?s=$prevs&q=$var&catid=$catid'>Previous " .$limit. "</a></div>";
      }
    
// check to see if last page
     $slimit =$s+$limit;
       
if (!($slimit >= $row_num_links_main) && $row_num_links_main!=1) {
     // not last page so display next link
          $n=$s+$limit;
          
echo "<div align='right'><a href='$PHP_SELF?s=$n&q=$var&catid=$catid'>Next " .$limit. "</a></div>";
        }
    }
//end foreach $newarr
?>

2 Responses

  1. I can’t get the first script to work. I’ve been trying to tweak this for ages but all I can get is the first page of results from my database. If I click on the next link it says s=10 and q=whatever query has been entered in the search box but it still gives me the frist page of results. Any help on this would be much appreciated. I haven’t tried the second and supposedly working script.

    • Hi “mrsyardbroom”

      All the trick is in the limit query
      $query = “select * from the_table where 1st_field like \”%$trimmed%\” order by 1st_field”;
      $query .= ” limit $s,$limit”;

      so the final query becomes:
      $query = “select * from the_table where 1st_field like \”%$trimmed%\” order by 1st_field limit $s,$limit”;

      Now, after getting $s and $limit (I think it is set to 10) you first try to execute the query in your database to see if it returns exact results are not.

      If it returns result as expected then see the code for any bugs.
      I hope you will find your way.

Leave a Reply

You must be logged in to post a comment.