phpmysqladdslashes

backslash in php and mysql


I have a question about backslash in MySql and PHP! I write a simple code for testing!

include "src/db.inc.php";
$name="licon's";
$name=addslashes($name);
$sql="insert into test values('$name')";
mysql_query($sql);
$sql1="select * from test";
$rs=mysql_query($sql1);
$row=mysql_fetch_assoc($rs);
echo $row['name'];

as the code displays, I want to insert a string with a single quote into an table.

1.I need to escape the string, here I use the function addslashes(). so the $name will be something like this "licon\'s".

2.but when I insert into $name into the table and I select it in mysql console, the backslashes added by the function addslashes disappear. just as the following:

mysql> select * from test;
+---------+
| name    |
+---------+
| licon's |
+---------+

3.when I select the field 'name' in PHP script and print it, the backslash also disappears.
as the following:

$sql1="select * from test";
$rs=mysql_query($sql1);
$row=mysql_fetch_assoc($rs);
echo $row['name'];
======
print: licon's 

so I want to know the function addslashes() add a backslash in the variable $name. why the backslash disappear?


Solution

  • addslashes() and stripslashes() are some old way of manipulating the quotes into and from DB.

    The reason is old PHP versions has magic_quotes_gpc() which is on by default on and this would do the following for Get/Post/Cookie operations.

    Now while you need to echo it would require stripslashes()

    The new PHP and mysql does not need that at all and mysql is pretty good to handle your quotes and special charters so the best thing to use is mysql_real_escape_string() or equivalent mysqli_ functions.

    And more importantly This feature has been DEPRECATED as of PHP 5.3.0 so probably its doing nothing as you are doing addslashes()

    No, addslashes adds slashes to the data that you're sending to MySQL, but MySQL removes them before storing the data in the database. MySQL interprets \' as a piece of data, while interpreting a single ' as part of the SQL statement syntax.