Without the quotes, the user-submitted data will be seen as field references, and/or invalid SQL.
Consider a username of username
. A proper query would be:
SELECT ... FROM ... WHERE username='username'
and only match if there really is a user whose name is "username".
Without the quotes, it becomes:
SELECT ... FROM ... WHERE username=username
which would match ALL non-null records in the table.
Now consider a 2-part username: John doe
SELECT ... FROM ... WHERE username=John doe
The DB server will try to compare the username field against a field name 'John', which most likely doesn't exist. Then there's this "doe" thing in there which is not a field name, not an SQL key word, so is a syntax error.
Now consider a username: 1 or 1=1
SELECT ... FROM ... WHERE username=1 or 1=1
again, this will ALWAYS return true and match ALL rows, because "1=1" will always be true.
mysql_real_escape_string() only guarantees that any data you pass through it will not "break" a PROPERLY CONSTRUCTED query. If the query you're inserting the escaped data into is NOT properly constructed, then all bets are off.