Following is my code in which I am making insertion in two different tables. My question is if due to bad server or bad connection or the like. The insertion to the first table being made but not to the second one. Then does the following code will rollback the insertion being done for the the first table and if not then how that can be done?
Note: My table type in Innodb
$mysqli->autocommit(FALSE);
$stmt_one = $mysqli->prepare("Insert into TABLE SET $var1 = ?, $var2 = ? ");
$stmt_two = $mysqli->prepare("Insert into TABLE SET $var1 = ?, $var2 = ? ");
$stmt_one->bind_param('is',$var1,$var2);
$stmt_two->bind_param('is',$var1,$var2);
$stmt_one->execute();
$stmt_two->execute();
$mysqli->commit();
$stmt_one->close();
$stmt_two->close();
Look at:
try {
$mysqli->autocommit(FALSE);
$stmt_one = $mysqli->prepare("Insert into TABLE SET $var1 = ?, $var2 = ? ");
$stmt_two = $mysqli->prepare("Insert into TABLE SET $var1 = ?, $var2 = ? ");
$stmt_one->bind_param('is',$var1,$var2);
$stmt_two->bind_param('is',$var1,$var2);
$stmt_one->execute();
$stmt_two->execute();
$mysqli->commit();
$stmt_one->close();
$stmt_two->close();
} catch (Exception $e) {
$mysqli->rollBack();
echo "Fallo: " . $e->getMessage();
}
For starting transaction you need turn off auto-committing DB modifications. You do it via $mysqli->autocommit(FALSE);. It means that all queries-changes DB must be "fixed" for "finish" transaction. Its doing via $mysqli->commit();. While you don't calling commit ("fix") - there will be no changes in DB.
In your case ( inserting into 2 tables ): if the insertion to the first table being made but not to the second , will be invoked exception with $mysqli->rollBack();. Since we have not caused сommit transaction (due to exception ), all changes will be roll back to start point (turning off auto-committing), in other words, we do rollback current transaction.
Related
More transaction questions!
What I have right now is a mess of strung-together queries, that are all manually reversed if any fail:
Code Block 1
$stmt1 = $db->prepare(...); // Update table1, set col=col+1
if($stmt1 = $db->execute(...)){
$stmt2 = $db->prepare(...); // Insert into table2, id=12345
if($stmt2 = $db->execute(...)){
$stmt3 = $db->prepare(...); // Select val from table3
if($stmt3 = $db->execute(...)){
$result = $stmt3->fetchAll();
if($result[0]['val'] == something){
$stmt4 = $db->prepare(...); // Update table4, set status=2
if($stmt4 = $db->execute(...)){
return true;
}else{
$stmt1 = $db->prepare(...); // Update table1, set col=col-1 (opposite of above)
$stmt1 = $db->execute(...);
$stmt2 = $db->prepare(...); // Delete from table2, where id=12345 (opposite of above)
$stmt2 = $db->execute(...);
return false;
}
}
return true;
}else{
$stmt1 = $db->prepare(...); // Update table1, set col=col-1 (opposite of above)
$stmt1 = $db->execute(...);
$stmt2 = $db->prepare(...); // Delete from table2, where id=12345 (opposite of above)
$stmt2 = $db->execute(...);
return false;
}
}else{
$stmt1 = $db->prepare(...); // Update table1, set col=col-1 (opposite of above)
$stmt1 = $db->execute(...);
return false;
}
}
It's a mess, difficult to debug, difficult to add on to, difficult to understand when the queries are large, and won't return all tables back to original state if the connection is lost mid-way through.
This same process is even worse when deleting a row, because everything in it needs to be stored - just in case the operation needs to be undone.
Now, I know most of this will still work when I port it over to a single transaction, but the one part I am unsure of is:
Code Block 2
$result = $stmt3->fetchAll();
if($result[0]['val'] == something){
... continue ...
}else{
... reverse operations ...
return false;
}
Because the results-gathering would take place before the commit() in the transaction. As follows:
Code Block 3
$db->beginTransaction();
try{
$stmt1 = $db->prepare(...);
$stmt1->execute();
$stmt2 = $db->prepare(...);
$stmt2->execute();
$stmt3 = $db->prepare(...);
$stmt3->execute();
$result = $stmt3->fetchAll();
if($result[0]['val'] == something){
$stmt4 = $db->prepare(...);
$stmt4->execute();
}else{
$db->rollBack();
return false;
}
$db->commit();
return true;
}catch(Exception $e){
$db->rollBack();
throw $e;
return false;
}
Will this work? Specifically, can I include the $result = $stmt3->fetchAll(); before the commit(), and then execute the conditional query?
Also, I'm not entirely sure on this, but do I require the $db->rollBack(); within the try block, if the code is exited (return false) before the commit()?
Your first question:
Specifically, can I include the $result = $stmt3->fetchAll(); before the commit(), and then execute the conditional query?
I see no reason why it should not work. A transaction behaves basically the same as operations without transactions - except that changes are only drafts. Any changes you make in the previous statements will be applied to a "working copy" valid for this single session only. For you it will appear completely transparent. However any changes will be rolled back if you do not commit them.
Also worth noting (emphasis mine):
In layman's terms, any work carried out in a transaction, even if it is carried out in stages, is guaranteed to be applied to the database safely, and without interference from other connections, when it is committed.
This can cause racing conditions.
Your second question:
Also, I'm not entirely sure on this, but do I require the $db->rollBack(); within the try block, if the code is exited (return false) before the commit()?
From the documentation it says:
When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back.
Therefore you do not necessarily require to roll back manually as it will be done by the driver itself.
However note the following from the same source as well:
Warning PDO only checks for transaction capabilities on driver level. If certain runtime conditions mean that transactions are unavailable, PDO::beginTransaction() will still return TRUE without error if the database server accepts the request to start a transaction.
So be sure to check the compatibility beforehand!
A few notes
Do NOT begin a transaction in another transaction. This will commit the first transaction implicitely. See this comment.
Another note from the documentation:
Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.
Here is my script:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction();
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
$db_conn->commit();
}
catch(PDOException $e){
$db_conn->rollBack();
}
All I want to know, can I use an if statement in the codes which are between beginTransaction() and commit() ? Something like this:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction();
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
if (/* a condition here */){
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
}
$db_conn->commit();
}
catch(PDOException $e){
$db_conn->rollBack();
}
Can I ?
Actually I asked that because here is a sentence which says you can't and doing that is dangerous:
Won't work and is dangerous since you could close your transaction too early with the nested commit().
There is no problem with your transaction structure. The comment on php.net only means, that MySQL does not support nested transactions. In order to your further question, you can query any data (SQL), manipulate data (DML), but not modify any database structures (DDL - data definition language).
/*won't work*/
START TRANSACTION;
/*statement*/
START TRANSACTION; /*nested not supported, auto commit*/
/*statement*/
COMMIT;
/*statement dependend on 1st transaction won't work*/
COMMIT;
See also MySQL ref
Transactions cannot be nested. This is a consequence of the implicit commit performed for any current transaction when you issue a START TRANSACTION statement or one of its synonyms.
You can do everything within a transaction, the only thing you cannot do is nest transactions.
Not the if clause itself is the problem in your linked comment, but the fact there is another beginTransaction / commit pair inside.
I have a script which is containing some queries:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
As you see there is two statements (insert and update). All I'm trying to do is making sure both of them work or none of them.
I mean I want to implement a dependency between those two statements. If updating fails, then inserting shouldn't work and vice versa. How can I do that?
You could use sql transactions
http://www.sqlteam.com/article/introduction-to-transactions
You can use transactions and PDO has an api for this (http://php.net/manual/en/pdo.begintransaction.php),
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction();
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
$db_conn->commit();
}
catch(PDOException $e){
$db_conn->rollBack();
}
As others said, you could use 'transactions'.
Or
you could mannualy check whether the data is right in the database. Just 'select' what you have inserted.
The 'execute' function return 'true' on success or 'false' on failure. You can do something like:
$isDone=$stm1->execute(array($value));
if(!$isDone){
echo 'Operation fails, I will stop.';
return false;
}
I've written this code to ensure that two users can't edit the same row of the same table at the same time. The only problem that I have with it, is that it connects to the database 3 times, once to add a new lock, once to check that it's the only lock for that row and once to either delete the lock or to retrieve the data for the user to edit. I really don't like this, but it was the only way that I could imagine doing it.
Are there any ways of making this more efficient?
<?php
$CountryID = $_GET["CountryID"];
$userID = $_SESSION["userID"];
$currentTime = date('Y-m-d H:i:s');
try{
include_once 'PDO.php';
//Adds a new lock into the database.
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth = $dbh->prepare('INSERT INTO lock (UserID, TableID, RowID) VALUES (?, ?, ?)');
$sth->execute(array($userID,1,$CountryID));
$insertedID = $dbh->lastInsertId();
//Checks to see if there is more than one lock for this table/row. If there is more than 1 row, it will check to make sure that all OTHER rows are older than 5 minutes old incase of broken locks.
$sth = $dbh->prepare('SELECT * from lock where TableID = ? AND RowID = ?');
$sth->execute(array(1,$CountryID));
$rowCount = $sth ->rowCount();
$locked = false;
if ($rowCount >1 ){
foreach($sth as $row){
if ($row['LockID'] != $insertedID AND (abs(strtotime($currentTime) - strtotime($row['Date']))) < 300){
$locked = true;
break;
}
}
}
if ($locked){
//Delete the lock we put in first, and tell the user that someone is already editing that field.
$sth = $dbh->prepare('DELETE from lock where LockID = ?');
$sth->execute(array($insertedID));
echo "Row is currently being edited.";
}else{
//Don't delete the lock, and get data from the country table.
echo "Row isn't being edited.";
$sth = $dbh->prepare('SELECT * from country where CountryID = ?');
$sth->execute(array($CountryID));
}
}catch (PDOException $e){
echo "Something went wrong: " . $e->getMessage();
}
$dbh = null;
?>
It looks like you want a scheme for advisory persistent locking. That is, you want to keep the locks in place for a relatively long time -- longer than a DBMS transaction could reasonably expect to do from a web app. I call it "advisory" because it's not "mandatory" in the sense that the DBMS enforces it.
You are very close. I suggest you define your lock table with a compound primary key (TableID, RowID). That way, attempts to insert duplicate records into that table will fail. Forget about the LockID. You don't need it. UserID is helpful because it will give you a hint at diagnosing trouble.
Then, to set up a lock (in your example on table 1, row $CountryID) you will do your insert like so:
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); /* only once*/
$sth = $dbh->prepare('INSERT INTO lock (UserID, TableID, RowID) VALUES (?, ?, ?)');
$locked = true;
try {
$sth->execute(array($userID,1,$CountryID));
}
catch (PDOException $e) {
$locked = false;
}
This is nice because you'll handle the duplicate-key error (integrity constraint violation) by setting $locked to false. When $locked is false you know somebody else has the lock and you can't have it. It's also nice because it's race-condition-proof. If two users are racing to take the same lock, one of them definitively wins and the other definitively loses.
When you want to release the lock, do the delete in a similar fashion.
$sth = $dbh->prepare('DELETE FROM lock WHERE TableID = ? AND RowID = ?');
$it_was_locked = false;
$sth->execute(array(1,$CountryID));
if ($sth->rowCount() > 0) {
$it_was_locked = true;
}
Here, the variable $it_was_locked lets you know whether the lock was already in place. In any case after you run this command the lock will be cleared.
One more thing. For the integrity of your system, please consider defining a lock timeout. Perhaps it should be ten seconds, and perhaps it should be ten hours: that's up to your application's user-experience needs. The timeout will keep your application from getting all jammed up if people start but don't complete transactions.
Then, put a locktime column into your lock table and automatically put the current time into it. You'd do this with a line like this in your table definition.
locktime TIMESTAMP DEFAULT CURRENT_TIMESTAMP
Then, whenever you insert a lock, first release all locks that have timed out, like so.
$stclean = $dbh->prepare('DELETE FROM lock WHERE locktime < NOW() - 10 SECOND');
$sth = $dbh->prepare('INSERT INTO lock (UserID, TableID, RowID) VALUES (?, ?, ?)');
$locked = true;
$stclean->execute();
if ($stclean->rowCount() > 0) {
/* some timed-out locks were released; make an error log entry or whatever */
}
try {
$sth->execute(array($userID,1,$CountryID));
}
catch (PDOException $e) {
$locked = false;
}
This kind of thing makes for a serviceable locking scheme. When you're doing system test, you can expect to look at this lock table a lot, trying to figure out what module forget to take a lock and what module forgot to release it.
I have the following table:
ID: bigint autoinc
NAME: varchar(255)
DESCRIPTION: text
ENTRYDATE: date
I am trying to insert a row into the table. It executes without error but nothing gets inserted in database.
try {
$query = "INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES(?,?,?)";
$stmt = $conn->prepare($query);
$name= 'something';
$desc = 'something';
$curdate = "CURDATE()";
$stmt->bind_param("sss", $name, $desc, $curdate);
$stmt->execute();
$stmt->close();
$conn->close();
//redirect to success page
}
catch(Exception $e) {
print $e;
}
It runs fine and redirects to success page but nothing can be found inside the table. Why isn't it working?
What about replacing DESCTIPTION with DESCRIPTION inside the $query?
Edit
Just out of curiosity, I created a table called mytable and copy-pasted your code into a PHP script.
Here everything worked fine and rows got inserted, except that the binded parameter CURDATE() did not execute properly and the ENTRYDATE cell was assigned 0000-00-00.
Are you sure you are monitoring the same database and table your script is supposedly inserting to?
What happens when going with error_reporting(E_ALL); ?
Have you verified that the script actually completes the insertion?
The following appears to be working as expected:
error_reporting(E_ALL);
try {
$query = "INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES (?, ?, CURDATE())";
$stmt = $conn->prepare($query);
$name= 'something';
$desc = 'something';
$stmt->bind_param("ss", $name, $desc);
$stmt->execute();
if ($conn->affected_rows < 1) {
throw new Exception('Nothing was inserted!');
}
$stmt->close();
$conn->close();
//redirect to success page
}
catch(Exception $e) {
print $e->getMessage();
}
Are you sure there is no error? There seems to be a typo in your column name for example.
Note that PDO is extremely secretive about errors by default.
See How to squeeze error message out of PDO? on how to fix this.
Try preparing this query instead:
"INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES(?,?,CUR_DATE())"
And check the results of $stmt->execute(). It would have given you a warning that "CUR_DATE()" (sic) is not a valid DATE.
You can check if a statement was correctly executed by checking the return value of execute() and querying the errorInfo() method:
if (!$stmt->execute()) {
throw new Exception($stmt->errorInfo(), stmt->errorCode());
}
Be aware that upon failure, execute() does not throw an exception automagically. You'll have to check for successful operation and failure for yourself.
Is it possible that autocommit is OFF?
If so then you have to commit your insert like so
/* commit transaction */
$conn->commit();
Regards