MySQLi Tutorial: INSERT id, no id — no entry.

Often times when you are working with a database you tend to insert more than one row. This could be because you are signing up a user, adding stats, creating a post in a forum software, or all of the above. There are many times when you want to use the new data row directly after it has been inserted, to do this you usually want the `id` field, or something similar (`user_id`, or other auto-incrementing key). MySQLi makes this very easy using the insert_id property. To get this value you would perform a standard insert, and then call the insert_id via your current MySQLi instance. This example uses the same `people` table as the previous tutorials here. Like so:

/* make your connection */
$sql = new mysqli('localhost','username','password','localhost');
/* we will just create an insert query here, and use it,
normally this would be done by form submission or other means */
$query = "INSERT INTO `people` (`id`,`name`,`age`) VALUES (NULL,'Mitch','25');";
if ( $sql->query($query) ) {
    echo "A new entry has been added with the `id` of {$sql->insert_id}.";
} else {
    echo "There was a problem:<br />$query<br />{$sql->error}";
/* close our connection */

If all goes well you should see: A new entry has been added with the `id` of 5.

Otherwise you may see your query and a detailed error message from MySQL saying what went wrong, you can then use this to solve the issue.

Author: Mike on March 30, 2011
Category: MySQLi, Tutorials
Tags: , ,

Comments are closed.

Last articles