Harish Pareek
Harish Pareek

Reputation: 120

How to search mysql from php

I have a query from user to search in mysql database

<input type="text" name="query_textbox"><input type="submit" name="search_button">
<?php 
   if (isset($_GET['search_button'])) 
   {
    $query = $_GET['query_textbox'];
    $command = "SELECT * FROM `table` WHERE `ProteinName` LIKE '%$query%';";
    $result = mysql_query($command);
    echo $result;
   }
?>

When I put 'human' in textbox then it works. But when I search for 'human protein' it shows 0 results. Now the question is "if I search for a query including whitespaces like 'human protein', it should show me result for 'human protein' as well as for 'human' and for 'protein'. How to do that?

Upvotes: 0

Views: 149

Answers (2)

Supericy
Supericy

Reputation: 5896

You could do something like this:

$query = $_GET['query_textbox'];

// explode the query by space (ie "human protein" => "human" + "protein")
$keywords = preg_split("#\s+#", $query, -1, PREG_SPLIT_NO_EMPTY);

// combine the keywords into a string (ie "human" + "protein" => "'%human%' OR '%protein%'")
$condition = "'%" . implode("%' OR '%", $keywords) . "%'";

$command = "SELECT * FROM `table` WHERE `ProteinName` LIKE $condition;";

Upvotes: 2

Bhavik Shah
Bhavik Shah

Reputation: 2291

$query = $_GET['query_textbox'];

// explode the query by space (ie "human protein" => "human" + "protein")
$keywords = explode(" ", $query);

foreach($keywords as $key => $value){
    $condition[] = `ProteinName` LIKE "'%".$value."%'"
}

$cond_str = implode(' OR ', $condition);
$command = "SELECT * FROM `table` WHERE $cond_str;";

Upvotes: -1

Related Questions