Vote Up 0 Vote Down

addslashes vs mysql real escape string - which to use ?

I am confused about using addslashes and mysqlrealescape_string function. Both of which escapes the special characters. Which can be used for better security and usability. And why to use it ? Can we store strings without escaped in the database.

I am using currently mysql database. Any help appreciated.
flag
edited on 28/4/12

Answers


Vote Up 0 Vote Down
Using mysql_real_escape_string() function is preferred because you are using mysql database. And then you can use stripslashes() function while retrieving data.

Escaping strings is very important when we store string data in the database. Otherwise some security holes may happen.

The following are steps:

Step 1:
Inserting into database

$str  = "I'am Happy"; //original string
$escaped_str = mysql_real_escape_string($str); // escape the string
$res = mysql_query("insert into mytable set mycol = '{$escaped_str}'"); //now it is safe to enter in database


Step 2:
Fetching and displaying data

$res = mysql_query("select mycol from mytable limit 1");
$row = mysql_fetch_array($res);
$output = $row[0];

echo stripslashes($output); //prints as "I'am Happy"
flag | link |

Your Answer

Login before answering

Login with facebook