safely adding text into a database

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
toms100
Forum Contributor
Posts: 119
Joined: Wed Feb 26, 2003 10:29 am
Location: Bristol,UK

safely adding text into a database

Post by toms100 »

im trying to make a forum system, but how do i do the following:
-Replace 'returns' in the text box with <br> (so stuff is on seperate lines)
-Insert text which has stuff like ' " ) without ruiining the sql code.

hope you can help

Tom
User avatar
daven
Forum Contributor
Posts: 332
Joined: Tue Dec 17, 2002 1:29 pm
Location: Gaithersburg, MD
Contact:

Post by daven »

mysql_escape_string() to put stuff in the DB.
When you retrieve it: htmlspecialchars() and nl2br().
toms100
Forum Contributor
Posts: 119
Joined: Wed Feb 26, 2003 10:29 am
Location: Bristol,UK

Post by toms100 »

ok thanks for reply.
so say i have a text string "hello 209')9sd'sda"
and i wish to add it to database
i do $tString = mysql_escape_string("hello 209')9sd'sda")
then insert $tString into the db?

thanks
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Yes and then when you've selected it from the database and want to display it:
http://www.php.net/stripslashes
http://www.php.net/htmlspecialchars
http://www.php.net/nl2br

Mac
ups216
Forum Newbie
Posts: 3
Joined: Thu Mar 20, 2003 8:00 pm
Location: Sydney
Contact:

magic_quotes_gpc = On

Post by ups216 »

If you can put

magic_quotes_gpc = On

in your php.ini file, you don't have to do string escape. Just put your input string into SQL query, PHP will convert it automatically.

However, when you put them back to web page, use htmlspecialchars() and nl2bar() to decode them porperly.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Don't turn magic_quotes on as ups216 suggested. Use mysql_escape_string() or addslashes() when you need special characters escaped. You won't always want everything to be automatically escaped.

Mac
toms100
Forum Contributor
Posts: 119
Joined: Wed Feb 26, 2003 10:29 am
Location: Bristol,UK

Post by toms100 »

many thanks for the help guys, that is very usefull to me:)
Post Reply