What best practices should be followed when handling database queries and displaying data in a PHP script?

When handling database queries and displaying data in a PHP script, it is important to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to validate and sanitize user input before executing any queries to ensure data integrity. Finally, always handle errors gracefully by using try-catch blocks to catch any exceptions that may occur during database operations.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");

// Bind parameters and execute the query
$user_id = 1;
$stmt->bindParam(':id', $user_id, PDO::PARAM_INT);
$stmt->execute();

// Fetch and display the results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "User ID: " . $row['id'] . "<br>";
    echo "Username: " . $row['username'] . "<br>";
}