有人可以告诉我如何使用PDO将当前UPDATE tablename SET column
转换为安全可靠的语句来防止SQL注入?我正在尝试更好地理解绑定和PDO,但是在使用PDO进行设置时遇到了问题。这是我目前常规msqli
<?php
session_start();
$db = mysqli_connect("hostname", "username", "password", "dbname");
$username = $_SESSION['jigowatt']['username'];
mysqli_query($db, "UPDATE login_users SET Points=Points+15 WHERE username='$username'");
?>
答案 0 :(得分:5)
您不需要PDO或MySQLi。 mysql_real_escape_string
保护您免受SQL注入:
$name = 'Bob';
$age = 25;
$description = "' OR 1=1"; // a SQL injection string
$query = "
UPDATE people(name, age, description)
VALUES ('".mysql_real_escape_string($name)."', ".(int) $age.", '".mysql_real_escape_string($description)."');";
// a secure query execution
$result = mysql_query($query);
PDO::quote()
PDO::quote()
等于mysql_real_escape_string
:
$pdo = new PDO(...);
$name = 'Bob';
$age = 25;
$description = "' OR 1=1"; // a SQL injection string
$query = "
UPDATE people(name, age, description)
VALUES (".$pdo->quote($name).", ".(int) $age.", ".$pdo->quote($description).");";
// a secure query execution
$result = $pdo->query($query);
您可以使用预准备语句。您可以将漏洞查询放在预准备语句中,但最好使用占位符表示变量:
$pdo = new PDO(...);
$name = 'Bob';
$age = 25;
$description = "' OR 1=1"; // a SQL injection string
$query = "
UPDATE people(name, age, description)
VALUES (:name, :age, :description);";
$stmt = $pdo->prepare($query); // prepare the query
// execute the secure query with the parameters
$result = $pdo->execute(array(
':name' => $name,
':age' => $age,
':description' => $description,
));