PDO编写的声明,正确使用?

时间:2012-05-06 16:01:15

标签: php pdo

我只是需要确保我已正确获得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);

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

您可以从$data之类的

开始使用空数组
// start with an fresh array for data
$data = array();

// imagine your code here

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

编辑:我错过了你的NOW()电话。 Imho你应该添加一个绑定变量,比如

// 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)");