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;
4

1 回答 1

12

在您的代码片段中,我看到了一些可能对问题产生影响的细微不一致。例如,在准备您使用的 SQL 语句的代码中,

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

注意$this关键字。然后要检索 ID,您调用,

$dbh->lastInsertId();

您是否尝试过使用,

$this->dbh->lastInsertId();

于 2010-04-20T14:12:10.610 回答