Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using addslashes/stripslashes to escape MySQL queries - how to undo? 1

Status
Not open for further replies.

badcoder7

Programmer
Aug 9, 2012
5
US
Some time back, I inherited a project where the original coding used addslashes/stripslashes to escape/unescape text in/out of MySQL. I've continued to use that method of escaping and have only just now come across a problem with it.

To insert the original string

O'Brian says "Don't do it! 1\2\3

Addslashes does add a backslash to each backslash in the original string

INSERT INTO test VALUES ('O\'Brian says \"Don\'t do it!\" 1\\2\\3')

But on retrieval, stripslashes strips ALL the backslashes and outputs:

O'Brian says "Don't do it!" 123

I'm looking at using $mdb2->quote() going forward, which seems to be working okay in my initial tests, but anybody have any suggestions about how to fix all the hundredes of queries (which addslashes/stripslashes) in the 1.4 million lines of existing code?

Is it possible to redefine built-in functions in PHP so I could maybe intercept and redefine all calls to addslashes and stripslashes so that addslashes actually executes $mdb2->quote() and stripslashes doesn't do anything?

If so, how might I clean up all my existing data which has been written with addslashes?
 
what do you mean 'retrieval'? when the data is written to the database it does not have the escaping slashes in it. just the desired data. so when you read the data back into a variable it is not escaped (and does not have to be). So no need to use stripslashes.

do not, in any event, use addslashes for mysql. either use PDO placeholders with prepare ... execute syntax or if using procedural code use mysql_real_escape_string to escape.
 
Wow, I had no idea. I just assumed the escape slashes were written to the DB and continued the original convention of inserting with addslashes and running all extracted fields through stripslashes before outputting to the browser.

PHP.net states about mysql_real_escape_string(): "Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used." Do you think mysql_real_escape_string() will eventually be deprecated and someday be removed from PHP? Since this project uses MDB2, maybe $mdb2->escape() would be a better choice?
 
I have had a brief look at the code of mdb2 and it seems that the escape function is just a str_replace(). I would not recommend this.

I recommend PDO.

I don't think that mysql_real_escape_string will be deprecated soon.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top