我正在使用PDO,我想使用该功能插入,您可以提供自定义对象/类作为isnert的参数。 catch块中不会抛出任何错误。如果我尝试只是原始插入从表中输入字段,那么它可以正常工作。
这是我想要创建实例的自定义类,然后使用PDO
进行插入class User {
public $email;
public $username;
public $fname;
public $sname;
function __construct($e,$u,$fn,$sn) {
$this->email = $e;
$this->username = $u;
$this->fname = $fn;
$this->sname = $sn;
}
}
这是我用来尝试插入
的代码try{
$DBH = new PDO("mysql:host=localhost;dbname=mydb", "myuser", "mypass");
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$user = new User('the email','the username','the fname','the sname');
$STH = $DBH->("INSERT INTO User (email, username, fname, sname) value (:email, :username, :fname, :sname)");
$STH->execute((array)$user);
}
catch(PDOException $e) {
echo $e->getMessage();
}
答案 0 :(得分:1)
您可能希望先绑定值,然后再调用execute。 http://www.php.net//manual/en/pdostatement.bindparam.php
$STH = $DBH->prepare("INSERT INTO User (email, username, fname, sname) value (:email, :username, :fname, :sname)");
$STH->bindParam(':email', $user->email);
// and so on
$STH->execute();