What are some best practices for handling data retrieved from a database in PHP to ensure proper processing and output?

When handling data retrieved from a database in PHP, it is important to properly sanitize and validate the data to prevent SQL injection attacks and ensure data integrity. One best practice is to use prepared statements with parameterized queries to securely interact with the database. Additionally, always validate and sanitize user input before using it in database queries to avoid security vulnerabilities.

// Example of using prepared statements to handle data retrieved from a database in PHP

// 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 to the prepared statement
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);

// Execute the prepared statement
$stmt->execute();

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

// Sanitize and output the retrieved data
echo htmlspecialchars($userData['username']);