What best practices should be followed when constructing SQL queries in PHP to prevent errors like the one in the code example?
When constructing SQL queries in PHP, it is important to use prepared statements with parameterized queries to prevent SQL injection attacks and errors. This involves using placeholders for dynamic values in the query and binding the actual values separately. This approach helps to sanitize user input and ensures that the SQL query is executed safely.
// Example of constructing SQL query with prepared statement
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
// Prepare the SQL query with placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the actual value to the placeholder
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);