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

Categories

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

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

1 Answer

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...