Reputation: 4519
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'");
?>
Upvotes: 0
Views: 1003
Reputation: 41934
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::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);
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,
));
Upvotes: 5