Hoytman
Hoytman

Reputation: 1812

is mysqli_insert_id reliable?

I am building a log-in system which uses three tables in a mysql database (PHP) called users, sessions and log-ins. All tables have an auto-increment index. After a successful log-in happens, the user row is linked to a session row via the values stored in a new log-in row. I am wondering if mysqli_insert_id() is safe to use in this process. I am worried that if there is an error during the session row INSERT, the log-in row will receive an incorrect session index number and the user will get logged into the wrong session.

is this going to be a problem? If so, is there a good way to handle it?

Upvotes: 1

Views: 406

Answers (3)

Devner
Devner

Reputation: 7255

If you want to ensure the integrity of your data & the operations that you perform, then I suggest you go with the "All or None" approach. This means that all your queries will pass individually or they will all fail, even if one fails. You can implement this using TRANSACTION & ROLLBACK features in MySQL. For more info, you may visit: http://www.tutorialspoint.com/sql/sql-transactions.htm

Upvotes: 0

tadman
tadman

Reputation: 211610

That method will produce reliable results if:

  • The last INSERT operation succeeded.
  • The result is checked immediately after the INSERT succeeded on the same database connection.

Most of the time it will be sufficient to call INSERT and then fetch the ID of what was inserted as the next operation so long as you're using the same database handle.

A framework will do all of this for you automatically, so it's usually not something you should be concerned with.

Upvotes: 2

Mohamed Melouk
Mohamed Melouk

Reputation: 192

it's better if you use triggers

trigger will do a query when you trigger another

see this tutorial

Upvotes: -1

Related Questions