The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
See
mysqli_insert_id()
.Whatever you do, don't insert and then do a "
SELECT MAX(id) FROM mytable
". Like you say, it's a race condition and there's no need.mysqli_insert_id()
already has this functionality.Another possible answer will be:
When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.
By this method, you don't have to worry about the id, it'll be made automatically.
For example (taken from w3schools )
Hope this will be helpful for someone.
Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.
I just want to add a small detail concerning
lastInsertId()
;When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.
Consider the following example
What happens here is that I push in
my_table
two new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a differentvarNumb
.The echoed value at the end will be equal to the id of the row where
varNumb=1
, which means not the id of the last row, but the id of the first row that was added in the last request.As @NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.
Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php
An example.
The code line
$course_id = $query_new->insert_id;
will display the ID of the last inserted row. Hope this helps.Try like this you can get the answer:
Have a look at following links:
http://www.w3schools.com/php/func_mysqli_insert_id.asp
http://php.net/manual/en/function.mysql-insert-id.php
Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0