0

I have made a very basic search form which fetches name of users from database. It has two problems whenever I hit enter on empty search box it display the whole database instead of showing a error message or just doing nothing like google search box. secondly, i want the search results to appear in dropdown first then a button for whenever a user wants more search results.

Please help in making these changes. any help will be definitely appreciated.

    <h2>Users:</h2><br>
    <?php
    $username="";
    $output = '';
    if (isset($_POST['search'])){
    $search_query = $_POST['search'];
    $search_q = $_POST['search'];
    $search_query = preg_replace("#[^0-9a-z]#i","", $search_query);
    $search_q = preg_replace("#[^0-9a-z]#i","", $search_q);
    $query = mysql_query("SELECT * FROM users WHERE username LIKE '%$search_query%' OR last_name LIKE '%$search_query%'") or die ("Could not search");
    $count = mysql_num_rows($query);
    if($count == 0 ||) {
        $output = 'No Results Found.';
    }
    else{
    while($row = mysql_fetch_array($query)){
        $fname = $row['first_name'];
        $lname = $row['last_name'];
        $id = $row['id'];
    $output .= "<div><a href='profile.php?u=$row[username]'>$fname $lname</a></div>";
    }
    }
    }

    ?>
    <?php echo("$output");?>

      <form method="post" action="search.php" id="search">
        <input type="text" name="search" placeholder="Search..">
Sanchit Gupta
  • 77
  • 1
  • 3
  • 10
  • [**Please, don't use `mysql_*` functions in new code**](http://stackoverflow.com/q/12859942). `mysql_*` functions are deprecated since PHP 5.5 (and **removed entirely** in PHP 7) and you should stop using them if you can. You should choose another API that allows you to use [prepared statements](http://stackoverflow.com/q/60174/) (which you *really should* when dealing with variables), like `mysqli_*` or PDO - see [choosing an API](http://php.net/manual/en/mysqlinfo.api.choosing.php). – Qirel Jan 26 '17 at 16:41
  • Just don't perform the query if it's empty. On the client-side, you can add a `required` attribute to your input, on the server-side you can do `if (!empty($_POST['search'])) {` instead, which checks if there are any values to search for. – Qirel Jan 26 '17 at 16:42

1 Answers1

0

You should be aware of the fact that mysql_query(), mysql_num_rows(), and mysql_fetch_array() are all deprecated in PHP 5.5.0 and removed in PHP 7.0.0. And $_POST['search'] is not filtering out potential SQL injections and other malicious code.

Anyway, you should check to see if the search string is empty before checking the database:

if (empty($POST['search'])) {
 // do nothing or give error response
}

If you want to limit to 10 results:

"SELECT * FROM users WHERE username LIKE '%$search_query%' OR last_name LIKE '%$search_query%' LIMIT 10"
Harman
  • 346
  • 2
  • 6