jquery php live search
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 JOANSfor a moment the system pick up not only first even middle & last words
* TONY NESJO * BAJOZ ZACKSJust 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).
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'";
精彩评论