0

有人可以告诉我如何UPDATE tablename SET column使用 PDO 将我的当前转换为安全可靠的语句以防止 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'");


?>
4

1 回答 1

5

MySQL

为此,您不需要 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

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,
));
于 2012-10-26T15:46:20.783 回答