开发者

mysql_real_escape_string on all mySQL queries?

Is mysql_real_escape_string supposed t开发者_Python百科o replace both addslashes() and stripslashes()??

ie.. do I use it to encode form input variables on MySQL inserts as well as use it in place of stripslashes on MySQL select statements?

Sincerely, Confused PHP noob


If you are using the regular MySQL driver module for PHP, then yes, mysql_real_escape_string() is the way to go. You can ignore addslashes() and stripslashes() entirely, in fact.

Your query creation will look something like this:

$sql = "INSERT INTO tbl (x) VALUES '".mysql_real_escape_string($x)."'";

mysql_real_escape_string() should be used on any user input that is going into your query. Note that you don't want to escape your data any other way before inserting it. You shouldn't use addslashes() or htmlentities(), which are common mistakes when storing HTML fragments in a database. You should not need to unescape your data in any way after you have retrieved it.

As other posters mention, there are other MySQL database driver modules for PHP, including PDO and MySQLi. Both offer a feature known as prepared statements, which is an alternative method of creating queries that handles escaping for you.


I recommend using PDO and prepared statements instead; see the PDOStatement class. Prepared statements can be more efficient (if the engine doesn't have to reparse your SQL). They should also prevent you from accidentally storing escaped data in the db (double-escaping). Using PDO will make it easier to add support for other databases.


Yes, it should do all the backslashing for you (based upon whatever charset the mysql server is)


Yes, it should escape strings in preparation for use in MySQL. However, it is not the be-all, end-all of avoiding SQL injection. It does in fact leave you very vulnerable to it still.

Better to use the PHP PDO instead, parameterized queries are the way to go ;)


I'd recommend using prepared statements. That way you won't have the hassle of manually escaping every query.

$stmt = $db->prepare("SELECT stuff FROM table WHERE something = ?");
$stmt->execute('s', 'something'); // s means string

Another option is to use PDO, which is an even better version of this, and generally database independent.


http://php.net/manual/en/function.mysql-real-escape-string.php

You wouldn't want to use addslashes() and stripslashes(). If I recall correctly, mysql_real_escape_string() is more similiar to addslashes(), but it escapes different characters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜