What are some common mistakes to avoid when trying to populate a dropdown field with database entries in PHP?

When populating a dropdown field with database entries in PHP, common mistakes to avoid include not sanitizing user input to prevent SQL injection, not properly connecting to the database, and not handling errors effectively. To solve these issues, always use prepared statements to prevent SQL injection, ensure a successful database connection, and implement error handling to catch any potential issues.

// Establish a database connection
$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 to populate dropdown field
$sql = "SELECT id, name FROM table";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<option value='" . $row["id"] . "'>" . $row["name"] . "</option>";
    }
} else {
    echo "0 results";
}

$conn->close();