$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: " . $connection->insert_id;
} 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: " . mysqli_insert_id($connection);
} 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 AUTO_INCREMENT=50 ;
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.