Using Prepared Statement, how I return the id of the inserted row?

PhpMysqlMysqliPrepared Statement

Php Problem Overview


I want retrieve the id of a inserted row in the database, but I don't know how to do this.

I tried to return using the SQL clause RETURNING id, but not works.

How I can return the id after the insertion of a row?

Php Solutions


Solution 1 - Php

After calling the execute() method on the Prepared Statement, the id of the insert row will be in the insert_id attribute.

$pstm->execute();
$pstm->insert_id;

Solution 2 - Php

$newid = mysqli_insert_id($mysqli_db);

$mysqli_db is your mysqli database connection. As far as I know it shouldn't matter on which way ou inserted the row (prepared statement or direct INSERT INTO). mysqli_insert_id() should return the id of the last inserted row using this db connection.

The alternative is to make another query like SELECT LAST_INSERT_ID();.

Solution 3 - Php

You need to use:

$stmt = $db->prepare("SQL Query");
$stmt->execute();
$id = $db->lastInsertId();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRenato DinhaniView Question on Stackoverflow
Solution 1 - PhpRenato DinhaniView Answer on Stackoverflow
Solution 2 - PhpMarcoView Answer on Stackoverflow
Solution 3 - PhpJrBrionesView Answer on Stackoverflow