This question already has an answer here:
I'm creating a very simple Ajax
live search results (like google suggest) using PHP
and MySQL
.
The index page (HTML
and JavaScript
):
<html>
<head></head>
<body>
<hi>Live search!</h1>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script>$(document).ready(function(e) {
$("#search").keyup(function()
{
$("#here").show();
var x = $(this).val();
$.ajax(
{
type:'GET',
url:'fetch.php',
data:'q='+x,
success:function(data)
{
$("#here").html(data);
}
});
});
});
</script>
<style>
input {width:400px;font-size:24px}
#here {width:400px;
height:300px;
border:1px solid grey;
display:none;
}
#here a {
display:block;
width:98%
padding:1%
font-size:20px;
border-bottom:1px solid grey;
}
</style>
<input type="search" name="search" id="search">
<div id="here">
</div>
</body>
</html>
the fetching page: (PHP
);
<pre><code>
<?php
if(!empty($_GET['q']))
{
include 'connect.php';
$q=$_GET['q'];
$query="select * from names where names LIMIT 3 like '%$q%'";
$result=mysqli_query($conn,$query);
while($output=mysqli_fetch_assoc($result))
{
echo '<a>'.$output['names'].'</a>';
}
}
?>
And another connect page, which is not needed here.
You can observe that I was trying to limit the search query results by adding LIMIT 3
in the fetch.php but whenever I'm trying to search, I'm getting the following error:
"Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\ajax\fetch.php on line 8"
Without adding the LIMIT 3
in the $query, the live suggestions are working fine. But the code is showing too many results, which I want to limit. For example if I type "G", it is giving all 320 results with the first alphabet "G". I want to limit the results to only 3. I don't know how I can do it.
</div>
Correct is:
"select * from names where names like '%$q%' LIMIT 3"