我正在尝试使用 AJAX、PHP 和 MYSQL 进行实时搜索。 User-Profile.php 包含从数据库检索的所有用户数据,并且有一个搜索框可用于输入详细信息以查找名字以“xxx”开头的用户
使用 AJAX 脚本,我从输入框中获取值并将其发布到 search.php,在其中查询数据库并检索搜索结果。
使用 Echo Alert,我发现 search.php 从 AJAX 脚本获取值,但它没有查询数据库来显示实际结果。
即使我在表和数据库中搜索确切的数据,它也会将输出显示为 else 条件语句“NO RECORDS FOUND”。
请找到我的以下脚本并请帮助我解决它。
<强>1。用户配置文件.php
<head>
<script src="vendor/jquery/3.3.1/jquery.min.js">
</script>
<script src="vendor/ajax/libs/popper.js/1.14.6/umd/popper.min.js">
</script>
<script src="vendor/bootstrap/4.2.1/js/bootstrap.min.js">
</script>
</head>
<div class="container-fluid">
<div class="row justify-content-center"><div class="form-inline">
<label for="search" class="font-weight-bold lead">Search User</label>
<input type="text" name="search" id="search_text">
</div></div>
<div class="row">
<div class="col-lg-12">
<div class="table-responsive">
<?php
$stmt=$con->prepare("select * from user");
$stmt->execute();
$result=$stmt->get_result();
?>
<table class="table" id="table-data">
<thead>
<tr>
<th>First Name</th>
<th>Mobile Number</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php while($row=$result->fetch_assoc()){ ?>
<tr>
<td><?= $row['fname']; ?></td>
<td><?= $row['mobile']; ?></td>
<td><?= $row['miruid']; ?></td>
</tr>
<?php } ?>
</tbody>
</table></div></div></div></div>
<script type="text/javascript">
$(document).ready(function(){
$("#search_text").keyup(function(){
var search = $(this).val();
$.ajax({
url:'search.php',
method:'post',
data:{query:search},
success:function(response){
$("#table-data").html(response);
}
});
});
});
</script>
<强>2。搜索.php
<?php
require('php-includes/connect.php');
?>
<?php
$output='';
if(isset($_POST['query'])){
$search=$_POST['query'];
$stmt =$con->prepare("select * from user where fname like
concat('%',?,'%')");
$stmt->bind_param("ss",$search,$search);
}else{
$stmt = $con->prepare("select * from user");
}
$stmt->execute();
$result=$stmt->get_result();
if($result->num_rows>0){
$output="<thead>
<tr>
<th>First Name</th>
<th>Mobile Number</th>
<th>Email</th>
</tr>
</thead>
<tbody>";
while($row=$result->fetch_assoc()){
$output .="
<tr>
<td>".$row['fname']."</td>
<td>".$row['mobile']."</td>
<td>".$row['miruid']."</td>
</tr>";
}
$output .="</tbody>";
echo $output;
}else{
echo"<h3>No Records Found!</h3>";
}
?>
最佳答案
我已经查看了评论并通过替换以下两行代码解决了问题,
<强>1。错误
$stmt =$con->prepare("select * from user where fname like concat('%',?,'%')");
$stmt->bind_param("ss",$search,$search);
<强>2。解决方案
$stmt =$con->prepare("select * from user where fname like '%".$search."%'");
//Removed this line code $stmt->bind_param("ss",$search,$search);//
关于php - 实时搜索无法使用 Bootstrap 4、PHP、MySQLi 和 Ajax 运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56955723/