supercoolville
supercoolville

Reputation: 9096

PDO: Is lastInsertId() a separate query?

If I have this code:

<?php
    $q = $sql->prepare("INSERT INTO `table` (row) VALUES ('1')");
    $q->execute();

    $lastid = $sql->lastInsertId(); // is this a 2nd query?
?>

Would it run as two separate SQL queries?

If so, is there a way to do it in one?

Upvotes: 3

Views: 209

Answers (2)

Bill Karwin
Bill Karwin

Reputation: 562871

No, in fact it doesn't run an SQL query.

Here's the line from ext/pdo_msyql/mysql_driver.c:

char *id = php_pdo_int64_to_str(mysql_insert_id(H->server) TSRMLS_CC);

This is a call to the MySQL API, mysql_insert_id(). This internally accesses the last insert id as a property, not by running SQL.

Upvotes: 3

echo_Me
echo_Me

Reputation: 37253

    $lastid = $sql->lastInsertId();

it works like a query because it will select from database the last inserted id.

as the documentation said

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver.

Upvotes: 3

Related Questions