What best practices should be followed when retrieving and displaying data from a MySQL database in PHP?

When retrieving and displaying data from a MySQL database in PHP, it is important to use prepared statements to prevent SQL injection attacks. Additionally, it is good practice to sanitize user input to prevent cross-site scripting attacks. Finally, ensure that error handling is implemented to gracefully handle any database connection or query errors.

// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Prepare and execute a query using a prepared statement
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $columnValue);
$columnValue = "value";
$stmt->execute();
$result = $stmt->get_result();

// Display the retrieved data
while ($row = $result->fetch_assoc()) {
    echo "Column: " . $row["column"] . "<br>";
}

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