我仍在学习 PDO,所以我可能会错过一些东西,但基本上我是在尝试向表中插入一行,然后选择生成的 ID。
我不确定它是否喜欢一个 pdo 语句中的两个查询。这是我用来执行 SQL 的代码。
public function ExecuteQuery($sql, $params = array())
{
if($this->_handle == null)
$this->Connect();
$query = $this->_handle->prepare($sql);
foreach($params as $key => $value)
{
if(is_int($value)){
$query->bindValue(':'.$key, $value, \PDO::PARAM_INT);
}else if(is_bool($value)){
$query->bindValue(':'.$key, $value, \PDO::PARAM_BOOL);
}else if(is_null($value)){
$query->bindValue(':'.$key, $value, \PDO::PARAM_NULL);
}else{
$query->bindValue(':'.$key, $value, \PDO::PARAM_STR);
}
}
$query->execute();
$x = $query->fetchAll(\PDO::FETCH_ASSOC);
var_dump($x);
return $x;
}
此函数是数据库类的一部分,$this->_handle 是 PDO 对象。
public function Connect()
{
try {
$this->_handle = new \PDO('mysql:host='.$this->_host.';dbname='.$this->_database, $this->_username, $this->_password);
$this->_handle->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
我正在运行的 SQL 是这样的:
INSERT INTO `users` (`Username`, `Password`, `PasswordSalt`, `Email`, `IsAdmin`, `LoginAttempts`, `LastLogin`, `LastLoginAttempt`, `Created`) VALUES (:username, :password, :passwordsalt, :email, :isadmin, :loginattempts, :lastlogin, :lastloginattempt, :created); SELECT LAST_INSERT_ID() as 'id'
用户已创建并存在于用户表中,但之后出错。
谁能看出哪里做错了? :)
干杯!
最佳答案
我很确定 PDO 的 mysql 驱动程序(也许是 mysql 本身?)不支持多查询准备语句。
不要在查询中使用 SELECT LAST_INSERT_ID()
,而是在 $query->execute() 之后使用
Conexion::$cn->lastInsertId()
关于php - PDO 多查询 "SQLSTATE[HY000]: General error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8094623/