PHP SQL Search

PHP SQL Search is used to return the records details from the table based on the search condition.

PHP SQL Search

PHP SQL Search

     

PHP SQL Search is used to return the records details from the table based on the search condition. The PHP SQL Search allows the user to put his search text  and choose a option from select box. The click on search button helps the user to show the records details based on search text put by the user.

Understand with Example 

This example illustrates how to create a search application in the PHP. To access the records from table 'user' in the database we create a table user. The select statement fetches the records from table 'user'.

Table: user

In this example we create a text box where user put his/her search term and choose a option from select box. When user submit his/her query then we select all list from database table where the query stream involve.

$find = strtoupper($find): The PHP strtoupper ( ) Function convert the search text into upper case.

$find = strip_tags($find) : The string functions is used to manipulate strings.

$find = trim ($find) : The PHP trim() function returns a string without leading and trailing spaces.

Source Code of searchForm.php 

<h2>Search Form</h2>

<form name="search" method="post" action="<?=$PHP_SELF?>">
  Seach for: <input type="text" name="find" /> in
  <Select NAME="field">
  <Option VALUE="fname">First Name</option>
  <Option VALUE="lname">Last Name</option>
  <Option VALUE="designation">Designation</option>
  </Select>

  <input type="hidden" name="searching" value="yes" />
  <input type="submit" name="search" value="Search" />
</form>

<?php
  if ($searching =="yes"){
  echo "<h3>Search Results</h3><p>";
  if ($find == ""){
  echo "<p>Please Enter a search term";
  exit;
  }
  
  mysql_connect("localhost", "root", "root") or die(mysql_error());
  mysql_select_db("test") or die(mysql_error());
  $find = strtoupper($find);
  $find = strip_tags($find);
  $find = trim ($find);

  $query = mysql_query("SELECT * FROM user WHERE upper($field) LIKE'%$find%'");
  while($result = mysql_fetch_array($query)){
  echo $result['fname'];
  echo " ";
  echo $result['lname'];
  echo "<br>";
  echo $result['designation'];
  echo "<br>";
  echo "<br>";
  }

  $matches=mysql_num_rows($query);
  if ($matches == 0){
  echo "Sorry, we can not find an entry to match your query<br><br>";
  }

  echo "<b>Searched For:</b> " .$find;
  }
?>

Download Source Code

Output: