所以我的问题是标题中的错误,有我的代码:
jQuery(document).ready(function ($) {
$("#food_search").keyup(function(event){
var search_term =$(this).val();
$.ajax({
type:"POST",
url:"Mypage",
data:{'fsearch':search_term},
success:function(res){
$("#food_search_result").html(res);
console.log(res);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!----------------------------------------------------------------
HTML
----------------------------------------------------------------->
<form method="post">
<p>Търсене на храни: <input type="text" name="fsearch" id="food_search"></p>
</form>
<!----------------------------------------------------------------
PHP
----------------------------------------------------------------->
<?php
$hostname = "localhost";
$username = "name";
$password = "pass";
$databaseName = "dbname";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
if(!empty($_POST["fsearch"])) {
$req = $connect->prepare('SELECT * FROM food_data_bg WHERE title LIKE "%".$fsearch."%"');
$req->execute(array(
'title'=>'%'.$_POST['fsearch'].'%'
));
if($req->rowCount()==0){
echo 'Не бяха намерени резултати!';
}
else{
while($data=$req->fetch()){
?>
<div class="search-result">
<img src="<?php echo $data['fimage']; ?>" class="fimage"/>
<span class="result-title"><?php echo $data['title'] ;?></span><br>
<span class="calories-total"><?php echo $data['calories total'] ;?></span><br>
</div>
<?php
}
}
}
?>
代码用于即时搜索(google like)。$req
变量必须只获取db中的信息,就像jquery通过ajax传递给php的变量search_term一样,php必须检查是否有单词或短语对应于输入字段中写的东西。
感谢!
答案 0 :(得分:0)
$fsearch = $connect->real_escape_string($_POST['fsearch']);
$req = $connect->query("SELECT * FROM food_data_bg WHERE title LIKE %{$fsearch}%");
while($row=$req->fetch_array()){
//output function data: $row['title'], $row['calories total'], etc
}
答案 1 :(得分:0)
我通过添加var $ fsearch并修复我的查询调用来修复它,因为“%”。$ fsearch。“%”'不正确我写了'“。$ fsearch。”%'“正如我所说像这样添加了var $ fsearch:$fsearch = $_POST['fsearch'];
我尝试过使用
if($req) {
//code if it return true (if it is working)
}else{
//code if it return false(not working)
}
现在它回归真实,这意味着查询正在运行,但给了我其他的
错误:mysqli_stmt :: execute()需要0个参数,给定1个
我会问其他问题。 谢谢你的帮助!