Need to prevent sql injection when querying the database
Implementation method:
PHP comes with its own method SQL statements can be escaped, and backslashes are added before certain characters when required in database query statements. These characters are single quotes ('), double quotes ("), backslash (\) and NUL (NULL character). (Recommended learning: PHP Programming from Beginner to Master)
string addslashes ( string $str )//该函数返回一个字符串
Example
<?php $str = "Is your name O'reilly?"; // 输出: Is your name O\'reilly? echo addslashes($str); ?>
ThinkPHP automatically provides security protection. For string type data, ThinkPHP will perform escape_string processing (real_escape_string, mysql_escape_string)
To effectively prevent SQL injection Question, official recommendation:
Try to use arrays for query conditions, which is a safer way;
If you must use string query conditions as a last resort, use the preprocessing mechanism;
Use automatic verification and automatic completion mechanisms for custom filtering of applications;
If the environment permits, try to use PDO and use parameter binding.
Query condition preprocessing
This method is similar to putting a placeholder in the query statement, and then passing in the parameters in the form of an array
For example:
$Model->where("id=%d and username='%s' and xx='%f'",array($id,$username,$xx))->select(); $Model->where("id=%d and username='%s' and xx='%f'",$id,$username,$xx)->select();
The above is the detailed content of How to prevent sql injection in php. For more information, please follow other related articles on the PHP Chinese website!