views:

25

answers:

1

I am forking some php scripts and I need to update a mysql row to track some progress. I read that I should use InnoDB for this but I coulnd't find any complete example I can understand. A friend told me he uses this php code:

mysql_query("SET AUTOCOMMIT=0;");
mysql_query("START TRANSACTION;");
mysql_query("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;");

// UPDATE QUERY HERE

mysql_query("COMMIT;");
mysql_query("UNLOCK TABLES;");      
mysql_query("SET AUTOCOMMIT=1;");

He told me he tried other methods but everything else than that code overloaded his server after some time.

Does someone could tell me if this code will do what I need or if there's a better way to do it?

+1  A: 

The database type doesn't matter. MySQL is designed to automatically queue the asynchronous requests and execute them in the order in which they arrive. However, the requests will probably not even be asynchronous, unless you have a lot of them running at once. Either way, you shouldn't have a problem with this, unless your scripts have to update the row in a specific order. In that case, you should use a single script where you can more closely control the updating order.

SimpleCoder
You mean I dont even need to use the code I posted and I can just UPDATE the row from multiple scripts without worrying if they will try to do it at the same time? (I just have to add a column+1 to a row column so no order needed, but I do have to read the column value)
jarkam
Exactly. That's the beauty of MySQL, and most database systems for that matter. You don't have to worry about deadlocks or race conditions. If you are just incrementing a field, you have nothing to worry about.
SimpleCoder
If, across 100 different scripts, you increment the same field at the same (or nearly the same) time, you can be sure that the final value of the field will be 100 more than what it was (after all 100 statements have executed, of course.)
SimpleCoder
Just tested opening 200 "threads" (php scripts) with a 100x loop updating the same row without sleeps and I got 20000 as final value on the row, looks like it works fine, I thought I was going to get errors from trying to update the same row, thanks for clarifying it for me.
jarkam
It's all part and parcel of RDBMS's "ACID": http://en.wikipedia.org/wiki/ACID
Marc B