How does getting mysql's last insert ID work with transactions? + transaction questions How does getting mysql's last insert ID work with transactions? + transaction questions codeigniter codeigniter

How does getting mysql's last insert ID work with transactions? + transaction questions


To answer your first question...

When using transactions, your queries are executed normally as far as your connection is concerned. You can choose to commit, saving those changes, or rollback, reverting all of the changes. Consider the following pseudo-code:

insert into number(Random_number) values (rand()); select Random_number from number where Number_id=Last_insert_id();

//php

if($num < 1)   $this->db->query('rollback;'); // This number is too depressing.else   $this->db->query('commit;'); // This number is just right.

The random number that was generated can be read prior to commit to ensure that it is suitable before saving it for everyone to see (e.g. commit and unlock the row).

If the PDO driver is not working, consider using the mysqli driver. If that is not an option, you can always use the query 'select last_insert_id() as id;' rather than the $this->db->insert_id() function.

To answer your second question, if you are inserting or updating data that other models will be updating or reading, be sure to use transactions. For example, if a column 'Number_remaining' is set to 1 the following problem can occur.

Person A reads 1Person B reads 1Person A wins $1000!Person A updates 1 to be 0Person B wins $1000!Person B updates 0 to be 0

Using transactions in the same situation would yield this result:

Person A starts transaction
Person A reads '1' from Number_remaining
(The row is now locked if select for update is used)
Person B attempts to read Number_remaining - forced to wait
Person A wins $1000
Person A updates 1 to be 0
Person A commits
Person B reads 0
Person B does not win $1000
Person B cries

You may want to read up on transaction isolation levels as well.

Be careful of deadlock, which can occur in this case:

Person A reads row 1 (select ... for update)
Person B reads row 2 (select ... for update)
Person A attempts to read row 2, forced to wait
Person B attempts to read row 1, forced to wait
Person A reaches innodb_lock_wait_timeout (default 50sec) and is disconnected
Person B reads row 1 and continues normally

At the end, since Person B has probably reached PHP's max_execution_time, the current query will finish executing independently of PHP, but no further queries will be received. If this was a transaction with autocommit=0, the query will automatically rollback when the connection to your PHP server is severed.