php – 由数据库填充的自动填充表单?

我目前正在开发一个项目,我需要在其中使用自动填充表单从db文件中调用其信息.我已经看过很多关于jquery自动完成表单的教程,但我不知道如何调用db文件来填充列表.

我在PHP工作.目前,代码表示一个简单的下拉框,它调用db文件以进行填充.

<?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>';
?>

任何帮助都是极好的!

我最近使用这个库进行自动完成 – http://www.devbridge.com/projects/autocomplete/jquery/
所以这里是基于你的简短脚本:

<?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>
<?}?>
相关文章
相关标签/搜索