What are the potential security risks associated with mixing HTML and database queries in PHP, and how can they be mitigated?

Mixing HTML and database queries in PHP can lead to SQL injection attacks if user input is not properly sanitized. To mitigate this risk, it is important to use prepared statements with parameterized queries to prevent malicious SQL code from being executed.

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

// Prepare a SQL statement with a parameterized query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Sanitize user input
$username = htmlspecialchars($_POST['username']);

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

// Fetch results
$result = $stmt->get_result();

// Display the results in HTML
while ($row = $result->fetch_assoc()) {
    echo "<p>" . $row['username'] . "</p>";
}

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