Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

php - Autocomplete form populated by a database?

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.

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>
<?}?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...