I have a PHP search suggestion script which uses a MySQL database as its’ back-end and jQuery to push the content to the search box page. The PHP is currently in suggest.php and my search box is on index.php. I want to put the PHP script from suggest.php into the index.php script code but it doesn’t seem to work. Why could this be?
Here is my code for suggest.php:
<?php
$database=new mysqli('localhost','username','password','database');
if(isset($_POST['query'])){
$query=$database->real_escape_string($_POST['query']);
if(strlen($query)>0){
$suggestions=$database->query("SELECT name, value FROM search WHERE name LIKE '%".$query."%' ORDER BY value DESC LIMIT 5");
if($suggestions){
echo '<ul id="suggest">';
while($result=$suggestions->fetch_object()){
echo '<li>'.$result->name.'</li>';
}
echo '</ul>';
}
}
}
?>
Here is my code for index.php:
<script type='text/javascript' src='js/jquery.js'></script>
<script type='text/javascript'>function lookup(a){if (a.length==0){$("#suggestions").hide();} else {$.post("suggest.php",{query:"" + a + ""},function (b){$("#suggestions").html(b).show();})}};</script>
<form id='search' method='post'>
<input type='text' id='query' onkeyup='lookup(this.value);'>
<div id='suggestions'></div>
</form>
It looks like index.php creates the interface your users use, but suggest.php returns the lookup suggestions. You don’t want another copy of the interface coming back when you’re trying to get the lookup suggestions, so you can’t call index.php in place of suggest.php
Also, index.php is not really a php file, at least from what you’ve posted. It might as well be index.html