What are potential pitfalls when using PHP to display database results in HTML forms?

One potential pitfall when using PHP to display database results in HTML forms is not properly sanitizing user input, which can lead to security vulnerabilities such as SQL injection attacks. To mitigate this risk, always use prepared statements or parameterized queries to interact with the database, ensuring that user input is properly escaped.

// Example of using prepared statements to display database results in HTML forms

// Establish database connection
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Prepare SQL statement
$stmt = $mysqli->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);

// Set user input
$userId = $_POST['user_id'];

// Execute the query
$stmt->execute();

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

// Fetch results and display in HTML form
while ($stmt->fetch()) {
    echo "<input type='text' name='user_id' value='$id'>";
    echo "<input type='text' name='user_name' value='$name'>";
}

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