RE: Transactions - working but unsure about steps

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Stuart, you are calling your rollback function only if $result is false.

This check you are performing at the end of performing your 3 queries, each
of which update $result. The net result here is that you will only call
rollback() if the 3rd query results in false.

I would create another function called maybe run_query() which is something
like:

function run_query($sql)
{
  $result = mysql_query($query);
  if(!$result)
  {
    return false;
  }else{
    return true;
  }
}

then:

begin();
$query = "INSERT INTO firsttable.....//first query
$res1 = run_query($query);
$query = "INSERT INTO secondtable...//second query
$res2 = run_query($query);
$query = "INSERT INTO thirdtable....//third query
$res3 = run_query($query);

if($res1 && $res2 && $res3) // If all results are true
{
  commit();
  echo "your insertions were successful";
}else{
  echo mysql_errno($link)." : ".mysql_error($link)."\n";
  rollback();
  exit;
}

Graham


> -----Original Message-----
> From: Stuart Felenstein [mailto:stuart4m@xxxxxxxxx]
> Sent: 16 October 2004 13:53
> To: php-db@xxxxxxxxxxxxx
> Subject:  Transactions - working but unsure about steps
>
>
> My statements are all working but I'm not sure if
> things are set up correctly.  I say this because at
> one point the first $query failed, yet the rest of
> inserts wre committed.  Now I believe I need to set
> autocommit to 0 , yet the query failed due to a syntax
> error. Hence 0 records effected wouldn't be the case
> here.
> Here is what I have:
>
> //Create these functions -
> function begin()
> {
> mysql_query("BEGIN");
> }
> function commit()
> {
> mysql_query("COMMIT");
> }
> function rollback()
> {
> mysql_query("ROLLBACK");
> }
>
> connection statement with error checking...........
>
> begin(); // transaction begins
> $query = "INSERT INTO firsttable.....//first query
> $result = mysql_query($query); // process first query
> $query = "INSERT INTO secondtable...//second query
> $result = mysql_query($query); // process second query
> $query = "INSERT INTO thirdtable....//third query
> $result = mysql_query($query); // process third query
>
> then:
>
> if(!$result)
> {
> echo mysql_errno($link) . ": " . mysql_error($link).
> "\n";
> rollback(); // transaction rolls back
>
> exit;
> }
> else
> {
> commit(); // transaction is committed
> echo "your insertion was successful";
>
> --
> PHP Database Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

-- 
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux