简体   繁体   中英

How to prevent a database search from running on an empty string?

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

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.
}

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

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

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM