我无法使我的搜索功能正常工作。我没有看到任何PHP错误,但页面刷新并重新显示数据库列。我希望它只显示搜索查询的结果。
例如,如果我搜索“Mike”,我想在“Tech_Num”,“Tech_F_Name”,“Tech_L_Name”和“Mobile_Num”中显示所有Mikes。
代码:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Include the connection
include "connect.php";
$sql = "SELECT * FROM tech_info ";
if (isset($_POST['searchquery'])) {
$result = mysqli_query($con, "SELECT * FROM tech_info");
$search_term = $_POST['searchquery'];
$sql .= "WHERE Tech_F_Name = '{$search_term}'";
$sql .= " OR Tech_L_Name = '{$search_term}'";
}
?>
<form action="test2.php" method="POST">
Search: <input type="text" name="searchquery" />
<input type="submit" name="searchname" value="Search Me">
</form>
<table width="70%" cellpadding="5" cellspace="5">
<tr>
<td><strong>Tech_Num</strong></td>
<td><strong>First Name</strong></td>
<td><strong>Last Name</strong></td>
<td><strong>Mobile Number</strong></td>
</tr>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['Tech_Num']; ?>
<td><?php echo $row['Tech_F_Name']; ?>
<td><?php echo $row['Tech_L_Name']; ?>
<td><?php echo $row['Mobile_Num']; ?>
<?php } ?>
</table>
答案 0 :(得分:5)
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Include the connection
include "connect.php";
$sql = "SELECT * FROM tech_info ";
if (isset($_POST['searchquery'])) {
$search_term = mysql_real_escape_string($_POST['searchquery']);
$sql .= "WHERE Tech_F_Name = '{$search_term}'";
$sql .= " OR Tech_L_Name = '{$search_term}'";
}
$result = mysqli_query($con, $sql);
?>
你的东西顺序错误,需要在使用它之前构建sql查询。
答案 1 :(得分:1)
您的操作顺序似乎有误。您应该首先创建$ sql变量,然后将其发送到数据库?类似的东西:
if (isset($_POST['searchquery'])) {
$search_term = $_POST['searchquery'];
$sql .= "WHERE Tech_F_Name = '{$search_term}'";
$sql .= " OR Tech_L_Name = '{$search_term}'";
$result = mysqli_query($con, $sql);
}
此外,对于初学者,请替换:
$search_term = $_POST['searchquery'];
与
$search_term = mysql_real_escape_string($_POST['searchquery']);
答案 2 :(得分:0)
我觉得你对这个剧本很困惑:-) 如果你想在一些数据库coloumns中搜索,你试着写这样的东西:
include "connect.php";
$sql = "SELECT * FROM tech_info ";
if (isset($_POST['searchquery'])) {
$search_term = $_POST['searchquery'];
$sql .= "WHERE Tech_F_Name = '{$search_term}'";
$sql .= " OR Tech_L_Name = '{$search_term}'";
}
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {}