tags:

views:

510

answers:

4

In my code i am using addslashes to escape certain characters while inserting them into the database and when i send some information out i use stripslashes to remove those slashes, the situation is stripslashes function removes all the slashes so if i need to send any string which has backslashes those also get removed. How can i retain those required slashes.

Any help will be greatly appreciate.

+6  A: 

You might want to try using mysql_real_escape_string. You don't have to unescape it, and it is safe for database use.

Better yet, use prepared statements

Chacha102
Thanks for the inputs, in a scenario where the code has extensively used addslashes and has to maintain compatibility with both MSSQL and MYSQL will the mysql_real_escape_string still work ? I think it will, as it is php function, just want to confirm. Also is it advisable to use some encoding function like str_replace ("\\", "\", stripslashes($string)). Please advice.
pks83
I'd would look at prepared statements. Because if you put in prepared statements, you are going to get the same thing going in as you get coming out. Meaning that it won't break you current slashes stuff if you don't want to redo the whole system immediately. If you use the PDO library for prepared statements, you will get compatibility with any database.
Chacha102
A: 

I think it's better to use htmlspecialchars for escaping the data for database storage. You don't have to worry about restoring them after getting them from the database as they will be handled correctly by the browser.

RaYell
The only problem with this is that when you actually want things like HTML tags to be preserved, like on a form or a blog, you have to remember to unencode them.
Chacha102
This protects against bad HTML and should be done when outputting to HTML. It doesn't protect against SQL Injection, which is the danger when putting data into a database.
David Dorward
Still seems like a better idea then using `addslashes` and `stripslashes`.
RaYell
It is a good idea, just not an answer to the question.
Chacha102
+2  A: 

You can try using PDO prepared statements when inserting to database so you don't need to worry about escaping anything.

ian
A: 

In my code i am using addslashes to escape certain characters while inserting them into the database and when i send some information out i use stripslashes to remove those slashes ...

You're doing it wrong. You must escape strings when you embed them in a query. You do not unescape data when it comes back from the database. There are no slashes to remove. They only exists in the query - not in the database.

Besides that, bound parameters/prepared statements are much better, as already noted by others in this thread.

troelskn