What best practices should be followed when retrieving data from a database within HTML output in PHP?

When retrieving data from a database within HTML output in PHP, it is important to properly sanitize the data to prevent SQL injection attacks and ensure the security of your application. One common practice is to use prepared statements with parameterized queries to safely retrieve data from the database.

<?php
// 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 a SQL query
$stmt = $conn->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("i", $id);

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

// Get the result set
$result = $stmt->get_result();

// Fetch data and output in HTML
while ($row = $result->fetch_assoc()) {
    echo "<div>{$row['column']}</div>";
}

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