What are the best practices for fetching and displaying data from a MySQL database in PHP?

When fetching and displaying 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 user input to ensure data integrity. Finally, use error handling to gracefully handle any potential database errors.

// 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 SQL query to fetch data
$stmt = $conn->prepare("SELECT id, name, email FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();

// Display the fetched data
while ($row = $result->fetch_assoc()) {
    echo "ID: " . $row['id'] . "<br>";
    echo "Name: " . $row['name'] . "<br>";
    echo "Email: " . $row['email'] . "<br>";
}

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