PDO的lastInsertId问题,php

7

我尝试了很多方法来获取以下代码中(从较大的类中剪切出来)最后插入的ID,但是现在我已经放弃了。

有人知道如何使PDO lastInsertId起作用吗?

先感谢您的帮助。

    $sql = "INSERT INTO auth (surname, forename, email, mobile, mobilepin, actlink, regdate) VALUES (:surname, :forename, :email, :mobile, :mobpin, :actlink, NOW())";
$stmt = $this->dbh->prepare($sql);
if(!$stmt) {
 return "st";
}

$stmt->bindParam(':surname', $this->surname);
$stmt->bindParam(':forename', $this->forename);
$stmt->bindParam(':email', $this->email);
$stmt->bindParam(':mobile', $this->mobile);
$stmt->bindParam(':mobpin', $this->mobilePin);
$stmt->bindParam(':actlink', $this->actlink);

$result = $stmt->execute();
//return var_dump($result);
$arr = array();
$arr = $stmt->errorInfo();
$_SESSION['record'] = 'OK' . $dbh->lastInsertId();
$arr .= $_SESSION['record'];
return $arr;

你能否提及它为什么不工作?仅仅说“它不工作”会让其他人猜测问题所在。更多的信息会带来更多的答案。 - Anthony Forloney
1个回答

12

在您的代码片段中,我看到了一些小的不一致之处,可能会影响问题的解决。例如,在准备 SQL 语句的代码中,您使用了:

$stmt = $this->dbh->prepare($sql); 

注意$this关键字。要检索ID,您需要调用以下代码:

$dbh->lastInsertId();

你尝试过使用:

$this->dbh->lastInsertId();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接