PDO lastInsertId issues, php
Asked Answered
K

1

7

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.

Does anyone know howto get PDO lastInsertId to work?

Thanks in advance.

    $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;
Keats answered 20/4, 2010 at 14:8 Comment(1)
Could you also mention how it is not working? By just saying, it doesn't work leads other people to assume what the problem may be. With more information come more answers.Cambria
C
12

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

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

$dbh->lastInsertId();

Have you tried using,

$this->dbh->lastInsertId();

Cambria answered 20/4, 2010 at 14:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.