Mahmoud Samy
Mahmoud Samy

Reputation: 270

how can i make more intelligent search by php and mysql

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?

Upvotes: 5

Views: 1814

Answers (2)

Mahmoud Samy
Mahmoud Samy

Reputation: 270

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>";

}

Upvotes: 1

mitkosoft
mitkosoft

Reputation: 5316

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.

Upvotes: 3

Related Questions