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

PHP+MySQL筛选搜索栏无匹配结果时不显示“无结果”提示如何解决

PHP搜索栏无结果提示修复方案

问题原因

  • 现有代码仅在查询到匹配商品时,才会进入while循环输出商品内容,没有对查询结果为空的场景做处理,因此无匹配结果时不会渲染任何提示内容
  • 额外问题:代码直接将用户输入的搜索内容拼接入SQL语句,存在SQL注入风险,建议同步优化

修改后的代码

<?php
if(isset($_GET['search'])){
    // 先对用户输入做基础转义,临时缓解注入风险,最优方案是改用预处理语句
    $search_query = mysqli_real_escape_string($con, $_GET['user_query']);
    $run_query_by_pro_id = mysqli_query($con, "select * from products WHERE product_keywords like '%$search_query%'");

    // 新增判断:查询结果为空时输出提示
    if(mysqli_num_rows($run_query_by_pro_id) <= 0){
        echo "<div class='col-12 text-center py-5'>
                <h3>暂无符合条件的商品,建议更换搜索关键词重试</h3>
              </div>";
    }else{
        // 原有商品输出逻辑
        while($row_pro = mysqli_fetch_array($run_query_by_pro_id)){
            $pro_id = $row_pro['product_id'];
            $pro_brand = $row_pro['product_brand'];
            $pro_title = $row_pro['product_title'];
            $pro_price = $row_pro['product_price'];
            $pro_image = $row_pro['product_image'];
            $pro_price_old = $row_pro['product-old-price'];

            echo "
            <div class='col-md-3 col-xs-6'>
            <a href='product.php?p=$pro_id'>
            <div class='row1'>
              <div class='col4'>
              <img  src='product_images/$pro_image' alt=''></a>
                <a href='product.php?p=$pro_id'>$pro_title</a>
                <div class='rating' >
                    <i class='fa fa-star'></i>
                    <i class='fa fa-star'></i>
                    <i class='fa fa-star'></i>
                    <i class='fa fa-star'></i>
                    <i class='fa fa-star-o'></i>
                </div>
                <p>From <del class='product-old-price'>$$pro_price_old</del> to $$pro_price
                </p>
            <center>
              <div class='product-btns'>
                  <button class='add-to-wishlist' ><i class='fa fa-heart-o'></i><span class='tooltipp'>add to wishlist</span></button>
                  <button class='add-to-compare'><i class='fa fa-exchange'></i><span class='tooltipp'>add to compare</span></button>
                  <button class='quick-view' ><i class='fa fa-eye'></i><span class='tooltipp'>quick view</span></button>
              </center>
              <div class='add-to-cart'>
                  <button pid='$pro_id' id='product' href='#' tabindex='0' class='add-to-cart-btn'><i class='fa fa-shopping-cart'></i> add to cart</button>
              </div>
              </div>
              </div>
            </div>
            ";
        }
    }
}
?>

安全优化建议

直接拼接用户输入到SQL语句会导致注入漏洞,生产环境建议使用mysqli预处理语句执行查询,避免数据泄露或被篡改的风险。

内容的提问来源于stack exchange,提问作者Bardh Bibaj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:24:03