I want to get the last inserted id in MySQL
easiest way is to use $mysqli->insert_id;
My question is is this the best way to do it?
What if another user insert another post at the same and will it give a wrong id?
Appropriate any comments.
If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.
Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.
By definition, atomicity requires that each transaction is an all or nothing. So yes it is atomic in the sense that if the data that you are trying to insert will cause a duplicate in the primary key or in the unique index, the statement will instead perform an update and not error out.
Solution 1. You cannot insert duplicate values in a primary key column. Primary key columns are unique.
This id is related to connection added by $mysqli and is not related to another user
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With