What are the best practices for constructing SQL queries in PHP to prevent syntax errors and ensure proper data retrieval from a database?

When constructing SQL queries in PHP, it is crucial to properly sanitize user input to prevent SQL injection attacks and syntax errors. One way to achieve this is by using prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, ensuring that the input is treated as data rather than executable code.

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

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

// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

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

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

// Loop through the results
foreach ($results as $row) {
    // Process the data
}