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

When retrieving and displaying data from a MySQL database using PHP, it is important to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to sanitize user input and validate data before querying the database. Finally, handle errors gracefully and securely display data to users.

// Connect to MySQL database
$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);
}

// Retrieve and display data from database using prepared statement
$stmt = $conn->prepare("SELECT id, name, email FROM users WHERE id = ?");
$stmt->bind_param("i", $id);

$id = 1; // Example ID
$stmt->execute();
$stmt->bind_result($id, $name, $email);

while ($stmt->fetch()) {
    echo "ID: " . $id . " | Name: " . $name . " | Email: " . $email . "<br>";
}

$stmt->close();
$conn->close();