简体   繁体   中英

Convert into secure PDO statement?

Could someone show me how I would go about converting my current UPDATE tablename SET column into a safe and secure statement using PDO to protect against SQL injection ? I am trying to better understand binding and PDO but am having trouble with setting it up with PDO. Here is what I currently have with regular 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'");


?>

MySQL

You don't need PDO or MySQLi for that. mysql_real_escape_string protect you against sql injection:

$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

With PDO::quote()

PDO::quote() is equal to 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);

With prepared statements

You can use prepared statements. You could put the hole query inside the prepared statement, but it is better to use placeholders for variables:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM