How can PHP be used to create a dynamic cascading list structure from a database table?
To create a dynamic cascading list structure from a database table using PHP, you can retrieve the data from the database and use it to populate the dropdown lists. You can use AJAX to dynamically update the dropdown lists based on the selection made in the previous list.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve data for the first dropdown list
$sql = "SELECT DISTINCT category FROM items";
$result = $conn->query($sql);
echo "<select id='category'>";
echo "<option value=''>Select Category</option>";
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['category'] . "'>" . $row['category'] . "</option>";
}
echo "</select>";
// AJAX call to dynamically update the second dropdown list based on the selection made in the first list
echo "<select id='subcategory'></select>";
echo "<script>
$('#category').change(function(){
var category = $(this).val();
$.ajax({
url: 'get_subcategories.php',
method: 'POST',
data: {category: category},
success: function(response){
$('#subcategory').html(response);
}
});
});
</script>";
$conn->close();
?>
Keywords
Related Questions
- How can I ensure the integrity and consistency of my database when automatically overwriting it with a new dump file in PHP?
- How can PHP libraries like Buzz or Guzzle be utilized to extract MIME information from HTTP responses effectively?
- What are some best practices for retrieving weight information for products from a database and matching it with the appropriate shipping provider costs in PHP?