如果搜索表单为空白,则应显示用户应输入内容的错误。它应该只显示包含用户在搜索文本框中输入的关键字的结果。
但是,如果用户输入%或_或+,则会显示所有结果。如何在用户输入这些通配符时显示错误?
我的搜索php代码:
$search_result = "";
$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>
答案 0 :(得分:1)
在代码中检查特殊情况$ _GET [q] =“%”,就像检查空白查询一样。或者,在查询中删除所有出现的%和_。
答案 1 :(得分:1)
您可以使用正则表达式清除特殊字符
您可以查看preg_match,preg_replace或preg_filter(无论哪种方法适合您)。
喜欢:$ search_result = preg_match(“/ ^ [a-zA-Z0-9] * $ /”,$ search_result);
答案 2 :(得分:1)
$search_result = preg_replace ('/[%_*]/', '' , $_GET["q"] );
试试吧。我没有专门检查正则表达式的工具。但这可能对你有用。
然后您的结果将更安全,更清晰,如果用户输入“%”,您将进行空搜索。
答案 3 :(得分:0)
这是一个没有正则表达式的解决方案,可以取代所有出现的特殊字符。
$search_result = "";
$special_cases = array( '%', '_', '+' );
$search_result = str_replace( $special_cases, '', $_GET["q"] );