% _ in search form displays all results
if the search form is blank, it should display an error that something should be entered by the user. it should only show those results which contain the keywords the user has entered in the search textbox.
however, if the user enters % or _ or +, it displays all results. how do i display an error when the user enters these wildcard characters?
my search php code:
$search_r开发者_JS百科esult = "";
$search_result = $_GET["q"];
$search_result = trim($search_result);
if ($search_result == "") {
echo "<p>Search Error</p><p>Please enter a search...</p>" ;
exit();
}
$result = mysql_query('SELECT cQuotes, vAuthor, cArabic, vReference FROM thquotes WHERE cQuotes LIKE "%' . mysql_real_escape_string($search_result) .'%" ORDER BY idQuotes DESC', $conn)
or die ('Error: '.mysql_error());
// there's either one or zero records. Again, no need for a while loop
function h($s) {
echo htmlspecialchars($s, ENT_QUOTES);
}
?>
<div class="caption">Search Results</div>
<div class="center_div">
<table>
<?php while ($row= mysql_fetch_array($result)) { ?>
<tr>
<td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td>
<td style="font-size:16px;"><?php h($cQuotes); ?></td>
<td style="font-size:12px;"><?php h($row['vAuthor']); ?></td>
<td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td>
</tr>
<?php } ?>
</table>
<?php
?>
</div>
You can use regular expression to wipe out special characters
you can check preg_match, preg_replace or preg_filter (Whatever method suits you) for this.
like: $search_result=preg_match("/^[a-zA-Z0-9]*$/", $search_result);
Check for that special case $_GET[q] = "%" in your code, just like how you're checking for a blank query. Or, strip out all occurrences of % and _ in the query.
$search_result = preg_replace ('/[%_*]/', '' , $_GET["q"] );
Try it. I haven't got the tools to check that regex specifically. But this is the direction of which would probably work for you.
Then your result will be safer and cleaner, and if a user typed "%" you would have an empty search.
Heres a solution without regex's that replaces all occurences of your special characters.
$search_result = "";
$special_cases = array( '%', '_', '+' );
$search_result = str_replace( $special_cases, '', $_GET["q"] );
精彩评论