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

One best practice for handling database queries in PHP is to use prepared statements to prevent SQL injection attacks. Another good practice is to properly sanitize user input before using it in a query. Additionally, it's important to close database connections after they are no longer needed to free up resources.

// Example of using prepared statements to handle database queries in PHP

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

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

// Bind the placeholder to a variable
$stmt->bindParam(':username', $username);

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

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

// Close the database connection
$pdo = null;