What best practices should be followed when writing PHP scripts to query a database?

When writing PHP scripts to query a database, it is important to follow best practices to ensure security, efficiency, and maintainability. One key practice is to use parameterized queries to prevent SQL injection attacks. Additionally, it is recommended to validate and sanitize user input before using it in a query to prevent potential vulnerabilities. Finally, consider using prepared statements for frequently executed queries to improve performance.

// Example of using parameterized query to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();
$results = $stmt->fetchAll();