I’m having troubles using transactions. I want to use transactions for saving all or none record to the database but if one model can be saved and the other fails then the successful model stays in database. It seems no rollback is done.
Here is an example causing the error:
$model1 = new User();
$model1->username = "user1@localhost.com";
$model2 = new User();
$model2->username = NULL;
$transaction = Yii::app()->db->beginTransaction();
try{
if(!$model1->save()){ // can be saved normally
throw new CHttpException(null, "model1 could not be saved");
}
if(!$model2->save()){ //should fail on validation and rollback transaction
throw new CHttpException(null, "model2 could not be saved");
}
$transaction->commit();
}
catch(Exception $e){
$transaction->rollBack();
throw new CHttpException(null,"catch transaction, ".$e->getMessage());
}
Also, this page suggests that it might be possible for the MySQL installation to become corrupt in some way. Reinstalling MySQL might fix your problem.
Thanks for your hints Keith but I still could not identify the problem. I read about your first post and tried the example from the second post… I tried to query the database directly in phpmyadmin and it worked. I used exactly the same example given in the second post and it worked. So there must be something wrong in the way the transaction is done from the application side. Do you have another hint what could be the problem there?
Hi Maurizio. What do you mean with using this db connection? The table I’m creating records in is located in this database I’m using for my transaction. Or is it possible that something is wrong with my connection?
So my idea was that you are starting the stransaction on "db" but the model uses another connection like "db1"… but from your answer I guess this is not the problem here…