Skip to content
PHP Logo

How can you dynamically fill a select box with values from a database based on the selection in another select box?

To dynamically fill a select box with values from a database based on the selection in another select box, you can use AJAX to fetch the data from the database and update the second select box based on the selected value in the first select box. You can create a PHP script that will return the values based on the selected option and use JavaScript to make an AJAX call to this script and update the second select box accordingly.

php
<?php
// Assuming you have a database connection established

if(isset($_POST['selected_option'])) {
    $selected_option = $_POST['selected_option'];

    // Query database to get values based on selected option
    $query = "SELECT * FROM table WHERE column = '$selected_option'";
    $result = mysqli_query($connection, $query);

    // Generate options for the second select box
    $options = '';
    while($row = mysqli_fetch_assoc($result)) {
        $options .= '<option value="' . $row['value'] . '">' . $row['label'] . '</option>';
    }

    echo $options;
}
?>