You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Bootstrap4、PHP、MySQLi和Ajax的实时搜索功能失效求助

解决实时搜索功能的查询无结果问题

我帮你定位到了问题的核心,咱们来快速修复这个实时搜索的bug:

核心错误原因

在search.php的SQL绑定参数环节,你犯了一个小失误:
你写的SQL语句是select * from user where fname like concat('%',?,'%'),这里只有1个占位符?,但你在bind_param里却写了"ss"(表示需要两个字符串参数),还重复传递了两次$search,这会直接导致参数绑定失败,SQL查询无法正确执行,最终返回空结果,触发"No Records Found"提示。

修正后的search.php代码

<?php require('php-includes/connect.php'); ?>
<?php 
$output='';
if(isset($_POST['query'])){
    $search=$_POST['query'];
    // 这里只有1个占位符,所以bind_param只需要对应一个参数
    $stmt =$con->prepare("select * from user where fname like concat('%',?,'%')");
    $stmt->bind_param("s",$search); // 修正:"s"对应单个字符串参数
}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>";
}
?>

额外优化建议

  • 添加防抖功能:避免每次按键都发送AJAX请求,给输入事件加个延迟,减少服务器压力:
    $(document).ready(function(){
        let searchTimeout;
        $("#search_text").keyup(function(){
            clearTimeout(searchTimeout);
            var search = $(this).val();
            searchTimeout = setTimeout(function(){
                $.ajax({
                    url:'search.php',
                    method:'post',
                    data:{query:search},
                    success:function(response){
                        $("#table-data").html(response);
                    }
                });
            }, 300); // 延迟300ms发送请求,避免频繁触发
        });
    });
    
  • 大小写不敏感搜索:如果需要忽略大小写匹配,可以修改SQL语句:
    select * from user where LOWER(fname) like concat('%', LOWER(?), '%')
    

内容的提问来源于stack exchange,提问作者Sundarrajan Subramanian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:55:43