views:

473

answers:

2

example: making a payment transfer from user A to user B. Account of user A: -10 USD Account of user B: +10 USD

if there is an transaction, and something goes wrong, everything gets undone. So with transactions it will not happen that account of user A gets decreased by 10, while account of user B does not get increased by 10.

I know the java people make use of transactions and rollbacks all over the place. But I've never heard of PHP-guys doing that.

+4  A: 
$db = new mysqli("localhost", "", "", "");
$db->autocommit(FALSE);
if ($db->query("INSERT ..."))
    $db->commit();
else
    $db->rollback();

Make sure your tables use InnoDB engine: MyISAM does not support transactions.

Comment update:

InnoDB is one of two major storage engines used by MySQL, the other one being MyISAM.

MySQL comes with InnoDB support compiled in by default and in fact it takes some effort to disable it.

I've never heard of MySQL with InnoDB disabled even by cheapest of the hosters.

Quassnoi
you would need an own server for innoDB, since no cheap hoster has it, right?
Thanks
A: 

If you use pdo, it also has transaction support

http://us2.php.net/manual/en/pdo.begintransaction.php

like was already said, make sure you use the innoDB storage engine.

Galen
Is that thread-safe? What if 20 users start things at pretty much the same time, so that several threads do stuff like that pretty much the same time?
Thanks
@thanks: I think the most basic example to give is to say that they get queued up. Databases are designed to handle things like this, and 20 users starting transactions at almost-all-at-once should be completely negligible.
anonymous coward