I've read the online php manual but I'm still not sure of the way these two functions work: mysqli::commit & mysqli::rollback.
The first thing I have to do is to:
$mysqli->autocommit(FALSE);
Then I make some queries:
$mysqli->query("...");
$mysqli->query("...");
$mysqli->query("...");
Then I commit the transaction consisting of these 3 queries by doing:
$mysqli->commit();
BUT in the unfortunate case in which one of these queries does not work, do all 3 queries get cancelled or do I have to call a rollback myself? I want all 3 queries to be atomic and be considered as only one query. If one query fails then all 3 should fail and have no effect.
I'm asking this because in the comments I've seen on the manual page: http://php.net/manual/en/mysqli.commit.php
the user Lorenzo calls a rollback if one of the queries failed.
What's a rollback good for if the 3 queries are atomic? I don't understand.
EDIT: This is the code example I am doubtful about:
<?php
$all_query_ok=true; // our control variable
$mysqli->autocommit(false);
//we make 4 inserts, the last one generates an error
//if at least one query returns an error we change our control variable
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (200)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (300)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false; //duplicated PRIMARY KEY VALUE
//now let's test our control variable
$all_query_ok ? $mysqli->commit() : $mysqli->rollback();
$mysqli->close();
?>
I think this code is wrong because if any of the queries failed and $all_query_ok==false then you don't need to do a rollback because the transaction was not processed. Am I right?
I think this code is wrong because if any of the queries failed and
$all_query_ok==false then you don't need to do a rollback because the
transaction was not processed. Am I right?
No, the transaction does not keep track if a single SQL-Statement fails.
If a single SQL-Statement fails the statement is rolled back (like it is described in #eggyal's Answer) - but the transaction is still open. If you call commit now, there is no rollback of the successful statements and you just inserted "corrupted" data into your database. You can reproduce this easily:
m> CREATE TABLE transtest (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL DEFAULT '',
CONSTRAINT UNIQUE KEY `uq_transtest_name` (name)) ENGINE=InnoDB;
Query OK, 0 rows affected (0.07 sec)
m> START TRANSACTION;
Query OK, 0 rows affected (0.00 sec)
m> INSERT INTO transtest (name) VALUE ('foo');
Query OK, 1 row affected (0.00 sec)
m> INSERT INTO transtest (name) VALUE ('foo');
ERROR 1062 (23000): Duplicate entry 'foo' for key 'uq_transtest_name'
m> INSERT INTO transtest (name) VALUE ('bar');
Query OK, 1 row affected (0.00 sec)
m> COMMIT;
Query OK, 0 rows affected (0.02 sec)
m> SELECT * FROM transtest;
+----+------+
| id | name |
+----+------+
| 3 | bar |
| 1 | foo |
+----+------+
2 rows in set (0.00 sec)
You see that the insertion of 'foo' and 'bar' were successful although the second SQL-statement failed - you can even see that the AUTO_INCREMENT-value has been increased by the faulty query.
So you have to check the results of each query-call and if one fails, call rollback to undo the otherwise successful queries. So Lorenzo's code in the PHP-manual makes sense.
The only error which forces MySQL to roll back the transaction is a "transaction deadlock" (and this is specific to InnoDB, other storage engines may handle those errors differently).
As documented under InnoDB Error Handling:
Error handling in InnoDB is not always the same as specified in the SQL standard. According to the standard, any error during an SQL statement should cause rollback of that statement. InnoDB sometimes rolls back only part of the statement, or the whole transaction. The following items describe how InnoDB performs error handling:
If you run out of file space in a tablespace, a MySQL Table is full error occurs and InnoDB rolls back the SQL statement.
A transaction deadlock causes InnoDB to roll back the entire transaction. Retry the whole transaction when this happens.
A lock wait timeout causes InnoDB to roll back only the single statement that was waiting for the lock and encountered the timeout. (To have the entire transaction roll back, start the server with the --innodb_rollback_on_timeout option.) Retry the statement if using the current behavior, or the entire transaction if using --innodb_rollback_on_timeout.
Both deadlocks and lock wait timeouts are normal on busy servers and it is necessary for applications to be aware that they may happen and handle them by retrying. You can make them less likely by doing as little work as possible between the first change to data during a transaction and the commit, so the locks are held for the shortest possible time and for the smallest possible number of rows. Sometimes splitting work between different transactions may be practical and helpful.
When a transaction rollback occurs due to a deadlock or lock wait timeout, it cancels the effect of the statements within the transaction. But if the start-transaction statement was START TRANSACTION or BEGIN statement, rollback does not cancel that statement. Further SQL statements become part of the transaction until the occurrence of COMMIT, ROLLBACK, or some SQL statement that causes an implicit commit.
A duplicate-key error rolls back the SQL statement, if you have not specified the IGNORE option in your statement.
A row too long error rolls back the SQL statement.
Other errors are mostly detected by the MySQL layer of code (above the InnoDB storage engine level), and they roll back the corresponding SQL statement. Locks are not released in a rollback of a single SQL statement.
Related
I am using InnoDB in MySQL and accessing the table from PHP with PDO.
I need to lock the table, do a select and then, depending on the result of that either insert a row or not. Since I want to have the table locked for as short a time as possible, can I do it like this?
prepare select
prepare insert
begin transaction
lock table
execute select
if reservation time is available then execute insert
unlock table
commit
Or do the prepares have to be inside the transaction? Or do they have to be after the lock?
Should the transaction only include the insert, or does that make any difference?
beginTransaction turns off autocommit mode, so it only affects queries that actually commit changes. This means that prepared statements, SELECT, and even LOCK TABLES are not affected by transactions at all. In fact, if you're only doing a single INSERT there's no need to even use a transaction; you would only need to use them if you wanted to do multiple write queries atomically.
I need to do 2 query.
Basically it's a
mysql_query("INSERT INTO table ($value1,$value2)");
and
mysql_query("UPDATE table2 SET field1 = '$value1', field2 = '$value2'");
I think I can simply do a
if (mysql_query("INSERT ...") !== false) {
mysql_query("UPDATE ...");
}
In this case should I use a transaction? And how should I use it?
Or can i leave that simple if?
Thanks
You will generally use transactions if you want some "all or nothing" behavior.
Basically, with transactions, you can :
Start a transaction
Do the first query
If it succeeds, do the second query
If it succeed, commit the transaction
Else, rollback the transaction -- cancelling both queries that correspond to that transaction.
If working with mysql_* function, you'll have to :
Start the transaction, with a START TRANSACTION query
Do your queries
Depending on the result of those queries, either do a COMMIT or a ROLLBACK query.
To detect whether a query succeeded or not, you can indeed check the return value of mysql_query() : it will return false in case of an error.
Note : MySQL is the old extension -- and doesn't have functions to deal with transactions ; which means you have to deal with them as regular queries.
Working with MySQLi, you could use :
mysqli::autocommit() to disable autocommit
and mysqli::commit() or mysqli::rollback()
For insert and updates MySQL has a good, alternative solution - "ON DUPLICATE KEY UPDATE". It does what you want safely in a single query:
INSERT .... ON DUPLICATE KEY UPDATE
(also the key must be set as unique in this scenario)
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Is it possible to insert a row into multiple tables at once? If you do several tables related by an ID; what is the best way to ensure integrity is maintained in case an INSERT fails?
That's exactly what transactions are for. If any of the commands fail, the whole thing since START TRANSACTION is rolled back:
START TRANSACTION;
INSERT INTO sometable VALUES(NULL,'foo','bar');
INSERT INTO someothertable VALUES (LAST_INSERT_ID(),'baz');
COMMIT;
This being MySQL, you can't use transactions with MyISAM tables (you'll need the tables to use some engine that supports this, probably InnoDB).
This will never be inserted into the table (normally you'd have some branching, e.g. an IF):
START TRANSACTION;
INSERT INTO sometable VALUES(NULL,'data','somemoredata');
ROLLBACK;
Caveat: SQL commands which change the database structure (e.g. CREATE,ALTER,DROP) cannot be rolled back!
Use transactions, luke.
MySQL can insert multiple rows (search for 'multiple rows') like this:
INSERT INTO table (field1, field2, ...) VALUES (value1, value2), (value3, value4), etc...
However, there's no way to tell what got inserted and what wasn't due to constraint violations, beyond the query returning a count of records, duplicates, and warnings. You also can't use last_insert_id() to figure out the IDs of the new rows, as that only returns the LAST id that was created, not a set of ids.
If you need to guarantee integrity, then use single row insert statements and transactions.
I have made a database wrapper with extra functionality around the PDO system (yes, i know a wrapper around a wrapper, but it is just PDO with some extra functionality). But i have noticed a problem.
The folowing doesn't work like it should be:
<?php
var_dump($db->beginTransaction());
$db->query('
INSERT INTO test
(data) VALUES (?)
;',
array(
'Foo'
)
);
print_r($db->query('
SELECT *
FROM test
;'
)->fetchAll());
var_dump($db->rollBack());
print_r($db->query('
SELECT *
FROM test
;'
)->fetchAll());
?>
The var_dump's shows that the beginTransaction and rollBack functions return true, so no errors.
I expected that the first print_r call show a array of N items and the second call show N-1 items. But that issn't true, they both show same number of items.
My $db->query(< sql >, < values >) call nothing else then $pdo->prepare(< sql >)->execute(< values >) (with extra error handling ofcourse).
So i think or the transaction system of MySQL doesn't work, or PDO's implenmentaties doesn't work or i see something wrong.
Does anybody know what the problem is?
Check if your type of database equals innoDB. In one word you must check if your database supports transactions.
Two possible problems:
The table is MyISAM which doesn't support transaction. Use InnoDB.
Check to make sure auto-commit is OFF.
http://www.php.net/manual/en/pdo.transactions.php
I'm entering this as an answer, as a comment is to small to contain the following:
PDO is just a wrapper around the various lower level database interface libraries. If the low-level library doesn't complain, either will PDO. Since MySQL supports transactions, no transaction operations will return a syntax error or whatever. You can use MyISAM tables within transactions, but any operations done on them will be done as if auto-commit was still active:
mysql> create table myisamtable (x int) engine=myisam;
Query OK, 0 rows affected (0.00 sec)
mysql> create table innodbtable (x int) engine=innodb;
Query OK, 0 rows affected (0.00 sec)
mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)
mysql> insert into myisamtable (x) values (1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into innodbtable (x) values (2);
Query OK, 1 row affected (0.00 sec)
mysql> rollback;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> select * from myisamtable;
+------+
| x |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
mysql> select * from innodbtable;
Empty set (0.00 sec)
mysql>
As you can see, even though a transaction was active, and some actions were performed on the MyISAM table, no errors were thrown.
MySQL doesn't support transactions on the MyISAM table type, which is unfortunately the default table type.
If you need transactions, you should switch to the InnoDB table type.
Another reason this may happen is certain types of SQL statements cause an immediate auto-commit. I had a large script that ran in a transaction that was getting committed immediately and ignored the transaction. I eventually found out it was because any ALTER TABLE statement immediately causes a commit to happen.
Types of statements that cause auto commits are:
Anything that modifies a table or the database, such as ALTER TABLE, CREATE TABLE, etc.
Anything that modifies table permissions, such as ALTER USER or SET PASSWORD
Anything that locks that tables or starts a new transaction
Data loading statements
Administrative statements, such as ANALYZE TABLE, FLUSH, or CACHE INDEX
Replication control statements, such as anything to do with a slave or master
More info and a complete list can be found here: https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html
If you're having this problem only with a specific script and you're sure you're using InnoDB, you might want to look to see if any SQL statements in your script match these.
I have to following code:
http://www.nomorepasting.com/getpaste.php?pasteid=22987
If PHPSESSID is not already in the table the REPLACE INTO query works just fine, however if PHPSESSID exists the call to execute succeeds but sqlstate is set to 'HY000' which isn't very helpful and $_mysqli_session_write->errno and
$_mysqli_session_write->error are both empty and the data column doesn't update.
I am fairly certain that the problem is in my script somewhere, as manually executing the REPLACE INTO from mysql works fine regardless of whether of not the PHPSESSID is in the table.
Why are you trying to doing your prepare in the session open function? I don't believe the write function is called more then once during a session, so preparing it in the open doesn't do much for you, you might as well do that in your session write.
Anyway I believe you need some whitespace after the table name, and before the column list. Without the whitespace I believe mysql would act as if you where trying to call the non-existent function named session().
REPLACE INTO session (phpsessid, data) VALUES(?, ?)
MySQL sees no difference between
'COUNT ()' and 'COUNT()'
Interesting, when I run the below in the mysql CLI I seem to get a different result.
mysql> select count (*);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*)' at line 1
mysql> select count(*);
+----------+
| count(*) |
+----------+
| 1 |
+----------+
1 row in set (0.00 sec)
REPLACE INTO executes 2 queries: first a DELETE then an INSERT INTO.
(So a new auto_increment is "By Design")
I'm also using the REPLACE INTO for my database sessions, but I'm using the MySQLi->query() in combination with MySQLI->real_escape_string() in stead of a MySQLi->prepare()
So as it turns out there are other issues with using REPLACE that I was not aware of:
Bug #10795: REPLACE reallocates new AUTO_INCREMENT (Which according to the comments is not actually a bug but the 'expected' behaviour)
As a result my id field keeps getting incremented so the better solution is to use something along the lines of:
INSERT INTO session(phpsessid, data) VALUES('{$id}', '{$data}')
ON DUPLICATE KEY UPDATE data='{$data}'
This also prevents any foreign key constraints from breaking and potential causing data integrity problems.