php - 基于 SQL 数据库的自动完成文本框结果

标签 php jquery html mysql autocompletebox

我正在尝试在文本框中创建一个自动完成功能,但结果应该来 self 的 SQL 数据库。

这是我要配置的代码:
index.php:

<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>jQuery UI Autocomplete - Default functionality</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
        <link rel="stylesheet" href="/resources/demos/style.css">
        <script>
            $(function() {
                var availableTags = [
                    "autocomplete.php"; ];
                $( "#tags" ).autocomplete({
                    source: availableTags
                });
            });
        </script>
    </head>
    <body>
        <div class="ui-widget">
            <label for="tags">Tags: </label>
            <input id="tags">
        </div>
    </body>
</html>

编辑:我更改了变量 availableTags 的内容并将其设为 var availableTags = <?php include('autocomplete.php') ?>;

变量 availableTags 是单词的来源,所以我尝试更改它,而不是在从我的数据库中获取单词的地方放置一个文件名。

这是我的 autocomplete.php 文件:

 <?php

 include('conn.php');
 $sql="SELECT * FROM oldemp";
 $result = mysqli_query($mysqli,$sql) or die(mysqli_error());

 while($row=mysqli_fetch_array($result))
 {
 echo "'".$row['name']."', ";
 }
 ?>

编辑:还更改了while循环的内容,将其变成了

$name=mysqli_real_escape_string($con,$row['name']);
$json[]=$name;

如何将从 autocomplete.php 中获取的单词插入到 availableTags 变量中?

编辑/更新:每当我在文本框中键入内容时都会显示一个列表,但其中没有文本。我知道它正在获取,但该词本身并未显示在列表中。

最佳答案

jQuery UI 自动完成可以接受 source option 的 3 种不同类型的值。 :

  1. 一个数组,包含用于自动完成的内容列表
  2. 一个字符串,其中包含用于过滤列表并将结果发送给我们的脚本的 URL。该插件会将输入的文本作为 term 参数发送到附加到我们提供的 URL 的查询字符串中。
  3. 一个函数,用于检索数据,然后使用该数据调用回调。

您的原始代码使用第一个数组。

var availableTags = [
  "autocomplete.php";
];

告诉自动完成的是字符串 "autocomplete.php" 是自动完成列表中唯一的东西。

我想你想做的是用这样的东西嵌入它:

$(function() {

  var availableTags = [
    <?php include("autocomplete.php"); /* include the output of autocomplete as array data */ ?>;
  ];

  $( "#tags" ).autocomplete({
    source: availableTags
  });

});

假设从数据库返回的列表总是很短,那么这可能没问题。这样做有点脆弱,因为您只是将 PHP 的原始输出插入您的 JS。如果返回的数据包含 ",您可能必须使用 addSlashes 来正确转义它。但是,您应该更改查询以返回单个字段而不是 *,您可能只需要一个字段作为自动完成中的标签,而不是整行。

更好的方法是使用第二种方法:

$(function() {

  var availableTags = "autocomplete.php";

  $( "#tags" ).autocomplete({
    source: availableTags
  });

});

这将要求您更改获取列表的后端脚本,以便它进行过滤。此示例使用 prepared statement确保用户在 $term 中提供的数据不会打开您 SQL injection :

<?php

include('conn.php');

// when it calls autocomplete.php, jQuery will add a term parameter
// for us to use in filtering the data we return. The % is appended
// because we will be using the LIKE operator.
$term = $_GET['term'] . '%';
$output = array();

// the ? will be replaced with the value that was passed via the
// term parameter in the query string
$sql="SELECT name FROM oldemp WHERE name LIKE ?";

$stmt = mysqli_stmt_init($mysqli);

if (mysqli_stmt_prepare($stmt, $sql)) {

  // bind the value of $term to ? in the query as a string
  mysqli_stmt_bind_param($stmt, 's', $term);

  mysqli_stmt_execute($stmt);

  // binds $somefield to the single field returned by the query
  mysqli_stmt_bind_result($stmt, $somefield);

  // loop through the results and build an array.
  while (mysqli_stmt_fetch($stmt)) {
      // because it is bound to the result
      // $somefield will change on every loop
      // and have the content of that field from
      // the current row.
      $output[] = $somefield;
  }

  mysqli_stmt_close($stmt);
}

mysqli_close($mysqli);

// output our results as JSON as jQuery expects
echo json_encode($output);

?>

自从我使用 mysqli 以来已经有一段时间了,因此该代码可能需要一些调整,因为它尚未经过测试。

最好养成使用准备好的语句的习惯,因为如果使用得当,它们可以防止 SQL 注入(inject)。您可以改用普通的非准备语句,使用 mysqli_real_escape_string 转义每个用户提供的项目在将其插入 SQL 语句之前。 但是,这样做很容易出错。只需要忘记逃避一件事,就会让自己容易受到攻击。大多数major "hacks"最近的历史是由于草率的编码引入了 SQL 注入(inject)漏洞。

如果你真的想坚持使用非准备语句,代码看起来像这样:

<?php
  include('conn.php');

  $term = $_GET['term'];
  $term = mysqli_real_escape_string($mysqli, $term);
  $output = array();

  $sql = "SELECT name FROM oldemp WHERE name LIKE '" . $term . "%';";

  $result = mysqli_query($mysqli,$sql) or die(mysqli_error());

  while($row=mysqli_fetch_array($result))
  {
    $output[] = $row['name'];
  }

  mysqli_close($mysqli);

  // output our results as JSON as jQuery expects
  echo json_encode($output);
?>

关于php - 基于 SQL 数据库的自动完成文本框结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21298169/

相关文章:

php - 在 PHP $_COOKIE global 中转义 JSON

php - 如何在mysql中获取下周星期一到星期日

php - 表格中的输入文本框不允许在 Firefox 中进行任何输入

html - 为登录创建模糊框

php - 问题发布数据

php - 使用 MySQL 或 PHP 防止重复条目的正确方法

php - 为什么 AJAX 不向我的 PHP 页面发送数据?

javascript - 什么是 Touch 等同于 Mouseout 事件?

jQuery 更改函数仅适用于最接近的元素

javascript - 我有一段代码试图让一个盒子移动,但它不起作用。语言为HTML5,代码如下