Reputation:
I have made a "live search bar" with php and javascript. if you enter a word in the search bar it searches the database (mysql).
index.php:
<input type="text" onkeyup="getMovie(this.value)"/>
<div id="movie"></div>
javascript.js:
function getMovie(value) {
$.post("getmovie.php",{partialMovie:value},function(data) {
$("#movie").html(data);
});
}
getmovie.php:
include_once "connection.php";
if($_POST['partialMovie']){
$partialMovie = $_POST['partialMovie'];
$sql = "SELECT title FROM movie WHERE title LIKE '%$partialMovie%'";
$stm = $db->prepare($sql);
$result = $stm->execute(array());
while($row = $stm->fetch(PDO::FETCH_ASSOC)) {
echo "<li>".$row['title']."</li>";
}
}
This works, but it is way to slow. I have only 3 "movies" in my database, but it takes like a second or two to show the results.
the titles of the 3 movies are: een twee drie. but if i type "een" fast, after a second you see een, twee, drie. a second later you see: een twee. and another second later you see: een.
So my question is: is there a way to speed the search up or is there a way to stop searching if you type another letter?
Upvotes: 1
Views: 1668
Reputation: 16055
HTML:
<input type="text" id="movie-autocomplete"/>
<div id="movie"></div>
JS:
$(document).ready(function(){
$('#movie-autocomplete').keyup(function(){
setTimeout(function(){
$.post(
"getmovie.php",
{
partialMovie: $(this).val()
},
function(data) {
$("#movie").html(data);
}
);
}, 500);
});
});
This will create a small delay and post an atual value within the field.
PHP:
include_once "connection.php";
if(!empty($_POST['partialMovie'])){
$partialMovie = $_POST['partialMovie'];
$sql = "SELECT title FROM movie WHERE title LIKE :movie ORDER BY title LIMIT 0, 10";
$stm = $db->prepare($sql);
$result = $stm->execute(array(':movie' => "%{$partialMovie}%"));
while($row = $stm->fetch(PDO::FETCH_ASSOC)) {
echo "<li>".$row['title']."</li>";
}
}
We have to bind the parameter to secure the SQL query and prevent SQL injection. Also You should ensure You have set the PDO to use real prepared statements.
To further speed all the process You should return only JSON data from the PHP and fill in the <ul>
within Your JS code...
Upvotes: 0
Reputation: 30242
Either lower your expectation, because 1 second for a request's round trip is not very improvable, or get the data as json at page load time and search against locally available json data. But if there are many records this might not be an option.
Upvotes: 2
Reputation: 4544
As you use PDO, bind your parameters to avoid sql injection.
Then use full text search in MySQL (select match against), it will be a lot faster than the like %% approach.
Doc : http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
Upvotes: 0