Transactions Programming PHP and MySQL This is nothing new, but I'd post it here because I just served and these are two tools widely used worldwide.
First of all we need servers (php and mysql) pre-installed. Then we need to enable INNODB support in mysql, see this post
.
is important to know that transactions are supported only for innodb type tables, so we need to create or modify tables with this type. This is easily accomplished with the attribute ENGINE = INNODB.
Here is the code to do so.
Create: CREATE TABLE
table ... ENGINE = INNODB;
Edit:
ALTER TABLE table ENGINE = INNODB;
No worries with the data in the amendment because it does not show any changes.
then already in the php code will have something like the following:
$ SERVER = "TuHost"
$ BASE_DATOS = "TuBaseDeDatos"
$ USER = "TuUsuario"
$ PASSWORD = "TuPassword"
$ db = mysql_connect ($ SERVER, $ USER, $ PASSWORD);
mysql_select_db ($ BASE_DATOS, $ db);
$ error = 0, / / \u200b\u200bvariable to detect error
mysql_query ("BEGIN") / / Transaction start
$ result = mysql_query ("INSERT INTO table1 VALUES (1.1000)");
if (! $ Result)
$ error = 1;
$ result = mysql_query ("INSERT INTO table2 VALUES (1.2000)");
if (! $ Result)
$ error = 1;
if ($ error) {
mysql_query ("ROLLBACK");
echo "failed transaction"
} else {mysql_query ("COMMIT");
echo "Transaction successful";}
The code
previous 2 insertions are to be undertaken (COMMIT) if any error occurs in both, otherwise it will return their previous values \u200b\u200b(ROLLBACK).
Well I hope they serve and if you have any questions you know, put comment.