6

我只需要确保我已经正确地获得了 PDO 准备语句,以下代码是否会受到 SQL 注入的保护?

$data['username'] = $username;
$data['password'] = $password;
$data['salt'] = $this->generate_salt();
$data['email'] = $email;

$sth = $this->db->prepare("INSERT INTO `user` (username, password, salt, email, created) VALUES (:username, :password, :salt, :email, NOW())");  
$sth->execute($data);
4

2 回答 2

7

是的,您的代码是安全的。但是可以缩短:

$data = array( $username, $password, $this->generate_salt(), $email );

// If you don't want to do anything with the returned value:
$this->db->prepare("
    INSERT INTO `user` (username, password, salt, email, created)
    VALUES (?, ?, ?, ?, NOW())
")->execute($data);
于 2012-05-06T16:09:16.420 回答
1

你可以从一个空数组$data开始

// start with an fresh array for data
$data = array();

// imagine your code here

到目前为止,您的代码看起来不错。

编辑:我错过了你的 NOW() 电话。恕我直言,您也应该使用绑定变量添加它,例如

// bind date
$data['created'] = date("Y-m-d H:i:s");

// updated prepare statement
$sth = $this->db->prepare("INSERT INTO `user` (username, password, salt, email, created) VALUES (:username, :password, :salt, :email, :created)");
于 2012-05-06T16:06:06.460 回答