What best practices should be followed when writing SQL queries in PHP to prevent unexpected errors like "unexpected T_STRING"?

When writing SQL queries in PHP, it's important to properly escape and sanitize input values to prevent unexpected errors like "unexpected T_STRING." This error occurs when a string is not properly enclosed in quotes in the SQL query, leading to syntax errors. To avoid this issue, always use prepared statements with placeholders for dynamic values in the query. Example PHP code snippet:

// Establish a database connection
$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 value to the placeholder and execute the query
$username = $_POST['username']; // Assuming this is user input
$stmt->bindParam(':username', $username);
$stmt->execute();

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

// Loop through the results
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}