What best practices should be followed when constructing SQL queries in PHP to avoid errors and vulnerabilities?

When constructing SQL queries in PHP, it is crucial to use parameterized queries to prevent SQL injection attacks. This involves using prepared statements with placeholders for dynamic data. By binding parameters to these placeholders, you can ensure that user input is properly sanitized and treated as data rather than executable code.

// Example of using parameterized queries to prevent SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

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

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

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

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