How can PHP be used to populate dropdown menus from a MySQL database and ensure the values are dependent on each other?
To populate dropdown menus from a MySQL database and ensure the values are dependent on each other, you can use AJAX to dynamically update the second dropdown based on the selection in the first dropdown. This can be achieved by sending a request to the server with the selected value from the first dropdown and fetching the corresponding options for the second dropdown.
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
// Fetch options for first dropdown
$sql = "SELECT DISTINCT category FROM items";
$result = $conn->query($sql);
echo "<select id='firstDropdown'>";
echo "<option value=''>Select Category</option>";
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row['category'] . "'>" . $row['category'] . "</option>";
}
echo "</select>";
// Fetch options for second dropdown based on selection in first dropdown
echo "<select id='secondDropdown'>";
echo "<option value=''>Select Item</option>";
echo "</select>";
$conn->close();
?>