PDO lastInsertId 问题,php

2021-12-26 00:00:00 php pdo lastinsertid

我已经尝试了很多方法来使用下面的代码(来自较大班级的片段)获取最后插入的 ID,现在我已经放弃了.

I have tried lots of ways to get the last inserted ID with the code below (snipplet from larger class) and now I have given up.

有谁知道如何让 PDO lastInsertId 工作?

Does anyone know howto get PDO lastInsertId to work?

提前致谢.

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

推荐答案

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

In your code snippet, I saw some minor inconsistencies that may have an effect on the problem. For an example, in the code to prepare your SQL statement you use,

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

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

Notice the $this keyword. Then to retrieve the ID, you call,

$dbh->lastInsertId();

你有没有试过使用,

$this->dbh->lastInsertId();

相关文章