Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO lastInsertId issues, php

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;
like image 783
Kyle Hudson Avatar asked Apr 20 '10 14:04

Kyle Hudson


People also ask

Is PHP PDO deprecated?

PDO (PHP Data Objects) Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.

How check PDO query is successful in PHP?

How check PDO query is successful in PHP? To determine if the PDO::exec method failed (returned FALSE or 0), use the === operator to strictly test the returned value against FALSE.

What is the advantage of PDO in PHP?

Advantage of PDO PDO allows comparatively seamless switching between different databases and platforms, which can be easily done by changing the connection string. It does not support database-specific syntaxes. The PDO extension can access any database which is written for PDO driver.

Does PHP come with PDO?

PDO ships with PHP.


1 Answers

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

like image 111
Anthony Forloney Avatar answered Nov 02 '22 22:11

Anthony Forloney