0

ive got working live search with ajax and php

JQUERY:

$("#search").keyup(function()   {
   var search_input = $(this).val();
   var dataString = 'keyword='+ search_input;
      if(search_input.length>1){
    $.ajax({
      type: "GET",
      url: "include/search.php?diary_date",
      data: dataString,
      beforeSend:  function() {
             $('#loading').addClass('loading');
          }, success: function(server_response) {                 
               $('#searchresultdata').html(server_response).show();
           $('span#faq_category_title').html(search_input);
    }
});
}return false;
});

PHP:

$q = "SELECT id_user, f_name, l_name, postcode, email,telp FROM user 
WHERE f_name LIKE '%$keyword%' 
OR l_name LIKE '%$keyword%'
OR email LIKE '%$keyword%'
OR postcode LIKE '%$keyword%'";

i want the search result, search from the first letter not from the middle or last for example:
keyword = JO
Result i want =
* JOHN BECKS
* JONATHAN WILKO * KATY JOANS

for a moment the system pick up not only first even middle & last words
* TONY NESJO
* BAJOZ ZACKS

1
  • simple, in your queries imagine % as * so if you emit the first % it would search like JO* but in SQL its JO% Commented Mar 20, 2011 at 21:43

2 Answers 2

4

Just remove the first % from each of your LIKE strings.

$q = "SELECT id_user, f_name, l_name, postcode, email,telp FROM user 
WHERE f_name LIKE '$keyword%' 
OR l_name LIKE '$keyword%'
OR email LIKE '$keyword%'
OR postcode LIKE '$keyword%'";

That said, you should really, really investigate using PDO or similar and sending a bound query, where each parameter gets properly escaped to prevent SQL injection attacks.

If you do that the SQL gets slightly more complicated, though, because you can't bind a parameter inside a string, so the addition of the % has to be done as a SQL concatenation:

$q = "SELECT id_user, f_name, l_name, postcode, email,telp FROM user 
WHERE f_name LIKE CONCAT(?, '%')
OR l_name LIKE CONCAT(?, '%')
OR email LIKE CONCAT(?, '%')
OR postcode LIKE CONCAT(?, '%')";

(then produce a prepared statement handle and execute with the appropriate parameters - you'll find plenty of examples else where on Stackoverflow).

Sign up to request clarification or add additional context in comments.

Comments

1

You can use REGEXP operator like so:

$q = "SELECT id_user, f_name, l_name, postcode, email,telp FROM user 
WHERE f_name REGEXP '^$keyword' 
OR l_name REGEXP '^$keyword'
OR email REGEXP '^$keyword'
OR postcode REGEXP '^$keyword'";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.