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

Kevin Mangal asked
php html mysql database search
via

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


Answer
via

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.
}
Share This
Posted in: