转换为安全的PDO声明?

时间:2012-10-26 15:10:17

标签: php mysql pdo mysqli sql-injection

有人可以告诉我如何使用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'");


?>

1 个答案:

答案 0 :(得分: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,
));