After a successful INSERT on the same connection, insert_id returns the generated AUTO_INCREMENT value.
<?php
$stmt = $connection->prepare('INSERT INTO student (name, class, mark) VALUES (?, ?, ?)');
$name = 'Alex';
$class = 'Three';
$mark = 82;
$stmt->bind_param('ssi', $name, $class, $mark);
$stmt->execute();
echo $connection->insert_id;
?>Current example first; the detailed examples below are retained for additional learning and comparison.
$query = "INSERT INTO student (name, class, mark, gender)
VALUES ('John Doe', 'Three', 85, 'Male')";
if ($connection->query($query) === TRUE) {
echo "Record inserted successfully!";
echo "<br>Insert ID: " . <span class='text-danger'>$connection->insert_id</span>;
} else {
echo "Error: " . $connection->error;
}
Using Procedural style
$query = "INSERT INTO student (name, class, mark, gender)
VALUES ('John Doe', 'Three', 85, 'Male')";
if (mysqli_query($connection, $query)) {
echo "Record inserted successfully!";
echo "<br>Insert ID: " . <span class='text-danger'>mysqli_insert_id($connection)</span>;
} else {
echo "Error: " . mysqli_error($connection);
}
Output
Record inserted successfully!
Insert ID: 38
In MySQL, an auto-increment field is commonly used to generate unique, sequential numbers for a primary key. The value is automatically increased every time a new row is inserted, ensuring that each record has a unique identifier.
CREATE TABLE IF NOT EXISTS `student` (
`id` int(2) NOT NULL AUTO_INCREMENT,
`name` varchar(50) CHARACTER SET utf8 NOT NULL DEFAULT '',
`class` varchar(10) CHARACTER SET utf8 NOT NULL DEFAULT '',
`mark` int(3) NOT NULL DEFAULT '0',
`gender` varchar(6) CHARACTER SET utf8 NOT NULL DEFAULT 'male',
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 <span class='text-danger'>AUTO_INCREMENT=50 </span>;
Once a new record is inserted it will get the id = 50
ALTER TABLE table_name AUTO_INCREMENT = next_value;
For example, if you want to reset the counter to fill the gap after deleting a row, you can specify the next ID.
INSERT INTO student (name, class, mark, gender)
VALUES ('John Doe', 'Three', 85, 'Male')
Here, MySQL will automatically assign the next available ID to the `student` table's primary key.
INSERT INTO student (id,name, class, mark, gender)
VALUES (55,'John Doe', 'Three', 85, 'Male')
Manually setting the ID to 55 will work, and future auto-incremented values will start from 56.ALTER TABLE student AUTO_INCREMENT = 5;
This command will reset the next auto-increment value to 5, reusing IDs after deletions or truncate or adjusting the sequence.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.