What are some best practices for retrieving and displaying user data from a MySQL database in PHP?

When retrieving and displaying user data from a MySQL database in PHP, it is important to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to sanitize and validate user input before querying the database to ensure data integrity. Finally, consider using a loop to fetch and display the data in a user-friendly format on the webpage.

<?php
// Establish a connection to the 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);
}

// Prepare and execute a query to retrieve user data
$stmt = $conn->prepare("SELECT id, username, email FROM users");
$stmt->execute();
$stmt->bind_result($id, $username, $email);

// Fetch and display the user data
while ($stmt->fetch()) {
    echo "ID: " . $id . " | Username: " . $username . " | Email: " . $email . "<br>";
}

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