-1

I want to add a user to the database. Every user has an unique ID that is automatic created(A_I). If I add an user I want to get this ID. I'm trying to do this with "insert_id", but if I do this I get an error.

$sth=Connection()->prepare ("INSERT INTO Users (Username, Password) VALUES(:Username, :Password)");
$sth->BindValue(":Username", $username, PDO::PARAM_STR);
$sth->BindValue(":Password", $password, PDO::PARAM_STR);
$sth->execute();
$ID = $sth->insert_id;

Can anyone tell me what I'm doing wrong?

Wouter
  • 13
  • 2
  • Duplicated question http://stackoverflow.com/questions/6556720/using-php-mysqli-and-prepared-statement-how-i-return-the-id-of-the-inserted-ro – BillyBigPotatoes Feb 19 '14 at 18:51

1 Answers1

3

You are using PDO not mysqli. You need to use PDO::lastInsertId(). Like this:

$con = Connection();
$sth= $con->prepare ("INSERT INTO Users (Username, Password) VALUES(:Username, :Password)");
$sth->BindValue(":Username", $username, PDO::PARAM_STR);
$sth->BindValue(":Password", $password, PDO::PARAM_STR);
$sth->execute();
$ID = $con->lastInsertId();
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
Krish R
  • 22,583
  • 7
  • 50
  • 59
  • Thanks for the fast response. If I do this it still comes with an error: Fatal error: Call to undefined method PDOStatement::lastInsertId() – Wouter Feb 19 '14 at 18:55