mysqli::$insert_id

mysqli_insert_id

Returns the value generated for an AUTO_INCREMENT column by the last query

&reftitle.description;

&style.oop;

``int``string```mysqli->insert_id`

&style.procedural;

``int``string```mysqli_insert_id` `mysqli` `mysql`

Returns the ID generated by an `INSERT` or `UPDATE` query on a table with a column having the `AUTO_INCREMENT` attribute. In the case of a multiple-row `INSERT` statement, it returns the first automatically generated value that was successfully inserted.

Performing an `INSERT` or `UPDATE` statement using the `LAST_INSERT_ID()` MySQL function will also modify the value returned by `mysqli_insert_id`. If `LAST_INSERT_ID(expr)` was used to generate the value of `AUTO_INCREMENT`, it returns the value of the last `expr` instead of the generated `AUTO_INCREMENT` value.

Returns `0` if the previous statement did not change an `AUTO_INCREMENT` value. `mysqli_insert_id` must be called immediately after the statement that generated the value.

&reftitle.parameters;

&mysqli.link.description;
&reftitle.returnvalues;

The value of the `AUTO_INCREMENT` field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an `AUTO_INCREMENT` value.

Only statements issued using the current connection affect the return value. The value is not affected by statements issued using other connections or clients.

If the number is greater than the maximum int value, it will be returned as a string.

&reftitle.examples;

### `$mysqli->insert_id` example

&style.oop;

    <?php

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $mysqli = new mysqli("localhost", "my_user", "my_password", "world");

    $mysqli->query("CREATE TABLE myCity LIKE City");

    $query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
    $mysqli->query($query);

    printf("New record has ID %d.\n", $mysqli->insert_id);

    /* drop table */
    $mysqli->query("DROP TABLE myCity");

&style.procedural;

    <?php

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $link = mysqli_connect("localhost", "my_user", "my_password", "world");

    mysqli_query($link, "CREATE TABLE myCity LIKE City");

    $query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
    mysqli_query($link, $query);

    printf("New record has ID %d.\n", mysqli_insert_id($link));

    /* drop table */
    mysqli_query($link, "DROP TABLE myCity");

&examples.outputs;

    New record has ID 1.