自动完成表单由数据库填充? [英] Autocomplete form populated by a database?

查看:106
本文介绍了自动完成表单由数据库填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前工作中,我需要有一个自动完成表单调用从数据库文件其信息的项目。我看到的jQuery的自动完成的表格很多教程,但我不知道该怎么称呼一个数据库文件填充列表。

I am currently working on a project in which I need to have an autocomplete form call its information from a db file. I have seen many tutorials on jquery autocomplete forms, but I do not know how to call a db file to populate the list.

我在PHP工作。目前,code再presents一个简单的下拉框,是对人口数据库文件调用。

I am working in PHP. Currently the code represents a simple drop down box that is calling on the db file for population.

    <?php
    global $wpdb;
    $depts = $wpdb->get_results( "SELECT * FROM departments ORDER BY department_name ASC" );
    echo '<select>';

    foreach($depts as $row) {
        echo '<option name="select_dept" value="'.$row->department_id.'">'.$row->department_name.'</option>';
    }
    echo '</select>';
?>

任何帮助将是真棒!

Any help would be awesome!

推荐答案

最近我已经使用这个库自动完成 - 的 http://www.devbridge.com/projects/autocomplete/jquery/
因此,这里是根据你的简单脚本:

I recently have used this library for autocompletion - http://www.devbridge.com/projects/autocomplete/jquery/ So here is brief script based on yours:

<?php

$query = isset($_GET['query']) ? $_GET['query'] : FALSE;

if ($query) {
    global $wpdb;
    // escape values passed to db to avoid sql-injection
    $depts = $wpdb->get_results( "SELECT * FROM departments WHERE department_name LIKE '".$query."%' ORDER BY department_name ASC" );

    $suggestions = array();
    $data = array();
    foreach($depts as $row) {
        $suggestions[] = $row->department_name;
        $data[] = $row->department_id;
    }
    $response = array(
        'query' => $query,
        'suggestions' => $suggestions,
        'data' => $data,
    );
    echo json_encode($response);
} else {
?>
<html>
<body>
<input type="text" name="" id="box" />

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://www.devbridge.com/projects/autocomplete/jquery/local/scripts/jquery.autocomplete.js"></script>

<script type="text/javascript">

$(document).ready(function(){
    $('#box').autocomplete({ 
        serviceUrl:'/',
        // callback function:
        onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); },
    }); 
});
</script>
</body>
<html>
<?}?>

这篇关于自动完成表单由数据库填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆