transactions, concurrency

Hi,

im playing around with Yii, InnoDB and transactions.

I want to make sure that two users can’t submit the same phonenumber twice at the same time. (concurrent users)

I setup a test ajax call to post 2 of the same numbers at the same time.

For some reason its still saving two records in the db. not sure what im doing wrong here. the table is set to use innoDB.

thanks

pete

  1. Check if phonenumber is already in the DB

  2. If not in DB create new record




$transaction = Yii::app()->db->beginTransaction();

	

try {

  //check if phonenumber already exists in DB

  $phoneNumber=Customers::model()->find('phone=?',array($phoneNumber));

			

  if($phoneNumber === null) {

    $customer->mobile_number = $phoneNumber;

    $customer->save();	

  } else {

    echo "already exists";

    Yii::app()->end();

  }


  $transaction->commit();

  $this->renderPartial('success');

}


// Was there an error?

  catch (Exception $e) {

    // Error, rollback transaction

    $transaction->rollback();

}






Transaction doesn’t save you from getting two records in DB. It only allows you to revert all changes you’ve made if there is an error. In your case you need to add unique constraint for mobile_number column.

Is it a possibility to make the ‘phone’ field unique ?

Just one other thing, shouldn’t you select the phonenumber as follows :




 $phoneNumber=Customers::model()->find('phone=:phone',array(':phone'=>$phoneNumber));