【问题标题】:autocomplete with MySQLi and php(via Autocomplete UI)使用 MySQLi 和 php 自动完成(通过自动完成 UI)
【发布时间】:2015-11-03 21:21:52
【问题描述】:

我正在尝试使自动完成 php 与数据库交互,但发现超过 10 个在线资源,无法使其与我的数据库一起使用。 下面是 index.php 代码:

<!doctype html>
<html>
<head>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
    <script>
        $(function() {
            //autocomplete
            $("#model").autocomplete({
                source: "search.php",
                minLength: 1
            });                

        });
    </script>
</head>
<body>
    <form action='' method='post'>
<p><label>Model:</label><input type='text' id="model" name='model' class='model'/></p>

</body>
</html>

这里是search.php:

<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '123456');
define('DB_NAME', 'inventory');

if (isset($_GET['term'])){
    $return_arr = array();

    $conn = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME);
    $stmt =  $conn->stmt_init();
    $term = '%'.$_GET['term'].'%';
    $stmt = $conn->prepare("SELECT name from items WHERE name like ?");
    $stmt->bind_param("s", $term);
    $stmt->execute();
    $stmt->bind_result($models);
    while( $row = $models){
        $return_arr[] =  $row['name'];
    }
    echo json_encode($return_arr);
}  
?>

有些教程使用 fetch_array() 对我的脚本不起作用,为什么?它仅适用于常规循环,例如 while 循环来存储数据库中的数组,然后使用 foreach 来回显每一行。我正在使用$mysqli-&gt;fetch_array()。 哪一部分错了?

【问题讨论】:

    标签: php jquery mysqli autocomplete


    【解决方案1】:

    你应该这样做:

    用这个替换“bind_result”行(只是为了方便):

    $stmt->bind_result($name);
    

    然后用这个替换你的while循环:

    while ($stmt->fetch()) {
        $return_arr[] = $name;
    }
    

    它应该可以工作。

    基本上,对于查询中的每一列,您都在 bind_result 语句中添加一个变量,并在迭代结果时使用这些变量;

    【讨论】:

      【解决方案2】:

      使用下面的代码并通过 url@, http://www.codexworld.com/autocomplete-textbox-using-jquery-php-mysql/

      //get matched data from skills table
      $query = $db->query("SELECT * FROM skills WHERE skill LIKE '%".$searchTerm."%' ORDER BY skill ASC");
      while ($row = $query->fetch_assoc()) {
          $data[] = $row['skill'];
      }
      
      //return json data
      echo json_encode($data);
      

      【讨论】:

        猜你喜欢
        • 2011-05-31
        • 1970-01-01
        • 2012-06-19
        • 2012-10-30
        • 2020-12-14
        • 1970-01-01
        • 2014-05-31
        • 1970-01-01
        • 2012-06-12
        相关资源
        最近更新 更多