Some website's search boxes aren't very good: when you put a space in the search bar and submit, it returns every search item they have. (Example: http://watchfreemovies.unblocked.co/)

Mine does the same. What can I do to make it verify that there is actual text in the search box before submitting?

Search box and button:

<div class="Nava">
<input type="button" name="button" id="hello" value="M" />
</div>
    <form action='/search.php' method='GET'>
        <input id='searchbar' type='text' name='search' placeholder="search for movies &  shows" maxlength="50" />
        <input id='submit' type='submit' name='submit' value='Search' />
    </form>
    <div class="Navbuttons">
        <a href="../shows"><input type="button" name="button" id="button" value="shows" /></a>
        <a href="../movies"><input type="button" name="button" id="button" value="movies" /></a>
    </div>

Results page:

$x = 0;
$construct = '';
$search = $_GET['search'];
$search = preg_replace("#[^0-9a-z ]#i", "", $search);
if (strlen($search) <= 0)
    echo "Search term too short";
else {
    echo "You searched for '<b>$search</b>' ";
    mysql_connect("localhost", "root", "");
    mysql_select_db("search");
    $search_exploded = explode(" ", $search);
    foreach ($search_exploded as $search_each) {
        $x++;
        if ($x == 1)
            $construct .= "keywords LIKE '%$search_each%'";
        else
            $construct .= "AND keywords LIKE '%$search_each%'";
    }
    $construct = "SELECT * FROM searchengine WHERE $construct";
    $run = mysql_query($construct);
    $foundnum = mysql_num_rows($run);
    if ($foundnum == 0)
        echo "<p>Sorry, there are no matching result for '<b>$search</b>'.</p>
    <li> Try different words with similar
     meaning</li>
     <li> make sure you're spelling is correct</li>";
    else {
        echo "$foundnum results found !";

        while ($runrows = mysql_fetch_assoc($run)) {
            $title = $runrows['title'];
            $desc  = $runrows['description'];
            $url   = $runrows['url'];

            echo "
    <hr><a href='$url'><h2><b>$title</b></h2></a><br>
    $desc<br>
    <a href='$url'></a><p>
    "; 
        }
    }

}
有帮助吗?

解决方案

Check server-side:

if (!trim($_GET['search'])) {
    echo 'Enter a query.';
}

Check client-side:

<form action='/search.php' method='GET'>
    <input id='searchbar' type='text' name='search' placeholder="search for movies &  shows" maxlength="50" required />
    <input id='submit' type='submit' name='submit' value='Search' disabled />
</form>
<script>
    document.getElementById('searchbar').onkeypress = function() {
        document.getElementById('submit').disabled = !this.value.trim();
    }
</script>

Fiddle

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top