What are potential pitfalls when trying to automatically select an option in a dropdown menu based on database query results in PHP?

When trying to automatically select an option in a dropdown menu based on database query results in PHP, a potential pitfall is not properly handling cases where the database query does not return any results or the selected option does not exist in the dropdown menu. To solve this issue, you can first check if the query returns any results before setting the selected option in the dropdown menu.

// Perform database query
$query = "SELECT option_value FROM options_table WHERE condition = 'value'";
$result = mysqli_query($conn, $query);

// Check if query returns results
if(mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);
    $selected_option = $row['option_value'];
} else {
    $selected_option = ""; // Default value if no results
}

// Create dropdown menu with selected option
echo "<select>";
echo "<option value='option1' " . ($selected_option == 'option1' ? 'selected' : '') . ">Option 1</option>";
echo "<option value='option2' " . ($selected_option == 'option2' ? 'selected' : '') . ">Option 2</option>";
echo "<option value='option3' " . ($selected_option == 'option3' ? 'selected' : '') . ">Option 3</option>";
echo "</select>";