Home >Backend Development >PHP Tutorial >How to Create a Dependent Dropdown Menu Using PHP and AJAX?
You want to create a dynamic drop-down box where the options in the second drop-down box are dependent on the selection made in the first drop-down box.
Database Structure:
Table: category | id | master | name | | --- | ------ | ----- | | 1 | 0 | Main 1 | | 2 | 1 | Sub 1 | | 3 | 1 | Sub 2 | | 4 | 0 | Main 2 | | 5 | 4 | Sub 3 | | 6 | 4 | Sub 4 |
PHP Script for Index Page (tester.php):
<select name="master">
PHP Script for Data Population (another_php_file.php):
<?php if (isset($_POST['master_id']) && $_POST['master_id'] != '') { $master_id = $_POST['master_id']; $sql = "SELECT * FROM `category` WHERE `master` = ?"; $statement = $objDb->prepare($sql); $statement->execute(array($master_id)); $list = $statement->fetchAll(PDO::FETCH_ASSOC); echo '<option value="" selected disabled>Select Sub</option>'; if (!empty($list)) { foreach ($list as $row) { echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>'; } } } ?>
The above is the detailed content of How to Create a Dependent Dropdown Menu Using PHP and AJAX?. For more information, please follow other related articles on the PHP Chinese website!