I understand the right way to protect a db from SQL injection is by using prepared statements. I would like to understand how prepared statements protect my db.
For starters, are prepared statements the same thing as "parameterised queries"?
As an example, I'm pasting below my code for the insertion of a new user in a user table. Is that secure? How does PDO work to make it secure? Does anything more needs to be done to secure the db from injection?
In 'Class_DB.php':
class DB {
private $dbHost;
private $dbName;
private $dbUser;
private $dbPassword;
function __construct($dbHost, $dbName, $dbUser, $dbPassword) {
$this->dbHost=$dbHost;
$this->dbName=$dbName;
$this->dbUser=$dbUser;
$this->dbPassword=$dbPassword;
}
function createConnexion() {
return new PDO("mysql:host=$this->dbHost;dbName=$this->dbName", $this->dbUser, $this->dbPassword);
}
}
In 'DAO_User.php':
require_once('Class_DB.php');
class DAO_User {
private $dbInstance;
function __construct($dbInstance){
$this->dbInstance=$dbInstance;
}
function createUser($user){
$dbConnection=$this->dbInstance->createConnexion();
$query=$dbConnection->prepare("INSERT INTO users (userName, hashedPassword, userEmail) VALUES (?,?,?)");
$query->bindValue(1, $user->userName);
$query->bindValue(2, $user->hashedPassword);
$query->bindValue(3, $user->userEmail);
$query->execute();
}
}
Thanks,
JDelage
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…