What are some best practices for handling database queries in PHP code?

When handling database queries in PHP code, it is important to use parameterized queries to prevent SQL injection attacks. This involves using prepared statements with placeholders for dynamic data. Additionally, it is recommended to validate and sanitize user input before executing any queries to ensure data integrity and security.

// Example of handling a database query using parameterized queries in PHP
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

// Bind parameter values to placeholders
$stmt->bindParam(':username', $username, PDO::PARAM_STR);

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

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