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

Joh*_*ohn 6 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);
Run Code Online (Sandbox Code Playgroud)

Flo*_*ine 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);
Run Code Online (Sandbox Code Playgroud)

  • 命名变量很好!你为什么要摆脱它们?除了简单的语句之外,我觉得它们在调试时非常有用,并且如果需要在查询中,还允许您多次使用命名参数. (2认同)