我正在尝试做一个非常简单的搜索功能,但不知何故我无法让它工作。这是我的 HTML:
<form action="" method="POST">
<div class="row">
<div class="col-sm-6">
<input placeholder="Search by name..." type="text" name="field" class="form-control" required="">
</div>
<div class="col-sm-3 text-right">
<input type="submit" name="search" value="Search" class="btn btn-univ">
</div>
<div class="col-sm-3">
<a href="allaccounts.php" class="btn btn-default text-left">Clear Search</a>
</div>
</div>
</form>
还有我的 PHP 和 MySQL 代码:
if (isset($_POST['search'])) {
$field = $_POST['field'];
$query = mysqli_query($con, "SELECT * FROM pastor WHERE fname OR lname LIKE '%$field%'") or die (mysqli_error($con));
// I just added this var_dump to check my input. Input is fine.
var_dump($field);
if (mysqli_num_rows($query) < 1) {
echo "<br><center>There are no pastors with this name</center><br>";
} else {
while ($row = mysqli_fetch_array($query)) {
echo "
<tr>
<td>$row[fname] $row[lname]</td>
<td>$row[location]</td>
<td>$row[phone]</td>
<td>$row[email]</td>
<td class='text-center'>$row[district]</td>";
// check status
if ($row['activated'] == 1) {
echo "<td><center style='color: green; font-weight: bold;'>Activated</center></td>";
} else if ($row['activated'] == 2) {
echo "<td><center style='color: #000240; font-weight: bold;'>Pending with Confirmed Phone<em></em></center></td>";
} else if ($row['activated'] == 3) {
echo "<td><center style='color: #00037F; font-weight: purple;'>Pending with Unconfirmed Phone</center></td>";
} else if ($row['activated'] == 4) {
echo "<td><center style='color: #0006E5; font-weight: purple;'>Pending (Account Recently Unblocked)</center></td>";
} else if ($row['activated'] == 0 && $row['blocked'] == 1) {
echo "<td><center style='color: red; font-weight: bold;'>Blocked</center></td>";
}
echo "
<td class='text-center'><a href='allaccounts.php?activateid=$row[id]' data-toggle='tooltip' title='Activate Account'><span class='glyphicon glyphicon-ok-sign'></span></a></td>
<td class='text-center'><a href='allaccounts.php?deactivateid=$row[id]' data-toggle='tooltip' title='Deactivate Account'><span class='glyphicon glyphicon-minus-sign'></span></a></td>
<td class='text-center'><a href='allaccounts.php?blockid=$row[id]' data-toggle='tooltip' title='Block Account'><span class='glyphicon glyphicon-remove-sign'></span></a></td>
<td class='text-center'><a href='allaccounts.php?deleteid=$row[id]' data-toggle='tooltip' title='Delete Account'><span class='glyphicon glyphicon-fire'></span></a></td>
</tr>
";
}
}
}
我通过 var_dump
检查了我的输入,我正在搜索的字符串正是我正在输入的。如果您需要,我的 fname
和 lname
字段上的数据类型是可变的。
最佳答案
您不能使用OR
来组合正在搜索的字段,您必须为每个字段设置单独的条件并将它们与OR
组合起来
WHERE fname LIKE '%$search%' OR lname LIKE '%$search%'
您的条件被解析为:
WHERE fname OR (lname LIKE '%$search%')
因为 fname
为真除非它为空,这个条件实际上总是为真。
顺便说一句,您应该学习使用准备好的查询来防止 SQL 注入(inject)。
关于php - 喜欢不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48506486/