Fix SQL syntax error

If $last equals true, there is a syntax error in the SQL query.