在php和mysqli中搜索没有结果

时间:2018-05-28 05:40:38

标签: php search mysqli

我不知道为什么我在这段代码中没有得到任何结果,每次我运行else语句运行。

<?php 
            if(isset($_POST['search'])){
                    $search = mysqli_real_escape_string($connection, $_POST['user_query']);

            $sql = "SELECT * FROM search WHERE search_title LIKE '%user_query%' OR search_desc LIKE '%user_query%' OR search_key LIKE '%user_query%' ";
            $run = mysqli_query($connection, $sql);
            $queryResult = mysqli_num_rows($run);


        if($queryResult > 0){
            while($rel_rows = mysqli_fetch_assoc($queryResult)){
                echo "<div id='post'>
            <a href='#'><img src='$rel_rows[search_img]'></a>
            <a href='#'><h4 class='post_name'>$rel_rows[search_title]</h4></a>
            <p class='post_info'> $rel_rows[search_desc]</p>
        </div>";
            }
        }
        else{

            echo "There are no results for your search";
        }

            }
         ?>

2 个答案:

答案 0 :(得分:0)

您传递了错误的搜索字符串;

更改为:

$sql = "SELECT * FROM search WHERE search_title LIKE '%$search%' OR search_desc LIKE '%$search%' OR search_key LIKE '%$search%' ";

您在mysqli_fetch_assoc(..)

中传递了错误的变量作为参数

更改为:

mysqli_fetch_assoc($run)

答案 1 :(得分:0)

试试这个

  <?php 
                if(isset($_POST['search'])){
                        $search = mysqli_real_escape_string($connection, $_POST['user_query']);
$user_query=$search; 
//Added this line and replace user_query to $user_query in SQL query statement    
                $sql = "SELECT * FROM search WHERE search_title LIKE '%$user_query%' OR search_desc LIKE '%$user_query%' OR search_key LIKE '%$user_query%' ";
                $run = mysqli_query($connection, $sql);
                $queryResult = mysqli_num_rows($run);


            if($queryResult > 0){
                while($rel_rows = mysqli_fetch_assoc($run)){
                    echo "<div id='post'>
                <a href='#'><img src='$rel_rows[search_img]'></a>
                <a href='#'><h4 class='post_name'>$rel_rows[search_title]</h4></a>
                <p class='post_info'> $rel_rows[search_desc]</p>
            </div>";
                }
            }
            else{

                echo "There are no results for your search";
            }

                }
             ?>

希望这会有所帮助!!