0

With my current code when I enter an empty string or a string of one space in the search input field I get every item in the database as a result. How can i make it so that the search doesn't run when an empty string is entered?

    <form action="search.php" method="POST">
        <input type="text" name="search" placeholder="search site">
        <button type="submit" name="submit-search"><img src="../assets/search icon-05.png"></button>
    </form>



    <?php
        if (isset($_POST['submit-search'])){
            $search = mysqli_real_escape_string($conn, $_POST['search']);
            $sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
            $result = mysqli_query($conn, $sql);
            $queryResult = mysqli_num_rows($result);

            if ($queryResult > 0){
                echo $queryResult . " results found";

                while ($row = mysqli_fetch_assoc($result)){
                    echo "<div class='articleItem'>
                        <h2>".$row['title']."</h2>
                        <p>".$row['abstract']."</p>
                        <a href=".$row['link']." target='_blank'>".$row['link']."</a>
                    </div>";
                }
            }
            else {
                echo "There are no results matching your search.";
            }
        }
    ?>
Kevin Mangal
  • 230
  • 1
  • 3
  • 14
  • You could wrap your query and response in a conditional that checks to see if `trim($_POST['search'])` is empty, and then not run the query in that case. – Nick Coons Nov 13 '17 at 06:35

3 Answers3

1

Check if isset, then trim, then confirm it still has at least one character.

if ( isset( $_POST['submit-search'] ) ) {
    $search = trim( (string) $_POST['submit-search'] );

    if ( isset( $search[0] ) ) { // Has at least one character?
        // Run query.
    }
}

If you have PHP 7+, here's a more terse syntax.

$search = trim( (string) ( $_POST['submit-search'] ?? '' ) );

if ( isset( $search[0] ) ) { // Has at least one character?
    // Run query.
}
jaswrks
  • 1,255
  • 10
  • 13
  • That seems a roundabout way of checking. Why not boil it down to something like `if ( !empty( trim( $_POST['search'] )))`? – Nick Coons Nov 13 '17 at 07:27
  • If `$_POST['search']` is undefined, your example will throw an 'undefined index` E_NOTICE level error. So it's good to check if the index exists before trimming it. That said, the example I gave could be more terse using any number of utilities, or perhaps with PHP 7 syntax. – jaswrks Nov 13 '17 at 07:40
  • I'm also typecasting with `(string)`, because you can't assume `$_POST['search']` is a string. It's coming from an untrusted source. – jaswrks Nov 13 '17 at 07:44
  • Use empty() function for check it have some value or not – Satish Nov 13 '17 at 08:12
  • I have nothing against `empty()` either, seems like a good idea. The only thing is that `0` would not make it through, so just something to think about is all. If you want someone to be capable of searching for `0`, check length of the string, not if 'empty'. 0 = empty. – jaswrks Nov 13 '17 at 14:35
  • @jaswrks It depends on the rest of his code. Since he's using `$_POST`, it's likely that this is coming from an HTML form, which means it will be a string, even if it contains a number. And because it's coming from a form, it will be set. He's already using it without checking it in the snippet that he posted, so if it needs to be checked for set, then he's already doing that elsewhere. You're right about `0` being empty, even though `0` can't be sent because it will be `"0"`, but even that is empty. So a better example would be `if( trim( $_POST['search'] ))`, removing `empty()` solves it. – Nick Coons Nov 13 '17 at 20:13
  • Likely, yes. I agree. But with respect, there is every chance in the world that a form could be submitted with even an array containing who knows what; i.e., we can never ever assume the data comes from a local HTML form. A POST can come from anywhere. Unless other code is writing to `$_POST`, which would be unexpected, then it won't matter at all what other code there is because the data that's being dealt with in this snippet references `$_POST`. So there is no room for assumption. – jaswrks Nov 13 '17 at 22:06
  • `if( trim( $_POST['search'] ))` is the same thing as checking if it's `!empty()`. It's explicitly a boolean check, and converting a string to a boolean follows the same rules that `empty()` does. So it's the same thing. See: http://php.net/manual/en/language.types.boolean.php#language.types.boolean.casting – jaswrks Nov 13 '17 at 22:22
0

You can check string length with strlen. A trim can be additionally used to remove white spece search also.

$hasResult = false ; //default mark no result.
if (isset($_POST['submit-search']) && strlen(trim($_POST['submit-search'])) > 0) {
    $search = mysqli_real_escape_string($conn, $_POST['search']);
    $sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
    $result = mysqli_query($conn, $sql);
    $queryResult = mysqli_num_rows($result);

    if ($queryResult > 0) {
        $hasResult = true ;  //mark result found
        echo $queryResult . " results found";

        while ($row = mysqli_fetch_assoc($result)) {
            echo "<div class='articleItem'>
                        <h2>" . $row['title'] . "</h2>
                        <p>" . $row['abstract'] . "</p>
                        <a href=" . $row['link'] . " target='_blank'>" . $row['link'] . "</a>
                    </div>";
        }
    }
}

if( ! $hasResult  ) { //Move to a common section
    echo "There are no results matching your search.";
}
nithinTa
  • 1,632
  • 2
  • 16
  • 32
-1

Use the below function to get the query string

<?php
$arr_with_index['title'] = $_POST['search'];
$search_qry = getLikeSearchQuery($arr_with_index)
// Add this $search_qry in your query string. This help you to searc N number of values

// For Array and Equal values
 function getSearchQuery($arr_with_index) {
  $search_qry = "";
        if(isset($arr_with_index)){
              foreach(@$arr_with_index as $index => $value) {
                    if(is_array($value)) {
                          if( implode("",$value) != '' ) {
                                if($index && $value) { $search_qry .= " and $index IN ('".implode("','",$value)."') "; }
                          }
                    } else {
                          $value = trim($value);
                          if($index && $value) { $search_qry .= " and "; $search_qry .= " $index = \"$value\" "; }
                    }
              }
        }
  return $search_qry;
}
// For String
function getLikeSearchQuery($arr_with_index) {
  $search_qry = "";

  foreach($arr_with_index as $index => $value) {
        $inner_flag = false;
        if($index && $value) {
              $field_arr = explode(",", $index);
              foreach($field_arr as $field_index => $field_value) {
                    if(!$inner_flag) { $search_qry .= " and ( "; } else { $search_qry .= " or "; }
                    $value = trim($value);
                    $search_qry .= " $field_value like "; $search_qry .= "  \"%$value%\" "; 
                    $inner_flag = true;
              }
        }
        if($inner_flag) { $search_qry .= " ) "; }
  }

  return $search_qry;
}

?>
Udhay
  • 1
  • 3