Wednesday, June 10, 2009

Formatting Strings for Storage: AddSlashes() and StripSlashes()

As well as using string functions to reformat a string visually, we can use some of these
functions to reformat strings for storage in a database.Although we won’t cover actually
writing to the database until Part II,“Using MySQL,” we will cover formatting strings
for database storage now.
Certain characters are perfectly valid as part of a string but can cause problems, particularly
when inserting data into a database because the database could interpret these
102 Chapter 4 String Manipulation and Regular Expressions
characters as control characters.The problematic ones are quotes (single and double),
backslashes (\), and the NUL character.
We need to find a way of marking or escaping these characters so that databases such
as MySQL can understand that we meant a literal special character rather than a control
sequence.To escape these characters, add a backslash in front of them. For example, "
(double quote) becomes \" (backslash double quote), and \ (backslash) becomes \\
(backslash backslash). (This rule applies universally to special characters, so if you have \\
in your string, you need to replace it with \\\\.)

No comments:

Post a Comment