What are the potential pitfalls to avoid when working with MySQL queries in PHP to populate form elements?

One potential pitfall to avoid when working with MySQL queries in PHP to populate form elements is not properly sanitizing user inputs, which can lead to SQL injection attacks. To prevent this, always use prepared statements and parameterized queries to securely interact with the database.

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

// Prepare a statement and bind parameters
$stmt = $conn->prepare("SELECT id, name FROM table WHERE id = ?");
$stmt->bind_param("i", $id);

// Set parameters and execute
$id = 1;
$stmt->execute();

// Bind result variables
$stmt->bind_result($id, $name);

// Fetch results and populate form elements
while ($stmt->fetch()) {
    echo "<option value='$id'>$name</option>";
}

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