Page 1 of 1

safely adding text into a database

Posted: Fri Mar 21, 2003 3:45 pm
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

Posted: Fri Mar 21, 2003 4:13 pm
by daven
mysql_escape_string() to put stuff in the DB.
When you retrieve it: htmlspecialchars() and nl2br().

Posted: Sat Mar 22, 2003 2:19 am
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

Posted: Sat Mar 22, 2003 2:40 am
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

magic_quotes_gpc = On

Posted: Sat Mar 22, 2003 6:29 am
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.

Posted: Sat Mar 22, 2003 7:54 am
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

Posted: Mon Mar 24, 2003 1:17 pm
by toms100
many thanks for the help guys, that is very usefull to me:)