我正在制作直播搜索功能。如果我在搜索字段内单击并按下退格键(我的MAC上的删除按钮),直到搜索框为空,当搜索框清除时,我的数据库中的每个条目都会显示。
以下是搜索表单代码:
<head>
<script type="text/javascript">
function searchq()
{
var searchTxt = $("input[name='search']").val();
$.post("search.php" , {searchVal: searchTxt}, function(output) {$("#output").html(output)});
}
</script>
</head>
<body>
<form action="search.php" method="post">
<input type="text" name="search" placeholder="Search for members..." onkeyup="searchq();" autofocus/>
<input type="submit" value=">>"/>
</form>
<div id="output">
</div>
</body>
这是PHP代码:
//collect
if (isset($_POST['searchVal'])) {
$searchq = $_POST['searchVal'];
//sanitize
$searchq = preg_replace ("#[^0-9a-z]#i","", $searchq);
$query = mysqli_query($conn, "SELECT * FROM Tutorials WHERE title LIKE '%$searchq%' OR artist LIKE '%$searchq%'") or die ("could not search");
$count = mysqli_num_rows($query);//counts number of rows in table
if ($count == 0) {
$output = 'No search results';
} else {
while ($row = mysqli_fetch_array($query)) {
$tit = $row['title'];
$art = $row['artist'];
$prev = $row['preview'];
$wat = $row['watch'];
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> <a href="'.$prev.'" >preview tutorial</a> - <a href="'.$wat.'">watch full tutorial</a></div>';
}
//echo "<p> " .$count. " search results</p>";
}
}
echo($output);
?>
代码是非常新手,我知道。
答案 0 :(得分:0)
我想补充一下:
if ($searchq == "") {
$output = 'No search results';
}else{
query here...
}
这样您就不会向查询发送空搜索。