1 第一种
$post=new Post; $post->title='sample post'; $post->content='content for the sample post'; $post->createTime=time();/$post->createTime=new CDbexpression_r('NOW()'); $post->save(); $user_field_data= new user_field_data; $user_field_data->flag=0; $user_field_data->user_id=$profile->id; $user_field_data->field_id=$_POST['emailhiden']; $user_field_data->value1=$_POST['email']; $user_field_data->save();
注当一个表存储4次的时候,需要创建4个handle new4次
2 第二种
存储后我们需要找到这条记录的流水id 这样做 $profile = new profile; $profile->id;
3 第三种
用于更加安全的方法,来绑定变量类型 这样可以在同一个表中存储两个记录
$sql="insert into user_field_data(user_id,field_id,flag,value1) values(:user_id,:field_id,:flag,:value1);"; $command=user_field_data::model()->dbConnection->createCommand($sql); $command->bindParam(":user_id",$profile->id,PDO::PARAM_INT); $command->bindParam(":field_id",$_POST['firstnamehiden'],PDO::PARAM_INT); $command->bindParam(":flag",$tmpflag,PDO::PARAM_INT); $command->bindParam(":value1",$_POST['firstname'],PDO::PARAM_STR); $command->execute(); $command->bindParam(":user_id",$profile->id,PDO::PARAM_INT); $command->bindParam(":field_id",$_POST['emailhiden'],PDO::PARAM_INT); $command->bindParam(":flag",$tmpflag,PDO::PARAM_INT); $command->bindParam(":value1",$_POST['email'],PDO::PARAM_STR); $rowchange = $command->execute(); if( $rowchange != 0){ 修改成功 }// 用来判断 //注:update delete都可以用这个方法 $sql="delete from profile where id=:id"; $command=profile::model()->dbConnection->createCommand($sql); $command->bindParam(":id",$userid,PDO::PARAM_INT); $this->rowflag=$command->execute(); $sql="update profile set pass=:pass,role=:role where id=:id"; $command=profile::model()->dbConnection->createCommand($sql); $command->bindParam(":pass",$password,PDO::PARAM_STR); $command->bindParam(":role",$role,PDO::PARAM_INT); $command->bindParam(":id",$userid,PDO::PARAM_INT); $this->rowflag=$command->execute(); // 同理变更updateAll()模式 $sql="update user_field_data set flag = :flag where user_id= :user_id and field_id= :field_id "; 原始sql语句 $criteria = new CDbCriteria; $criteria->condition = 'user_id = :user_id and field_id= :field_id'; $criteria->params = array(':user_id' => $userid,':field_id' => $fieldid); $arrupdate = array('flag' => $flag); if(user_field_data::model()->updateAll($arrupdate,$criteria) != 0) { 更新成功后。。。 }
4 第四种
更新和存储应用同一个handle 流程:先查询记录是否存在,若存在就更新,不存在就新创建
注:1. 第一次查询的变量,要跟save()前的变量一致。2. 存储时候需要再次 new一下库对象
$user_field_data = user_field_data::model()->findByAttributes( $attributes = array('user_id' => Yii::app()->user->user_id, 'field_id' => $key)); if ($user_field_data !== null) { $user_field_data->value1 = $value; $user_field_data->save(); } else { $user_field_data = new user_field_data; $user_field_data->user_id = Yii::app()->user->user_id; $user_field_data->field_id = $key; $user_field_data->value1 = $value; $user_field_data->save(); }
近期评论