ActiveRecord with Transaction [solved]

Hi all,

while i am working with activerecord, i keep suffering from this error:

[color="#FF0000"]CDbTransaction is inactive and cannot perform commit or roll back operations.[/color]

my code written is as follows:




$ret=false;

$traffic=new Traffic();

$transaction=$traffic->dbConnection->beginTransaction();

		

try

{

	$traffic->ip=Yii::app()->request->userHostAddress;

	$traffic->flow='out';

	$ret=$traffic->save();

			

	if($ret)

	{

		$usertraffic=new UserTraffic();

		$usertraffic->user_id=Yii::app()->user->getId();

		$usertraffic->traf_id=$traffic->id;

		$ret=$usertraffic->save();

				

		$ret?$transaction->commit():'';

	}

}

catch(Exception $e)

{

	$ret=false;

}

$ret=false;

!$ret?$transaction->rollback():'';




another question i would like to ask is "Is ActiveRecord safe from SQL Injection? Do they use prepare statement?"

thanks in advanced.

cheers.

You are setting $ret to false in the end so the last statement is always executed.

After commiting you cannot rollback.

sorry for confusion, because i would like to test out whether the transaction can be rollback. so at the end i set $ret false.

so you are saying after commit i cannot rollback except that i receive exception?

That’s correct, after a successful commit you can’t rollback (which is quite logical). If you want to test, you should comment out the commit line and put the $ret=false; statement there:


$ret=false;

$traffic=new Traffic();

$transaction=$traffic->dbConnection->beginTransaction();

                

try

{

        $traffic->ip=Yii::app()->request->userHostAddress;

        $traffic->flow='out';

        $ret=$traffic->save();

                        

        if($ret)

        {

                $usertraffic=new UserTraffic();

                $usertraffic->user_id=Yii::app()->user->getId();

                $usertraffic->traf_id=$traffic->id;

                $ret=$usertraffic->save();

                                

                //$ret?$transaction->commit():'';

                $ret=false;

        }

}

catch(Exception $e)

{

        $ret=false;

}

!$ret?$transaction->rollback():'';

thanks all for the doubts. it works now! :P

but my second question is not answered yet. >.<

is active record safe from sql injection? do active record uses prepared statement?

sorry for the trouble.

Yes, as far as PDO::prepare() goes to prevent that.

Just read the source code if you are curious: http://code.google.com/p/yii/source/browse/branches/1.0/framework/db/CDbCommand.php#106

cool! thanks.