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,
));