What best practices should be followed when handling database queries and storing data in arrays in PHP to ensure efficient and error-free code?

When handling database queries and storing data in arrays in PHP, it is important to follow best practices to ensure efficient and error-free code. One key practice is to properly sanitize user input to prevent SQL injection attacks. Additionally, using prepared statements can help improve performance and security. It is also recommended to validate and sanitize data before storing it in arrays to avoid potential issues.

// Example of using prepared statements to handle database queries in PHP
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(['username' => $_POST['username']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Example of sanitizing and validating data before storing in an array
$cleanedData = [];
$cleanedData['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$cleanedData['email'] = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$cleanedData['age'] = filter_var($_POST['age'], FILTER_VALIDATE_INT);

// Storing data in an array
$data = [];
$data[] = $cleanedData;