我有搜索框和按钮在MySQL表中搜索。而且效果很好。但是,当我在搜索框中嵌入时,它会向我发出错误消息(我设置了错误消息):输入一个单词进行搜索。这是我的HTML搜索框和按钮:
<form method="post" class="form-inline my-2 my-lg-0 navbar navbar-expand-lg navbar-light bg-info">
<input name="search" class="form-control mr-sm-2" placeholder="Search" aria-label="Search">
<button name="submit-search" class="btn my-2 my-sm-0 bg-white" type="submit">Search</button>
</form>我的函数search():
function search()
{
if (empty($_POST['search'])) {
$_SESSION['message'] = "Enter a word to search";
$_SESSION['msg_type'] = "warning";
return;
}
$keyword = '%' . $_POST['search'] . '%';
$database = new Database;
$db = $database->dbConnection();
$stmt = $db->query("SELECT * FROM posts WHERE id LIKE '$keyword' OR userId LIKE '$keyword' OR title LIKE '$keyword' OR completed LIKE '$keyword'");
$count = $stmt->rowCount(); //num di record trovati
if ($count > 0) {
$_SESSION['message'] = "Found items: " . $count;
$_SESSION['msg_type'] = "success";
} else {
$_SESSION['message'] = "No article match with: " . $_POST['search'];//it results this message. I don't get it why don't recognize that character(0).
$_SESSION['msg_type'] = "warning";
//header("location: allart.php");
} ?>
<div class="container" style=" margin-top:5%;">
<table class=" table table-hover" id="search-table" style="font-size: 18px;">
<hr>
<div style="text-align:center;"> <label style="text-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1), 10px 10px 10px rgba(0, 0, 0, 0.2); font-size:30px;border-radius: 45px; "> Results from search : </label></div> <br>
<tr>
<th>User ID:</th>
<th> ID: </th>
<th> Title: </th>
<th> Compiled: </th>
</tr>
<?php while ($row = $stmt->fetch()) : ?>
<tr>
<td> <?php echo $row['userId'] ?> </td>
<td> <?php echo $row['id'] ?> </td>
<td> <?php echo $row['title'] ?> </td>
<td> <?php echo $row['completed'] ? 'Compiled' : 'Not Compiled' ?> </td>
</tr>
<?php endwhile ?>
</table>
</div>
<?php }效果很好。但是,当我在搜索框中插入0时,他似乎不认识我设置的显示错误信息的字符。我检查了我的MySQL表,找到了id =10的行。所以当我在搜索栏中插入0时,它应该会得到id = 10的行。我不明白为什么它找不到任何包含的单词。
有什么办法解决这个问题吗?谢谢!
发布于 2020-02-20 11:31:19
您的问题是,从PHP的角度来看,0基本上是“空”的。而不是检查这个..。
if (empty($_POST['search'])) {。。试着检查它是否已设置:
if (!isset($_POST['search'])) {请参阅此方法的演示:https://3v4l.org/osfXH
编辑:我错过了感叹号,谢谢!)
https://stackoverflow.com/questions/60318874
复制相似问题