I really haven't found normal example of PHP file where MySQL transactions are being used. Can you show me simple example of that?
And one more question. I've already done a lot of programming and didn't use transactions. Can I put a PHP function or something in header.php that if one mysql_query fails, then the others fail too?
I think I have figured it out, is it right?:
mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");
$a1 = mysql_query("INSERT INTO rarara (l_id) VALUES('1')");
$a2 = mysql_query("INSERT INTO rarara (l_id) VALUES('2')");
if ($a1 and $a2) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
The idea I generally use when working with transactions looks like this (semi-pseudo-code):
try {
// First of all, let's begin a transaction
$db->beginTransaction();
// A set of queries; if one fails, an exception should be thrown
$db->query('first query');
$db->query('second query');
$db->query('third query');
// If we arrive here, it means that no exception was thrown
// i.e. no query has failed, and we can commit the transaction
$db->commit();
} catch (\Throwable $e) {
// An exception has been thrown
// We must rollback the transaction
$db->rollback();
throw $e; // but the error must be handled anyway
}
Note that, with this idea, if a query fails, an Exception must be thrown:
PDO can do that, depending on how you configure it
See PDO::setAttribute
and PDO::ATTR_ERRMODE and PDO::ERRMODE_EXCEPTION
else, with some other API, you might have to test the result of the function used to execute a query, and throw an exception yourself.
Unfortunately, there is no magic involved. You cannot just put an instruction somewhere and have transactions done automatically: you still have to specific which group of queries must be executed in a transaction.
For example, quite often you'll have a couple of queries before the transaction (before the begin) and another couple of queries after the transaction (after either commit or rollback) and you'll want those queries executed no matter what happened (or not) in the transaction.
I think I have figured it out, is it right?:
mysql_query("START TRANSACTION");
$a1 = mysql_query("INSERT INTO rarara (l_id) VALUES('1')");
$a2 = mysql_query("INSERT INTO rarara (l_id) VALUES('2')");
if ($a1 and $a2) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
<?php
// trans.php
function begin(){
mysql_query("BEGIN");
}
function commit(){
mysql_query("COMMIT");
}
function rollback(){
mysql_query("ROLLBACK");
}
mysql_connect("localhost","Dude1", "SuperSecret") or die(mysql_error());
mysql_select_db("bedrock") or die(mysql_error());
$query = "INSERT INTO employee (ssn,name,phone) values ('123-45-6789','Matt','1-800-555-1212')";
begin(); // transaction begins
$result = mysql_query($query);
if(!$result){
rollback(); // transaction rolls back
echo "transaction rolled back";
exit;
}else{
commit(); // transaction is committed
echo "Database transaction was successful";
}
?>
As this is the first result on google for "php mysql transaction", I thought I'd add an answer that explicitly demonstrates how to do this with mysqli (as the original author wanted examples). Here's a simplified example of transactions with PHP/mysqli:
// let's pretend that a user wants to create a new "group". we will do so
// while at the same time creating a "membership" for the group which
// consists solely of the user themselves (at first). accordingly, the group
// and membership records should be created together, or not at all.
// this sounds like a job for: TRANSACTIONS! (*cue music*)
$group_name = "The Thursday Thumpers";
$member_name = "EleventyOne";
$conn = new mysqli($db_host,$db_user,$db_passwd,$db_name); // error-check this
// note: this is meant for InnoDB tables. won't work with MyISAM tables.
try {
$conn->autocommit(FALSE); // i.e., start transaction
// assume that the TABLE groups has an auto_increment id field
$query = "INSERT INTO groups (name) ";
$query .= "VALUES ('$group_name')";
$result = $conn->query($query);
if ( !$result ) {
$result->free();
throw new Exception($conn->error);
}
$group_id = $conn->insert_id; // last auto_inc id from *this* connection
$query = "INSERT INTO group_membership (group_id,name) ";
$query .= "VALUES ('$group_id','$member_name')";
$result = $conn->query($query);
if ( !$result ) {
$result->free();
throw new Exception($conn->error);
}
// our SQL queries have been successful. commit them
// and go back to non-transaction mode.
$conn->commit();
$conn->autocommit(TRUE); // i.e., end transaction
}
catch ( Exception $e ) {
// before rolling back the transaction, you'd want
// to make sure that the exception was db-related
$conn->rollback();
$conn->autocommit(TRUE); // i.e., end transaction
}
Also, keep in mind that PHP 5.5 has a new method mysqli::begin_transaction. However, this has not been documented yet by the PHP team, and I'm still stuck in PHP 5.3, so I can't comment on it.
Please check which storage engine you are using. If it is MyISAM, then Transaction('COMMIT','ROLLBACK') will not be supported because only the InnoDB storage engine, not MyISAM, supports transactions.
When using PDO connection:
$pdo = new PDO('mysql:host=localhost;dbname=mydb;charset=utf8', $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // this is important
]);
I often use the following code for transaction management:
function transaction(Closure $callback)
{
global $pdo; // let's assume our PDO connection is in a global var
// start the transaction outside of the try block, because
// you don't want to rollback a transaction that failed to start
$pdo->beginTransaction();
try
{
$callback();
$pdo->commit();
}
catch (Exception $e) // it's better to replace this with Throwable on PHP 7+
{
$pdo->rollBack();
throw $e; // we still have to complain about the exception
}
}
Usage example:
transaction(function()
{
global $pdo;
$pdo->query('first query');
$pdo->query('second query');
$pdo->query('third query');
});
This way the transaction-management code is not duplicated across the project. Which is a good thing, because, judging from other PDO-ralated answers in this thread, it's easy to make mistakes in it. The most common ones being forgetting to rethrow the exception and starting the transaction inside the try block.
I made a function to get a vector of queries and do a transaction, maybe someone will find out it useful:
function transaction ($con, $Q){
mysqli_query($con, "START TRANSACTION");
for ($i = 0; $i < count ($Q); $i++){
if (!mysqli_query ($con, $Q[$i])){
echo 'Error! Info: <' . mysqli_error ($con) . '> Query: <' . $Q[$i] . '>';
break;
}
}
if ($i == count ($Q)){
mysqli_query($con, "COMMIT");
return 1;
}
else {
mysqli_query($con, "ROLLBACK");
return 0;
}
}
I had this, but not sure if this is correct. Could try this out also.
mysql_query("START TRANSACTION");
$flag = true;
$query = "INSERT INTO testing (myid) VALUES ('test')";
$query2 = "INSERT INTO testing2 (myid2) VALUES ('test2')";
$result = mysql_query($query) or trigger_error(mysql_error(), E_USER_ERROR);
if (!$result) {
$flag = false;
}
$result = mysql_query($query2) or trigger_error(mysql_error(), E_USER_ERROR);
if (!$result) {
$flag = false;
}
if ($flag) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
Idea from here: http://www.phpknowhow.com/mysql/transactions/
One more procedural style example with mysqli_multi_query, assumes $query is filled with semicolon-separated statements.
mysqli_begin_transaction ($link);
for (mysqli_multi_query ($link, $query);
mysqli_more_results ($link);
mysqli_next_result ($link) );
! mysqli_errno ($link) ?
mysqli_commit ($link) : mysqli_rollback ($link);
Related
Here is my script:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction(); // this
$stm1 = $db_conn->prepare("UPDATE table1 SET col = "updated" WHERE id = ?");
$stm1->execute(array($value));
$done = $stm->rowCount();
if ($done){
try {
$stm2 = $db_conn->prepare("INSERT into table2 (col) VALUES (?)");
$stm2->execute(array($id));
} catch(PDOException $e){
if ((int) $e->getCode() === 23000) { // row is duplicate
$stm3 = $db_conn->prepare("DELETE FROM table2 WHERE col = ?");
$stm3->execute(array($id));
}
}
} else {
$error = true;
}
$db_conn->commit(); // this
}
catch(PDOException $e){
$db_conn->rollBack();
}
First of all, I have to say, my script works. I mean the result or it is as expected in tests. Just one thing scares me. I read the documention and seen this sentence:
Won't work and is dangerous since you could close your transaction too early with the nested commit().
I'm not sure what's the meaning of sentence above, just I understand maybe I shouldn't use nested try - catch between beginTransaction() and commit(). Well I got it right? doing that is dangerous?
Exceptions have no direct relation to transactions. You can add as many catch blocks in your code as you need.
So your code is all right, given you already set PDO error reporting to Exceptions.
What is the best way to validate if a record was inserted successfully?
I'm using PDO Statements.
This:
/*******************
Update user picture
********************/
function updateuserpicture($userid, $filename) {
include ("./businesslogic/dbconnection/cfg.php");
try {
$db = new PDO('mysql:host='.$server.';dbname='.$db,$db_user,$db_password);
$sql = $db->prepare("Update usersdata set userpicture=:filename where userid=:userid");
$sql->bindParam(':filename',$filename);
$sql->bindParam(':userid',$userid);
$sql->execute();
$sqlresult = $sql->rowCount();
$db = null;
return $sqlresult; //Then validate if result is greater than 0.
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
}
}
or this:
/*******************
Update user picture
********************/
function updateuserpicture($userid, $filename) {
include ("./businesslogic/dbconnection/cfg.php");
try {
$db = new PDO('mysql:host='.$server.';dbname='.$db,$db_user,$db_password);
$sql = $db->prepare("Update usersdata set userpicture=:filename where userid=:userid");
$sql->bindParam(':filename',$filename);
$sql->bindParam(':userid',$userid);
if ($sql->execute()) {
$db = null;
return TRUE;
} else {
$db = null;
return FALSE;
} //Then validate if result is TRUE or FALSE.
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
}
}
Both ways works fine but im not sure what is the best, can you please help me?
PDO won't actually throw exceptions unless you tell it to. So your try..catch is entirely superfluous and will never do anything.
If the statement was executed without error, that means the data was inserted/updated successfully. No need to count rows, unless you are interested in the specific details of how many rows were altered (which is a different topic than "is the data in my database now?").
Given this, I'd recommend to set PDO to throw exceptions in case of errors and not do any further explicit checking:
$db = new PDO("mysql:host=$server;dbname=$db", $db_user, $db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $db->prepare('UPDATE users SET userpicture = :filename WHERE userid = :userid');
$sql->bindParam(':filename', $filename);
$sql->bindParam(':userid', $userid);
$sql->execute();
This may still mean that the statement did nothing if the user id didn't exist. This would point to a deeper bug in your app, it's questionable if the PDO code should care about it specifically.
Currently I am developing a system in which at a point I have to fire 100 inter dependent queries like,
In my script (Currently doing),
$query1 = mysql_query("INSERT_QUERY_STRING");
if(!$query) {
die('error'.mysql_error());
}
//this loop can be turn more than 100 times
while(CONDITION) {
//query generated here
$query2 = mysql_query("UPDATE_QUERY_STRING");
$query3 = mysql_query("UPDATE_QUERY_STRING");
$query4 = mysql_query("UPDATE_QUERY_STRING");
$query5 = mysql_query("UPDATE_QUERY_STRING");
if(!$query2 || !$query3 || !$query4 || !$query5) {
die('error '.mysql_error());
}
}
$query6 = mysql_query("UPDATE_QUERY_STRING");
if(!$query6) {
die('error '.mysql_error());
}
Ignore syntax error, it's just a logic
The problem is, since all the queries are depended on each other, if one fails then all the changes occurred before should be revoked. I know one solution of using MYSQL TRANSACTION, COMMIT AND ROLLBACK. Here's what I figured out (planning to do this),
$processes = array();
$processes[] = "INSERT_QUERY_STRING"; //query1
//this loop can be turn more than 100 times
while(CONDITION) {
//query generated here
$processes[] = "UPDATE_QUERY_STRING"; //looping queries
}
$processes[] = "UPDATE_QUERY_STRING" //last query
mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");
$error = false;
for($i=0;$i < count($processes) ; $i++)
{
$q = mysql_query($processes[$i]);
if(!$q) {
$error = true;
break;
}
}
if($error == false) {
mysql_query("COMMIT");
}
else {
mysql_query("ROLLBACK");
}
Is my solution good / best ? Is there any other possible solution do same stuff more quickly and effectively ? Thanks.
I think that will be better use try/catch in tour code:
$processes = array();
$processes[] = "INSERT_QUERY_STRING"; //query1
//this loop can be turn more than 100 times
while(CONDITION) {
//query generated here
$processes[] = "UPDATE_QUERY_STRING"; //looping queries
}
$processes[] = "UPDATE_QUERY_STRING"; //last query
mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");
$count_processes = count($processes);
for($i=0; $i < $count_processes; $i++)
{
try {
$q = mysql_query($processes[$i]);
if (!$q) throw new Exception(mysql_error());
}
catch (Exception $e) {
mysql_query("ROLLBACK");
break;
}
}
mysql_query("COMMIT");
mysql_query("SET AUTOCOMMIT=1");
Use try/catch is better because you have control over the code and error :)
Transactions are definitely the best way to go here. I'd put insert queries in try-catch statement to cover the unpredictable cases and use foreach for traversing $processes
I am trying to set up my first transaction in MySQL using PHP/PDO...
I just have a quick question, what is the best way to determine if the previous query was successful or not? Here is what I have right now, but I would rather find a way to test the query with an if statement.
This is pretty much mock up code to try to get a working model.. I know $results isn't effectively testing if anything was good or bad.. i have it there more as a place holder for the real deal when the time comes..
if ($_POST['groupID'] && is_numeric($_POST['groupID'])) {
$sql = "SET AUTOCOMMIT=0";
$dbs = $dbo->prepare($sql);
$dbs->execute();
$sql = "START TRANSACTION";
$dbs = $dbo->prepare($sql);
$dbs->execute();
$sql = "DELETE FROM users_priveleges WHERE GroupID=:groupID";
$dbs = $dbo->prepare($sql);
$dbs->bindParam(":groupID", $_POST['groupID'], PDO::PARAM_INT);
$dbs->execute();
try {
$sql = "DELETE FROM groups WHERE GroupID=:groupID LIMIT 1";
$dbs = $dbo->prepare($sql);
$dbs->bindParam(":groupID", $_POST['groupID'], PDO::PARAM_INT);
$dbs->execute();
$results["error"] = null;
$results["success"] = true;
try {
$sql = "DELETE FROM users WHERE Group=:groupID";
$dbs = $dbo->prepare($sql);
$dbs->bindParam(":groupID", $_POST['groupID'], PDO::PARAM_INT);
$dbs->execute();
$results["error"] = null;
$results["success"] = true;
$sql = "COMMIT";
$dbs = $dbo->prepare($sql);
$dbs->execute();
}
catch (PDOException $e) {
$sql = "ROLLBACK";
$dbs = $dbo->prepare($sql);
$dbs->execute();
$results["error"] = "Could not delete associated users! $e";
$results["success"] = false;
}
}
catch (PDOException $e)
{
$sql = "ROLLBACK";
$dbs = $dbo->prepare($sql);
$dbs->execute();
$results["error"] = "COULD NOT REMOVE GROUP! $e";
$results["success"] = false;
}
}
Some general notes:
Don't use bindParam() unless you use a procedure that modifies the parameter's value
Therefore, use bindValue(). bindParam() accepts argument value as a referenced variable. That means you can't do $stmt->bindParam(':num', 1, PDO::PARAM_INT); - it raises an error.
Also, PDO has its own functions for controlling transactions, you don't need to execute queries manually.
I rewrote your code slightly to shed some light on how PDO can be used:
if($_POST['groupID'] && is_numeric($_POST['groupID']))
{
// List the SQL strings that you want to use
$sql['privileges'] = "DELETE FROM users_priveleges WHERE GroupID=:groupID";
$sql['groups'] = "DELETE FROM groups WHERE GroupID=:groupID"; // You don't need LIMIT 1, GroupID should be unique (primary) so it's controlled by the DB
$sql['users'] = "DELETE FROM users WHERE Group=:groupID";
// Start the transaction. PDO turns autocommit mode off depending on the driver, you don't need to implicitly say you want it off
$pdo->beginTransaction();
try
{
// Prepare the statements
foreach($sql as $stmt_name => &$sql_command)
{
$stmt[$stmt_name] = $pdo->prepare($sql_command);
}
// Delete the privileges
$stmt['privileges']->bindValue(':groupID', $_POST['groupID'], PDO::PARAM_INT);
$stmt['privileges']->execute();
// Delete the group
$stmt['groups']->bindValue(":groupID", $_POST['groupID'], PDO::PARAM_INT);
$stmt['groups']->execute();
// Delete the user
$stmt['users']->bindParam(":groupID", $_POST['groupID'], PDO::PARAM_INT);
$stmt['users']->execute();
$pdo->commit();
}
catch(PDOException $e)
{
$pdo->rollBack();
// Report errors
}
}
I wouldn't prepare & execute the transaction statements. I'd use PDO::beginTransaction() , PDO::commit(), and PDO::rollback().
PDO::prepare() and PDO::execute() return FALSE if there's an error, or else they throw PDOException if you setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION).
In your exception handler, you should check PDO::errorInfo() and report the nature of the error. Best practice is to log the raw error info, but give the user a more friendly message.
Don't echo the literal error message in the UI -- this can give the user inappropriate knowledge about your SQL query and schema.
PDO Statement's execute() returns TRUE on success and FALSE on failure, so you can test the return value of the previous execute() in your if statement.
$pdo_result = $dbs->execute();
if ($pdo_result) {
// handle success
} else {
// handle failure
// you can get error info with $dbs->errorInfo();
}
That said, as #Bill Kerwin correctly points out (in his answer that I'm totally upvoting because it's exactly correct), it would be preferable to use PDO::beginTransaction(), PDO::commit(), and PDO::rollback().
Can somebody help me in converting the following code written using if-else to try/catch. Also let me know is trycatch needed in this case or if-else is apt
$results = mysql_query($query);
if(mysql_num_rows($results)!=0)
{
while(($result = mysql_fetch_row($results))!=FALSE)
{
$res ="DELETE FROM table1 WHERE id ='".$result['id']."'";
if(mysql_query($res)==false)
{
echo mysql_error();
exit;
}
}
echo $res ="DELETE FROM table2 WHERE id ='".$id."'";
if(mysql_query($res)!==false)
{
header("Location:list.php?m=4");
}
else
{
echo mysql_error();
exit;
}
}
else
{
echo "Error";
}
try...catch only makes any sense if your functions are throwing exceptions. If they don't, there's nothing to catch. I'd start with this as a refactoring:
$results = mysql_query($query);
if (!mysql_num_rows($results)) {
echo 'No results!';
exit;
}
$ids = array();
while (($result = mysql_fetch_row($results)) !== false) {
$ids[] = $result['id'];
}
$ids = array_map('mysql_real_escape_string', $ids);
$query = "DELETE FROM table1 WHERE id IN ('" . join("','", $ids) . "')";
if (!mysql_query($query)) {
echo mysql_error();
exit;
}
$query = "DELETE FROM table2 WHERE id = '$id'";
if (!mysql_query($query)) {
echo mysql_error();
exit;
}
header("Location: list.php?m=4");
exit;
This can still be improved a lot, but it's already an improvement over your spaghetti logic. If you're seriously interested in properly using exceptions, you should first move on to properly using functions for repetitive tasks (like the error, exit parts), then possibly restructure the whole thing into classes and objects, and lastly use exceptions to communicate between the now nested layers. Maybe start using a PHP framework to get a feeling for the whole thing.
Putting exceptions into the above code would be hardly more than a goto, but just for illustrative purposes:
try {
$results = mysql_query($query);
if (!mysql_num_rows($results)) {
throw new Exception('No results!');
}
$ids = array();
while (($result = mysql_fetch_row($results)) !== false) {
$ids[] = $result['id'];
}
$ids = array_map('mysql_real_escape_string', $ids);
$query = "DELETE FROM table1 WHERE id IN ('" . join("','", $ids) . "')";
if (!mysql_query($query)) {
throw new Exception(mysql_error());
}
$query = "DELETE FROM table2 WHERE id = '$id'";
if (!mysql_query($query)) {
throw new Exception(mysql_error());
}
header("Location: list.php?m=4");
exit;
} catch (Exception $e) {
echo 'ERROR: ' . $e->getMessage();
exit;
}
from the sound of it, it seems you think try/catch and if-else as the same behaviour. That is not the case. Try catch is used to prevent an exception from making the application crash or to handle exceptions gracefully, and to perform logging and giving user feedback. If-else (else if) is used to check the internal state of your application, and perform different actions accordingly.
Generally, a try-catch is less efficient than if there is a switch-case or else-if approach to the problem.