mysqli_real_escape_stringThis is a built-in PHP function and one of the commonly used methods to prevent SQL injection attacks. When replacing it with another function, the new function must support the escaping of special characters; for example, you can use the `PDO` method.PDO::quoteFunction SumbindParamThis method achieves the same effect. Additionally, other approaches can be used.addslashesEscape the function.
Here is an example code using PDO and the addslashes function:
Example code using PDO:
// 数据库连接
$host = 'localhost';
$user = 'username';
$pass = 'password';
$dbName = 'database_name';
$dsn = "mysql:host=$host;dbname=$dbName;charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];
$pdo = new PDO($dsn, $user, $pass, $options);
// 防止SQL注入
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$username = $pdo->quote($username);
$password = $pdo->quote($password);
$sql = "SELECT * FROM users WHERE username=$username AND password=$password";
$stmt = $pdo->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 处理查询结果
}In the above code, we usePDO::quoteThis function escapes special characters in the input string, making it safe to use when constructing SQL statements.
UseaddslashesExample code:
// 数据库连接
$host = 'localhost';
$user = 'username';
$pass = 'password';
$dbName = 'database_name';
$db = mysqli_connect($host, $user, $pass, $dbName);
if (!$db) {
die("无法连接到数据库: " . mysqli_connect_error());
}
// 防止SQL注入
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = addslashes($_POST['username']);
$password = addslashes($_POST['password']);
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($db, $sql);
// 处理查询结果
}In the above code, we have usedaddslashesThis function escapes special characters in the input string, making it safe to use when constructing SQL statements. Note that,addslashesFunctions have certain limitations; in some cases, they may not fully prevent SQL injection attacks. Therefore, they are not recommended as the sole means of defending against SQL injection attacks.