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();})}};</scri开发者_运维知识库pt>
<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
Once a PHP page has been sent out, there's no way to implement any further PHP code in it without a page refresh, if what @bbg says is true. I suggest you use AJAX which can send the request out to get the suggest.php script for execution on index.php. I also suggest you put the code in suggest.php in functions (they make code beautiful, my opinion).
精彩评论