Limiting results from instant search in PHP?

I made a search bar, for searching users in my database, and I will share my code below. But one problem is that, if I have 5 users in a table, it shows these 5 users, but if I have 1,000 than it shows all 1,000.

Whatever I tried to limit it, it did not work. Sometimes it completely kills the PHP script.

Does anyone know how to solve that and limit to only 5 results displayed per search query from the code below?

HTML INPUT AND AJAX SCRIPT:

<input id="text" type="text" name="text" onkeyup="showHint(this.value)" autocomplete="off" />
<div id="inner" class="inner"></div>
<script>
  function showHint(str) {
    if (str.length==0) {
      document.getElementById("inner").innerHTML="You haven't search. Please have :D";
      return;
    }
    if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    } else {
      // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById("inner").innerHTML=xmlhttp.responseText;
      }
    }
    xmlhttp.open("REQUEST","searchquery.php?text="+str,true);
    xmlhttp.send();
  }
</script>

AND searchquery.php:

<?
  $text = $_REQUEST['text'];
  $text = preg_replace('#[^a-z0-9]#i', '', $text);
  function connect($database) {
    mysql_connect('localhost','root','');
  mysql_select_db($database);
  }
  connect('developing');
  $query = "SELECT * FROM users WHERE first_name LIKE '%$text%' OR last_name LIKE '%$text%'";
  $action = mysql_query($query);
  $result = mysql_num_rows($action);
  if ($result == 0) {
    $output = "User does not exist...";
  }else{
    while ($row = mysql_fetch_array($action)) {
      $output .= '<div class="output"><img src="/'.$row['avatar'].'"><a href="#">'.$row['first_name'].' '.$row['last_name'].'</div><br />';
    }
  }
  echo $output;
?>

Can anybody see some solution on how to make that limit?

Upvotes: 0

Views: 674

Answers (1)

John Conde
John Conde

Reputation: 219804

Use LIMIT in your query:

SELECT * 
FROM users 
WHERE first_name LIKE '%$text%' 
OR last_name LIKE '%$text% 
LIMIT 5'

Upvotes: 4

Related Questions