954,561 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to perform a mysql rollback in php?

Hi,

I have a situation where i am inserting to two tables from a web form but the first table needs to be inserted to so i can get the PK, then use the PK to insert into the second table. So what I would like to do is rollback the insert operation if there is some error inserting to the first table or vice versa.

This is what i'm thinkin of doin so far:

mysql_query("START TRANSACTION");
if(mysql_query($myquery))
  mysql_query("COMMIT");
else
  mysql_query("ROLLBACK");


Any help/ideas/suggestions?

Thanks in advance...

ray_broome
Light Poster
25 posts since Aug 2004
Reputation Points: 10
Solved Threads: 0
 

so pretty much you want to take the insertion uid and use it in the second table.

something like this maybe.

$sql = "SQL HERE";
$query = mysql_query( $sql,$con );
if ( $query ) {
  $iid = mysql_insert_id( $con );
  $sql = "SQL HERE WITH {$iid}";
  $query = mysql_query( $sql );
}
kkeith29
Nearly a Posting Virtuoso
1,357 posts since Jun 2007
Reputation Points: 235
Solved Threads: 194
 

This is how I usually do it:

<?php
$querylog = "TRANSACTION STARTED";
$commit = "commit";
mysql_query("begin", $dbconn);

$query = "insert into ...";
if(!mysql_query($query, $dbconn))
{
	$commit = "rollback";
	$querylog .= "error in query: " . $query . " : " . mysql_error($dbconn) . "";
}

$query = "insert into ...";
if(!mysql_query($query, $dbconn))
{
	$commit = "rollback";
	$querylog .= "error in query: " . $query . " : " . mysql_error($dbconn) . "";
}

$query = "insert into ...";
if(!mysql_query($query, $dbconn))
{
	$commit = "rollback";
	$querylog .= "error in query: " . $query . " : " . mysql_error($dbconn) . "";
}

if($commit == "rollback")
{
	$querylog .= "ERROR IN TRANSACTIONtransaction rolled back";
	//echo $querylog;
}

mysql_query($commit);
?>
R0bb0b
Posting Shark
998 posts since Jun 2008
Reputation Points: 358
Solved Threads: 89
 

cool, thanks for the help guys, r0bb0b's solution seems closer to what i'm trying to do though because it is supposed to be an "all or nothing" situation

ray_broome
Light Poster
25 posts since Aug 2004
Reputation Points: 10
Solved Threads: 0
 

Make sure that your Storage Engine is set to InnoDB.

Attachments InnoDB.jpg 38.49KB
onlysumon
Newbie Poster
1 post since Apr 2011
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You