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

When handling and displaying data from a database in PHP applications, it is important to sanitize user input to prevent SQL injection attacks. This can be done by using prepared statements or parameterized queries. Additionally, it is recommended to validate and sanitize data before displaying it to the user to prevent cross-site scripting attacks.

// Example of using prepared statements to handle and display data from a database

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

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

// Bind parameters
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);

// Execute the query
$stmt->execute();

// Fetch the data
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Display the user data
echo "User ID: " . $user['id'] . "<br>";
echo "Username: " . htmlspecialchars($user['username']) . "<br>";
echo "Email: " . htmlspecialchars($user['email']) . "<br>";