在PHP语言中有许多语法需要我们去不断的熟悉,然后才能灵活的运用,编写我们需要的代码程序。下面为大家介绍PHP中try{}catch{}的用法以及调用函数回滚的用法。
源代码参考:
public function actionDelproperty(){
$rs['status'] = false;
$connection=Yii::app()->db;
try {
$transaction=$connection->beginTransaction();//事物开始
if(isset($_POST['brandhall_id']) && isset($_POST['apartment_id']) && isset($_POST['childCase'])){
$model = BrandhallApartmentRelation::model()->findByPk(array('brandhall_id'=>$_POST['brandhall_id'],'apartment_id'=>$_POST['apartment_id']));
$model->is_del = 1;
$model->save();
$childCase=$_POST['childCase'];
if(!empty($childCase)){
foreach ($childCase as $key=>$val){
$models =BrandhallShowroom::model()->findByAttributes(array('brandhall_id'=>$_POST['brandhall_id'], 'showroom_id'=> intval($val)));
if(!empty($models))
{
$models->is_del= 1;
$models->save();
}
}
}
$rs['status'] = true;
}
$transaction->commit();//事物结束
} catch (Exception $e) {
$transaction->rollback();//回滚函数
$rs['info']=$e->getMessage();//异常信息
}
echo CJSON::encode($rs);
}
PHP中try{}catch{}是异常处理,将要执行的代码放入TRY块中,如果这些代码执行过程中某一条语句发生异常,则程序直接跳转到CATCH块中,由$e收集错误信息和显示.
如上面的图片中try{}catch{}的用法,此外调用了beginTransaction和commit方法分别表示事物的开始和事物的结束,中间执行了对数据库的操作,如果try中出现语句执行异常则直接使用rollback回滚对数据的操作,返回之前数据库没被处理的状态,保证了数据的安全性,这样就达到很严谨的数据操作!![1442376703120448.jpg 1_140604151U24Q[1].jpg](/upload/image/20150916/1442376703120448.jpg)