【问题标题】:How to create autocomplete from sql in php如何在php中从sql创建自动完成
【发布时间】:2018-03-10 10:11:07
【问题描述】:

您好,首先对我的英语感到抱歉,我有这些代码可以在输入中获取数据并在用户键入时显示在列表中 但我的数据在 phpmyadmin 的 sql 数据库中,我在 php 中是新的 我想在 php 中从 sql 创建自动完成功能,但我不知道 google 中如何有大量示例,但没有一个适用于 utf-8 字符集 在我的数据库中有 utf-8 字,所以我做不到

这对我有用,但没有 sql

(function( $ ) {
var proto = $.ui.autocomplete.prototype,
initSource = proto._initSource;

function filter( array, term ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
return $.grep( array, function(value) {
    return matcher.test( $( "<div>" ).html( value.label || value.value ||         
value ).text() );
});
}

$.extend( proto, {
_initSource: function() {
    if ( this.options.html && $.isArray(this.options.source) ) {
        this.source = function( request, response ) {
            response( filter( this.options.source, request.term ) );
        };
    } else {
        initSource.call( this );
    }
},

_renderItem: function( ul, item) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ](         
item.label ) )
        .appendTo( ul );
}
});
})( jQuery );

$(function() {
    var availableTags = [
        { label: 'سیب', value:'سیب' }, //<===utf-8
        { label: '2سیب', value:'سیب2' },//<===utf-8
        { label: 'Apple3', value:'Apple3' }             
    ];
    $( "#tags" ).autocomplete({
        source: availableTags,
        html: 'html'
    });
});

我在这里得到了代码表格: http://jsfiddle.net/eay3d/1/

【问题讨论】:

  • 了解数据库中的字段名称会很有帮助。你可以做一个循环(在 php 中)来生成 availableTags 数组。

标签: php html mysql database autocomplete


【解决方案1】:

您可以使用 PHP 填写 JQuery 数组。在不了解有关表格的更多信息的情况下,我无法为您提供完整/有效的代码,但它看起来像这样:

var availableTags = [
<?php
$queryString = "SELECT * FROM `table`"; // I don't know what your table is called
$query = mysqli_query($conn, $queryString) or die('Unable to execute query. ' . mysqli_error($conn));
while ($row = mysqli_fetch_array($query)){
echo "{ label: '" . $row['dataLable'] . "', value:'" . $row['dataValue'] . "' },"; // I don't know what your fields are called
}
?>           
];

此示例还需要您正确设置数据库连接。你可以在 W3Schools 上阅读:Open a Connection to MySQL

【讨论】:

  • 我假设(顺便说一句)数据库实际上是 MySQL 而不是 SQL。我的基础是 OP 提到了 PHPMyAdmin。
猜你喜欢
  • 2023-03-18
  • 2016-06-13
  • 2013-02-27
  • 1970-01-01
  • 2010-12-22
  • 2017-10-30
  • 1970-01-01
  • 2014-09-30
  • 2014-04-19
相关资源
最近更新 更多