Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i make more intelligent search by php and mysql

Tags:

I have a table for places on database it contains two rows for title and description

I made a search by PHP and MYSQL like that

$select_place = $mysqli->query("SELECT * FROM places where title LIKE '%$searchname%' or description LIKE '%$searchname%'");
$num_place = $select_place->num_rows;

while ($rows_place = $select_place->fetch_array(MYSQL_ASSOC)){

$id_place            = $rows_place ['id'];
$title_place         = $rows_place ['title'];
$description_place   = $rows_place ['description'];

echo "<p>{$title_place}</p><br>";

}

It works well, But, for example, if you search for the word tower if written in wrong way like twer or towr it doesn't work How can i make it more intelligent?

like image 408
Mahmoud Samy Avatar asked Mar 12 '16 12:03

Mahmoud Samy


2 Answers

One good option is to include MySQL SOUNDEX() function:

SELECT
    *
FROM
    places
WHERE
    title LIKE '%$searchname%'
    OR description LIKE '%$searchname%'
    OR SOUNDEX(title) = SOUNDEX('$searchname')
    OR SOUNDEX(description) = SOUNDEX('$searchname')

This will match both towr and twer from your example.

More can be found here:

http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_soundex

Note that:

This function, as currently implemented, is intended to work well with strings that are in the English language only. Strings in other languages may not produce reliable results.

like image 55
mitkosoft Avatar answered Oct 12 '22 02:10

mitkosoft


i found very useful way to do it

here it is

$searchname = stringsafe($_GET['search']);
$searchname2 = explode(" ", $searchname);
$query = "SELECT * FROM places WHERE ";

foreach ($searchname2 as $each) {
    $i++;

    if($i == 1){
        $query .= " title LIKE '%$each%'
    OR description LIKE '%$each%'
    OR SOUNDEX(title) = SOUNDEX('$each')
    OR SOUNDEX(description) = SOUNDEX('$each')";
    }else{
        $query .= " OR title LIKE '%$each%'
    OR description LIKE '%$each%'
    OR SOUNDEX(title) = SOUNDEX('$each')
    OR SOUNDEX(description) = SOUNDEX('$each')";
    }
}

$select_place = $mysqli->query("$query limit 20");
$num_place = $select_place->num_rows;

if($num_place == 0){
    echo "<div class='message-no'>No results</div>";
}
else{

while ($rows_place = $select_place->fetch_array(MYSQL_ASSOC)){

$id_place            = $rows_place ['id'];
$title_place         = $rows_place ['title'];
$description_place   = $rows_place ['description'];

echo $title_place."<br>";

}
like image 25
Mahmoud Samy Avatar answered Oct 12 '22 01:10

Mahmoud Samy