# What are the differences between addslashes(), mysql_escape_string() and mysql_real_escape_string()

addslashes() escapes single quote (’), double quote ("), backslash (\\) and <span class="caps">NUL</span> (\\x00).

mysql\_escape\_string() and mysql\_real\_escape\_string() escapes the characters above plus: CR (\\r), LF (\\n) and <span class="caps">EOF</span> (\\x1a). Apparently (according to the manual), MySQL wants these characters escaped too, but my experiment shows otherwise (i.e. MySQL doesn’t care if these characters are in a string).

Suppose:

```
$value = 'bar'; // 'ba' and then CR-LF and then 'r'
```

print “insert into pairs values (‘foo’, ’” . addslashes($value) . “’)” gives:

```
insert into pairs values ('foo', 'ba\r\nr')
```

print “insert into pairs values (‘foo’, ’” . mysql\_real\_escape\_string($value) . “’)” gives:

```
insert into pairs values ('foo', 'bar')
```

In this case, the execution result should be the same, but the statement itself is different.

For other <span class="caps">EOF</span>, the execution result and statement are identical for both functions.

mysql\_real\_escape\_string() is available on <span class="caps">PHP</span> 4.3.0 or above. mysql\_escape\_string() is deprecated and you should use mysql\_real\_escape\_string() instead, as it takes the current character set into account when escaping characters.

addslashes() should be enough for single-byte strings. For multi-byte strings though,   
mysql\_real\_escape\_string() does provide better security. See [this article](http://www.newsforge.com/article.pl?sid=06/05/23/2141246) for details.

<span class="caps">PHP</span> manual on:

- [addslashes](http://us.php.net/addslashes)
- [mysql\_escape\_string](http://us.php.net/mysql_real_escape_string)
- [mysql\_real\_escape\_string](http://us.php.net/manual/en/function.mysql-escape-string.php)