artlemaks
artlemaks

Reputation: 147

Get last inserted ID in prepared statement

I need to get the last inserted ID for each insert operation and put it into array, I am trying to see what is the correct way of doing it.

Following this post Which is correct way to get last inserted id in mysqli prepared statements procedural style? I have tried to apply it to my code but I am still not getting the right response.

   if($data->edit_flag == 'ADDED')
        {

            $rowdata[0] =   $data->location_name;  
            $rowdata[1] =   0;  
            $rowdata[2] =   $data->store_id;

            $query = "INSERT IGNORE INTO store_locations (location_name,total_items, store_id) VALUES (?,?,?)";

            $statement = $conn->prepare($query);
            $statement->execute($rowdata);
            $id = mysqli_stmt_insert_id($statement);
            echo "inserted id: " . $id;
        }       

I then realised that I am using a PDO connection so obviously mysqli functions wont work. I went ahead and tried the following

$id = $conn->lastInsertId();
echo "insert id: " . $id;

but the response is still empty? What am I doing incorrectly? For the lastInsertId(), should I be using $conn or $statement from here:

$statement = $conn->prepare($query);
$statement->execute($rowdata);

Upvotes: 2

Views: 5885

Answers (2)

Arun Raj
Arun Raj

Reputation: 263

If you are using pdo,

$stmt = $db->prepare("...");
$stmt->execute();
$lastInsId = $db->lastInsertId();

Upvotes: 2

dchao5
dchao5

Reputation: 157

You are using lastInsertId() correctly according to the PDO:lastInsertId() documentation

        $statement = $conn->prepare($query);
        $statement->execute($rowdata);
        $id = $conn->lastInsertId();

Some potential reasons why it is not working:

  1. Is this code within a TRANSACTION? If so, you need to COMMIT the transaction after the execute and before the lastInsertId()
  2. Since you INSERT IGNORE there is the potential that the INSERT statement is generating an error and not inserting a row so lastInsertId() could potentially be empty.

Hope this helps!

Upvotes: 5

Related Questions