Reputation: 81
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.
Upvotes: 1
Views: 531
Reputation: 3390
To allow spaces in the query string try this:
$gameTitle = preg_replace("#[^\s0-9a-z]#i", "", $gameTitle);
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)."%'";
Upvotes: 0
Reputation: 347
The preg_replace function that you use, replaces all chars which are not 0-9 or a-z 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
Upvotes: 2
Reputation: 1249
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.
Upvotes: 0