Is there some code that I can use to filter through strings to put escape characters in front of invalid MySQL characters?
I'm building a comment section on my website and I need to be able t开发者_JS百科o filter through strings and escape invalid characters?
Is there any code that can automate this and return a string with escape characters properly placed?
I use PHP btw.
You want mysql_real_escape_string()
, or bind your params with something like PDO.
Use the built-in msyql_ functions: mysql_real_escape_string.
Using bound variables is generally better practice than just escaping a string.
First I'll parrot the party line that you should really consider learning to use a database abstraction layer or ORM as this will be better in the long term. I'll leave the holy wars about which package to user for this (and the merits of PDO, etc..) to someone else.
If you're using a recent version of PHP you should have the MySQLi (MySQL improved extension). This extension allows bound parameters as explained here:
http://php.net/manual/en/mysqli-stmt.bind-param.php
Also note that while escaping a string is a good start, it's NOT enough.
see: Is htmlentities() and mysql_real_escape_string() enough for cleaning user input in PHP?
精彩评论