How to fix my search issue

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • simon2x1
    New Member
    • Dec 2008
    • 123

    How to fix my search issue

    The code below is my search code, if i search for the username john it will display it but if i search JOHN, joh, jo, or j it will echo no match was found how can i fix that.

    Code:
    If(empty($_POST['search_q'])){
    
    			echo "Enter search word";
    
    			}else{
    
    			$term = $_POST["search_q"];
    			$result = @mysql_query("SELECT * FROM user WHERE name like '%$term%' ",$dbconnect);
    			$myrow = @mysql_fetch_array($result);
    				$uname = $myrow[username];
    			
    			echo "$uname";
    
    		}else{
    			echo "No match was found";
    	}
    
    }
  • HaLo2FrEeEk
    Contributor
    • Feb 2007
    • 404

    #2
    Well, first off, you don't need to put quots around variables in strings. It'll work, but code is easier to read if you don't, so:

    echo "$variable" ;

    Should actually be just:

    echo $variable;

    If you want to echo a string with the variable somewhere in the middle, then do this:

    echo "I'm a string with a " . $variable . " in the middle.";

    Next, your actual problem. Yo should use regular expressions. I have a search on my sit that, for a while, used the LIKE %% method, but I found some issues with it. For example, if I searched for the word "read", then I'd get results with the word "thread", since it contains the word read. What I did to solve it:

    Code:
    $findarr = explode(" ", $find);
    foreach($findarr as $word) {
      $searchstr .= "[[:<:]]".$word."[[:>:]] ";
      }
    $searchstr = trim($searchstr);
    
    $query = "SELECT * FROM `news` WHERE `news_title` REGEXP '".mysql_real_escape_string($searchstr)."' OR `news_text` REGEXP '".mysql_real_escape_string($searchstr)."' ORDER BY `news_id` DESC";
    $results = mysql_query($query);
    Now if I search for "read", I'll get any result that contains the word "read", but if I search for "read this" then I'll only get results that contain the phrase "read this".

    Comment

    Working...