What best practices should be followed when retrieving and displaying data from a database in PHP for dropdown menus?

When retrieving data from a database in PHP for dropdown menus, it's important to sanitize the input to prevent SQL injection attacks. Additionally, you should use prepared statements to safely retrieve data from the database. Finally, when displaying the data in dropdown menus, make sure to properly format the data as options within the select element.

// Connect to 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);
}

// Prepare and execute query
$stmt = $conn->prepare("SELECT id, name FROM table");
$stmt->execute();
$stmt->bind_result($id, $name);

// Create dropdown menu
echo "<select>";
while ($stmt->fetch()) {
    echo "<option value='" . $id . "'>" . $name . "</option>";
}
echo "</select>";

// Close connection
$stmt->close();
$conn->close();