Wednesday, August 4, 2010

How To Search String In MySQL?

Question: Is there a way to make it NOT case-sensitive. For example, I will search for family, and records appear, but if I'm searching for an agency called Family it won't find unless I make the "f" capitals. is there a way to force it. Also, if I put "spaces" in between the words it won't find any at all. Is there also a way to say, if there is a space in between the words, take either or both words and try to find a match. First try to find a match for the full search, if nothing then search for each word separately without being case sensitive. 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang='en'>
<head>
<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>
<title>Page title</title>
<style type="text/css">
table {
  border-collapse: collapse;
  border: solid 1px black;
}
td {
  padding: 2px 6px;
  border: solid 1px black;
}
</style>
</head>
<body>
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>
<p>Search for: <input type='text' name='search' size='20' maxlength='64'></p>
<p><input type='submit' value='Search'></p>
</form>
<?php
if(isset($_POST['search']))
{
  
$connx = mysql_connect('localhost', '*****', '*****') or die("connx");
  
$db = mysql_select_db('test') or die(mysql_error());
  
# convert to upper case, trim it, and replace spaces with "|":
  
$search = (ini_get('magic_quotes_gpc')) ? stripslashes($_POST['search']) :
            
$_POST['search'];
  
$search = mysql_real_escape_string($search);
  
$search = strtoupper(preg_replace('/\s+/', '|', trim($_POST['search'])));
  
# create a MySQL REGEXP for the search:
  
$regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";
  
$query = "SELECT * FROM `users` WHERE UPPER(`description`) $regexp OR ".
           
"`name` $regexp";
  
$result = mysql_query($query) or die($query . " - " . mysql_error());
  echo
"<table>\n";
  while(
$row = mysql_fetch_assoc($result))
  {
    echo
"<tr>";
    foreach(
$row as $key => $value)
    {
      echo
"<td>$value</td>";
    }
    echo
"</tr>\n";
  }
}
?>
</body>
</html>
Good luck!!!

No comments:

Post a Comment