空白/空搜索表单字段

时间:2016-08-09 08:58:56

标签: php html mysql

我已为我的数据库设置了搜索表单。当我搜索并找到结果时,会在搜索表单下方回显一条消息。例如,找到10条记录,找到0条记录。

如果搜索表单字段为空/空,如何使该消息消失。目前,它为空白/空搜索字段显示找到的15条记录。这是所有数据库记录。

感谢您的帮助。

表格:

<form action="" method="post">
    <input type="text" name="search_box" value="<?php if (isset($_POST['search_box'])) echo $_POST['search_box']; ?>" placeholder="Search here ..."/>
    <input value="Search" name="search" type="submit" /><br>
</form>

PHP:

<?php
        $count = mysqli_num_rows($result);
        if($count > 0){
            echo $count . " Records Found";
        }if($count == 0){
            echo "0 Records Found";
        }if($count == ""){
            echo "";
        }
        ?>

查询:

//Retrieve the practice posts from the database table
$query = "SELECT * FROM practice";

//check if search... button clicked, if so query fields
if(isset($_POST['search'])){
    $search_term = trim($_POST['search_box']);
    $query .= " WHERE title = '{$search_term}'";
    $query .= " or subject LIKE '%{$search_term}%'";}

3 个答案:

答案 0 :(得分:1)

<?php

//Retrieve the practice posts from the database table
$query = "SELECT * FROM practice";

//check if search... button clicked, if so query fields
if(isset($_POST['search'])){
    $search_term = trim($_POST['search_box']);
    $query .= " WHERE title = '{$search_term}'";
    $query .= " or subject LIKE '%{$search_term}%'";

   //execute your query
    $result = $dbconnect->query($query);

    $count = mysqli_num_rows($result);
    if($count > 0){
       echo $count . " Records Found";
    }
    if($count == 0){
       echo "0 Records Found";
    }
}
else {
   // it is mean your search box value($_POST['search']) is empty, so it will echo null value 
   echo $_POST['search'];
}
?>

请尝试,希望能节省您的一天:D

答案 1 :(得分:0)

请用以下代码替换PHP代码: -

<?php
           if(isset($_REQUEST['search_box'])){
        $count = mysqli_num_rows($result);
        } else {
         $count = '';
        }
        if($count > 0){
            echo $count . " Records Found";
        }if($count == 0){
            echo "0 Records Found";
        }if($count == ""){
            echo "";
        }
        ?>

答案 2 :(得分:0)

只需将代码放入post方法

即可
 if ((isset($_POST['search_box'])) && ($_POST['search_box']!=""))
{

    $count = mysqli_num_rows($result);
    if($count > 0){
        echo $count . " Records Found";
    }if($count == 0){
        echo "0 Records Found";
    }if($count == ""){
        echo "";
    }
}