简体   繁体   中英

PHP Keyword search not working with multiple words

I'm new to PHP and have created a basic HTML Form;

<form id="game" method="get" action="results.php">
    <label> Book Name
        <input type="text" name="gameTitle" />
    </label>
        <input type="submit" name="search" value="Search">
</form>

Here is my PHP;

$gameTitle = $_GET['gameTitle'];
$gameTitle = preg_replace("#[^0-9a-z]#i", "", $gameTitle);

$sql = "SELECT games.gameTitle FROM games WHERE gameTitle LIKE '%$gameTitle%'";

$Games = mysqli_query($conn, $sql) 
or die(mysqli_error($conn));

while ($row = mysqli_fetch_assoc($Games)) {
    $gameTitle = $row['gameTitle'];

echo "<div>$gameTitle</div>\n";
}

mysqli_free_result($Games); 
mysqli_close($conn);

?>

Now for example, if I was to search for a game called 'Far Cry' and I just searched 'Far' it would return the record. However, if I was to search 'Far C' etc (two words) it won't return the record. This happens even if I search the full name 'Far Cry', just seems to not work.

Thanks for any help.

The preg_replace function that you use, replaces all chars which are not 0-9 or az in $gameTitle . So if you search "Far Cry" the preg_replace make "FarCry" and the SQL statment would be WHERE gameTitle LIKE '%FarCry%' .. If there is no title with this word, it will return nothing

Take a look into the variable $gameTitle. You think you are looking for "Far Cry" but the code, the preg_replace part, will set the variable to "FarCry" and i guess that you stored a game called "Far Cry" and not "FarCry" in the database.

  1. To allow spaces in the query string try this:

    $gameTitle = preg_replace("#[^\\s0-9a-z]#i", "", $gameTitle);

  2. Do not forget about mysql_real_escape_string function to avoid SQL injection or even better use PDO, see examples at http://php.net/manual/en/pdo.prepared-statements.php

So the simple query will look like:

"SELECT games.gameTitle FROM games WHERE gameTitle LIKE '%".mysql_real_escape_string($gameTitle)."%'";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM