Andy R Andy R - 3 months ago 12
MySQL Question

Blank / Empty Search Form field

I have set up a search form for my database. When I search and results are found a message is echoed below the search form. For instance, 10 records found, 0 records found.

How can I get that message to disappear if the search form field is blank/empty. Currently it displays 15 records found for a blank/empty search field. Which is all the database records.

Thanks for any help.

Form:

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


Query:

//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}%'";}

Answer
<?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'];
}
?>

please try, hope will save your day :D