【发布时间】:2011-12-27 00:49:45
【问题描述】:
我还在学习 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'
用户已创建并存在于 users 表中,但之后出现错误。
谁能看到做错了什么? :)
干杯!
【问题讨论】: