2016-08-09 145 views
3

我已經爲我的數據庫設置了搜索表單。當我搜索並找到結果時,消息會在搜索表單下方回顯。例如,找到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}%'";} 
+0

有可能是在您的查詢錯誤,請張貼這裏 – Jason

+0

粘貼您的查詢時必須返回$ count = 15 – user1234

+0

當搜索字段爲空(no where子句)時,查詢正在提取所有記錄,所以15. – Jigar

回答

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

+0

不錯1,angvee - 工作,感謝您的幫助,真的很感激。 –

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 ""; 
     } 
     ?> 
+0

'search_box'將始終發佈,他還需要檢查它是否爲空()' – Jigar

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 ""; 
    } 
} 
+0

[同一評論](http://stackoverflow.com/questions/38846292/blank-empty-search-form-field# comment65057505_38846376) – Jigar

+0

@Jigar更改了代碼 –

+1

看起來不錯。下次嘗試在將來使用簡化的[empty()](http://php.net/manual/en/function.empty.php)。 :) – Jigar