Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - execute PHP code when selecting a combobox item

I have a static combobox in a php web page.I want when selecting an item from this combobox (example 'item 1') the php execute a SELECT statement to get the value of a field named 'item 1' from a table X in my database.

How that can be done ?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You will need to use AJAX to do this. Here is a simple example:

HTML

Just a simple select box, for the purposes of this example.

<select id='items'>
    <option value='1'>Item 1</option>
    <option value='2'>Item 2</option>
    <option value='3'>Item 3</option>
</select>

JavaScript

I'm going to use jQuery here, you don't have to if you don't want to but it makes AJAX a whole lot easier.

The browser will listen for a change event on the select box and perform an AJAX request to the appropriate URL. When the server sends back data, the success function will be triggered. Read more about .ajax() in the jQuery documentation.

$(document).ready(function() {
    $('#items').change(function() {
        $.ajax({
            type: 'GET',
            url: 'pageWithPhpCode.php',
            data: {
                itemID: $(this).val()
            },
            dataType: 'json',
            success: function(data) {
                // do whatever here
                console.log(data);
            }
        });
    });
});

PHP

Here I'm retrieving the data, JSON encoding it, and sending it back to the client with the appropriate MIME type. I'm not sure how you connect to your MySQL database, but I'm using PDO here.

Keep in mind that mysql_* functions are deprecated.

<?php
if(isset($_GET['itemID'])) {
    $db = new PDO();
    // ... connect to your database, however you do it

    $q = 'SELECT * FROM items WHERE id = :itemid;';
    $stmt = $db->prepare($q);
    $stmt->bindValue(':itemid', $_GET['itemID'], PDO::PARAM_INT);
    $stmt->execute();

    $output = $stmt->fetchAll(PDO::FETCH_ASSOC);

    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($output);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...