所以我刚刚发现了jquery auto-complete,我想把它添加到我的网页中。我想把它连接到我的php代码,这样我就可以搜索我的sql数据库了。不过,每当我尝试运行auto complete时,似乎找不到php数组im passing(im只是想让数组暂时工作)。有人能帮忙吗?
Jquery代码

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <script>
  $(function() {
    $( "#tags" ).autocomplete({
      source: "test.php"
    });
  });
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>


</body>
</html>

PHP代码
<?php
    $data[] = array(
        'c++','Java','JavScript',"c#" );
echo json_encode($data);
?>

最佳答案

这是您的答案的更新版本,应该可以解决不推荐使用的SQL驱动程序和注入问题。您需要用实际的列名替换SECOND_COLUMNNAME。除此之外,我认为这应该管用。

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=DB','username','password');
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
if(empty($_REQUEST['term']))
    exit();
//require_once('connect.php'); connection to db is in this file so connection is not needed
$query =  'SELECT name, SECOND_COLUMNNAME FROM locations
        WHERE name
        LIKE ?
        ORDER BY id ASC
        LIMIT 0,10';
$stmt = $dbh->prepare($query);
$stmt->execute(array(ucfirst($_REQUEST['term']) . '%'));
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $data[] = array(
                'label' => $row['name'],
                'value' => $row['SECOND_COLUMNNAME']
                );
}
echo json_encode($data);
flush();

链接:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.connections.php
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
How can I prevent SQL injection in PHP?
也不确定connect.php里面是否还有其他东西,你可能需要把它带回来。

09-25 17:40
查看更多