How can SQL queries be optimized to display all categories in a dropdown menu while retaining the default value from the database in PHP?
To optimize SQL queries to display all categories in a dropdown menu while retaining the default value from the database in PHP, you can first query all categories and then use a loop to populate the dropdown menu options. After that, you can check if the default value exists in the list of categories and set it as selected in the dropdown menu.
// Query to get all categories from the database
$sql = "SELECT * FROM categories";
$result = mysqli_query($connection, $sql);
// Populate dropdown menu with categories
echo "<select name='category'>";
while ($row = mysqli_fetch_assoc($result)) {
$selected = ($row['id'] == $defaultCategory) ? "selected" : "";
echo "<option value='" . $row['id'] . "' $selected>" . $row['name'] . "</option>";
}
echo "</select>";