4

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?

Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
ChainWay
  • 133
  • 1
  • 10

2 Answers2

1

If you are using MySQL then use mysql_real_escape_string($name) or use mysqli_real_escape_string($connection,$name) if you are using MySQLi to get the clean input to store in the MySQL database.

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
Thompson
  • 1,954
  • 10
  • 33
  • 58
  • 2
    this is not the point!even I use mysql_real_escape_string($name),the backslashe will still disappear when I select it from mysql!I just want to know why I do not need to use stripslashes! – ChainWay Jan 21 '14 at 07:18
  • 1
    THIS IS THE ONLY POINT – Strawberry Jan 21 '14 at 07:28
0

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.

  • When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) are escaped with a backslash automatically

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.

Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63