Getting the ID# of the inserted record using PDO with MySQL

Can’t get this to work with lastInsertId(). Tried all combinations I can come up with and haven’t seen any other relevant functions. Is this the method I should be using?

Yes. Can you post your code?

			$sth->bindParam(':addedby', $this->val['addedby'], PDO::PARAM_INT);
		$sth->bindParam(':updateby', $this->val['updateby'], PDO::PARAM_INT);
		
		$sth->execute();
		
		$retval[0] = true;
		$retval[1] = $dbh->lastInsertId();
		return $retval;
	} catch (Exception $e) {
		echo $e->getMessage();
		$msg = $e->procDBError($this->dbh);
		$retval[0] = false;
		$retval[1] = $msg;		
		return $retval;
	}

I have tried PDO::last, PDO->last, and $dbh using both as well and if I try var_dump it returns white space, not ‘null’. The insert command is working just fine

So it appears to be treating it as a code error

Do you have $retval = array(); before the query?

No I never do and have not had issues in the past

Is that the correct format? $dbh->lastInsertId() ? Are you supposed to put the table or field name in as an argument to te method?

The correct way to call “lastInsertId()” is by $connection->lastInsertId();

In the code example you provided we are unable to see what the variable $dbh actually contain.

You are certain that it has not been changed from being the database connection at the point it is used? And that it is accessible in that scope of the code?

That is the first thing I would recommend you to look into.

Edit:
Actually, spotted that you use $this->dbh inside the catch clause. Try changing your code to $this->dbh->lastInsertId(); instead.

1 Like

You just use the Database connection variable, assuming that is $dbh. If you print_r($retval[1]); do you see any value?

That’s it. duh $this->dbh. Let me try that. Thanks

That’s it. Thanks. I would have looked at that for another week because I was convinced it was right. hahahaha

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.