【问题标题】:Autocomplete from database not working从数据库自动完成不起作用
【发布时间】:2013-09-14 16:05:03
【问题描述】:

我正在使用自动完成,其中建议来自数据库并且工作正常,但是我尝试将其更改为 mysqli 但它不起作用。它没有显示任何建议;没有错误。

  1. 我在 mysqli 端缺少什么?
  2. 如何才能添加更多表(我有 40 个表)?谢谢。

MySQL:

 <?php
 mysql_connect("localhost","root","");
 mysql_select_db("database");

 $term=$_GET["term"];

 $query=mysql_query("SELECT * FROM products1 where title like '%".$term."%' order by id ");
 $json=array();

    while($student=mysql_fetch_array($query)){
         $json[]=array(
                    'value'=> $student["title"],
                    'label'=>$student["title"]
                        );
    }

 echo json_encode($json);

?> 

我对 MySQLi 准备好的语句的尝试:

<?php
$mydb = new mysqli('localhost', 'root', '', 'database');
$q = $_POST['term'];
$stmt = $mydb->prepare(" SELECT * from products1 where title LIKE ? ");
echo $mydb->error;
$stmt->bind_param('s', $q);
$stmt->execute();
?>
<?php
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$json[]=array(
            'value'=> $student["title"],
            'label'=>$student["title"]
                             );


}
echo json_encode($json);

?>

【问题讨论】:

标签: php mysql autocomplete mysqli


【解决方案1】:

首先,Jonathan 建议在术语中添加通配符('%') 是正确的。您的错误是在循环中使用变量 $student 而不是 $row (反之亦然)。

<?php
$mydb = new mysqli('localhost', 'root', '', 'test');
$q = '%'.$_POST['term'].'%';
$stmt = $mydb->prepare(" SELECT * from products1 where title LIKE ? ");
echo $mydb->error;
$stmt->bind_param('s', $q);
$stmt->execute();


$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$json[]=array(
        'value'=> $row["title"],
        'label'=>$row["title"]
                         );
}
echo json_encode($json);

?>

P.S.:确保您的查询首先有效。而且,您在 $row['columnName'] 中使用的列确实存在。

【讨论】:

  • 大声笑。这对我有用。记下我的查询。我没有用和你一样的。 (我会编辑它。看起来你只是复制粘贴。)
  • 问题实际上是在使用$_POST 而不是$_GET
猜你喜欢
  • 2016-10-14
  • 2020-05-10
  • 1970-01-01
  • 2017-02-26
  • 1970-01-01
  • 1970-01-01
  • 2012-07-10
相关资源
最近更新 更多