1
<?php
$user = 'john';
$pwd = "' OR ''='";
$sql = "SELECT * FROM users WHERE
user='" . $user . "' AND password='" . $pwd . "'";
echo $sql.'<br />';
// escape username and password for use in SQL
$user = mysql_real_escape_string($user);
$pwd = mysql_real_escape_string($pwd);

$sql_escaped = "SELECT * FROM users WHERE
user='" . $user . "' AND password='" . $pwd . "'";

echo $sql_escaped;
?> 

It shows:

SELECT * FROM users WHERE user='john' AND password='' OR ''=''
SELECT * FROM users WHERE user='john' AND password='\' OR \'\'=\'' 

Question:

How does mysql interpret this line: password='\' OR \'\'=\''? password equals \ or what?

1
  • Escape sequences in MySQL are almost identical to escape sequences in PHP. Even Stack Overflow's syntax highlighter gives a pretty good clue... Commented Jul 29, 2013 at 9:42

3 Answers 3

1

It will find records where the password matches exactly ' OR ''='

The backslash is escaping the single quotes so that the $pwd can't break out of the outer containing quotes.

Escaping in this way is a primitive way of preventing SQL Injection. Prepared Statements are much preferred because no escaping is required, the MySQL engine receives the variables as parameters separately to the query and so no concatenation is required and leaves no possibility of SQL Injection.

Sign up to request clarification or add additional context in comments.

Comments

0

"password equals \ or what?"

No, because a \ always escapes the following character. So in your case password would equal ' OR ''='. The \ make sure that the following character is not interpreted as a single quote but as a string. That's what the method mysql_real_escape_string() is for. You can even see that in the SO-highlighting in your example.

More on the topic SQL Injection and some examples can be found here.

Comments

0

MYSQL do sth like this :

SELECT '\'1' - returns '1 because \ turns off special meaning of ' character

so in Your example your password='\' OR \'\'=\'' is interprated as ' OR ''='

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.