views:

83

answers:

2

my problem is , i have a database design from this link http://stackoverflow.com/questions/3305825/is-my-database-overdesigned

edit* ok maybe useing transaction ? but where should i put the rollback if it fails ?

 $dbConnect->beginTransaction();
 $RegisterInsert = $dbConnect->prepare("INSERT INTO companies (
    `name`, `address`, `email`, `phone`, `link`, `verified`) VALUES (
    :name, :address, :email, :phone, :link, :verified)");
    $RegisterInsert->execute($RegisterData);

    $RegisterData2['CID'] = $dbConnect->lastInsertId();  

    $RegisterInsert = $dbConnect->prepare("INSERT INTO users_companies (
    `UID`, `CID`, `role`) VALUES (
    :UID, :CID, :role)");
    $RegisterInsert->execute($RegisterData2);
    $dbConnect->commit();

where should i put the rollback ?

Thanks

+1  A: 

A transaction should end with either a rollback() or a commit(), (only one of them)

Its usually used with an if...else statement as logically only one of them should be executed.

$dbConnect->beginTransaction();

//somecode
//$dbConnect->execute( $someInsert );
//some more code
//$result = $dbConnect->execute( $someSelect );
//$nextRow = $result->fetchRow();

//either commit or rollback!
if( $someResultCheck == true )
    $dbConnect->commit();
else
    $dbConnect->rollback();

Transactions are usually used when there is a complex logic involved with queries.

In case you are using MySQL, make sure you are not using MyISAM engine for tables, as it doesn't support transactions.

Kalyan
so my code above auto rollback if it fails ?
kaskus
Your code isn't guaranteed to automatically rollback unless autoCommit is set to false
Mark Baker
ok so were we should do an $someResultCheck ?, on RegisterInsert ? am i right ?
kaskus
@kaskus : Right. You only want to commit when both the inserts are successfully executed.So you will have to do `$someResultCheck = $RegisterInsert->execute($stmt);`.
Kalyan
@mark : autoCommit only matters for statements outside a transaction, where individual statements are wrapped inside a transaction. When you manually begin a transaction, it doesn't apply inside that.
Kalyan
@Kalyan - Thanks for the clarification. As I said elsewhere, I always code explicit transaction starts and commits/rollbacks because there'll never be any misunderstandings then with other developers reading the code
Mark Baker
+1  A: 

As soon as you know that the transaction as a whole is going to fail then you should rollback what you've done so far and not try any further updates - so in pseudo-code:

 function do_updates(array updates)
 { 
    PDO->beginTransaction();
    foreach (updates as statement) {
       run statement
       if failed {
         PDO->rollback(); 
         return false;
       }
    }
    return PDO->commit();

HTH

C.

symcbean