What is the best practice for fetching and displaying data from a MySQL database in PHP?

When fetching and displaying data from a MySQL database in PHP, it is best practice to use prepared statements to prevent SQL injection attacks. This involves binding parameters to the query before execution. Additionally, it is important to properly handle errors and sanitize user input to ensure data integrity.

<?php
// Establish a connection to the MySQL database
$connection = new mysqli("localhost", "username", "password", "database");

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

// Prepare a SQL query using a prepared statement
$query = $connection->prepare("SELECT column1, column2 FROM table WHERE condition = ?");
$condition = "some_value";
$query->bind_param("s", $condition);
$query->execute();

// Bind the result variables
$query->bind_result($result1, $result2);

// Fetch and display the data
while ($query->fetch()) {
    echo "Column 1: " . $result1 . ", Column 2: " . $result2 . "<br>";
}

// Close the connection
$connection->close();
?>