What are some best practices for handling and manipulating data retrieved from a database in PHP?

When handling and manipulating data retrieved from a database in PHP, it is important to properly sanitize input to prevent SQL injection attacks, validate data to ensure it meets expected criteria, and use prepared statements to securely interact with the database.

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

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

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

// Bind the user input to the placeholder
$stmt->bindParam(':id', $user_id, PDO::PARAM_INT);

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

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

// Use the retrieved data
echo $user['username'];