Example 1 — Get the Id After Insert
Insert one row and print the new AUTO_INCREMENT value. Sample id is fixed.
<?php
$mysqli = mysqli_connect("localhost", "demo_user", "demo_pass", "app_db");
mysqli_query(
$mysqli,
"INSERT INTO users (name, email) VALUES ('Ada', '[email protected]')"
);
echo "New id: ", mysqli_insert_id($mysqli), PHP_EOL;
mysqli_close($mysqli); How It Works
- Run INSERT on a table with an AUTO_INCREMENT primary key.
- Immediately call mysqli_insert_id() on the same link.
- The sample returns 42 as the new id.
- Use that id for related rows in other tables.

