-1

Once I add data via PDO, I would like to get the new entry back. I cannot use alias in my SELECT query as it is not unique, and I can't use id as it is an autoincrement index. Is there a PDO way to get the entry back once you run execute() over an INSERT query?

$db_target = new PDO (...);
$stmt = $db_target->prepare("INSERT INTO table (`alias`) VALUES (".$randomString.")");
$stmt->execute();
// how to query for the entry I've just added?

Structure of table:

id (autoincrement) | alias (NOT unique)
alfredopacino
  • 2,563
  • 6
  • 36
  • 61

1 Answers1

2

After you insert you can use lastInsertId()

db_target = new PDO (...);
$stmt = $db_target->prepare("INSERT INTO table (`alias`) VALUES (?)");
$stmt->execute([$randomString]);
$id = $db_target->lastInsertId();

The value is $id will be the auto incrementing primary key.

Bill Karwin
  • 499,602
  • 82
  • 638
  • 795