解析yii数据库的增删查改


Posted in PHP onJune 20, 2013

1. 存取数据库方法
存储第一种
存表时候用到
例子:

$post=new Post;
$post->title='samplepost';
$post->content='content for thesample post';
$post->createTime=time();/$post->createTime=newCDbexpression_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次

存储第二种
存储后我们需要找到这条记录的流水id 这样做 $profile = new profile;$profile->id;

存储第三种
用于更加安全的方法,来绑定变量类型 这样可以在同一个表中存储两个记录

$sql="insert intouser_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 whereid=:id";
$command=profile::model()->dbConnection->createCommand($sql);
$command->bindParam(":id",$userid,PDO::PARAM_INT);
$this->rowflag=$command->execute();
$sql="update profile setpass=: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 = newCDbCriteria;
$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)
{
更新成功后。。。
}

第四种更新和存储应用同一个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();
}

查询
注:当项目没查找到整个对象会为空需要这样判定
if($rows !== null) 当对象不为空
{
returntrue;
}else{
returnfalse;
}
SELECT

读表时候用到
例子:
第一种find()
// find thefirst row satisfying the specified condition
$post=Post::model()->find($condition,$params);
// find the row with postID=10
$post=Post::model()->find('postID=:postID',array(':postID'=>10));
同样的语句,用另种方式表示
$criteria=new CDbCriteria;
$criteria->select='title';// only select the 'title' column
$criteria->condition='postID=:postID';
$criteria->params=array(':postID'=>10);
$post=Post::model()->find($criteria);// $params is not needed

第二种find()
$post=Post::model()->find(array(
'select'=>'title',
'condition'=>'postID=:postID',
'params'=>array(':postID'=>10),
));
// find the row with the specified primarykey
$post=Post::model()->findByPk($postID,$condition,$params);
// find the row with the specified attributevalues
$post=Post::model()->findByAttributes($attributes,$condition,$params);

示例:
第一种findByAttributes()
$checkuser= user_field_data::model()->findByAttributes(
array('user_id' =>Yii::app()->user->user_id, 'field_id'=> $fieldid));
第二种findByAttributes()
$checkuser =user_field_data::model()->findByAttributes(
$attributes = array('user_id'=>Yii::app()->user->user_id, 'field_id'=> $fieldid));
第三种当没有conditions时候,不用params
$user_field_data=user_field_data::model()->findAllByAttributes(
$attributes = array('user_id'=> ':user_id'),
$condition = "field_id in(:fields)",
$params = array(':user_id'=>Yii::app()->user->user_id, ':fields'=> "$rule->dep_fields"));
// find the first row using the specified SQLstatement
$post=Post::model()->findBySql($sql,$params);
例子
user_field_data::model()->findBySql("selectid from user_field_data where user_id = :user_id and field_id =:field_id ", array(':user_id' =>$userid,':field_id'=>$fieldid));
此时回传的是一个对象
第四种 添加其他条件
http://www.yiiframework.com/doc/api/CDbCriteria#limit-detail
$criteria = newCDbCriteria;
$criteria->select='newtime';//选择只显示哪几个字段要与库中名字相同,但是不能COUNT(newtime) as name这样写
$criteria->join = 'LEFT JOINPost ON Post.id=Date.id';//1.先要在relation函数中增加与Post表的关系语句2.Date::model()->with('post')->findAll($criteria)
$criteria->group ='newtime';
$criteria->limit = 2; //都是从0开始,选取几个
$criteria->offset = 2;// 从哪个偏移量开始
print_r(Date::model()->findAll($criteria));
得到行数目或者其他数目 count
// get the number of rows satisfying thespecified condition
$n=Post::model()->count($condition,$params);
// get the number of rows using the specifiedSQL statement
$n=Post::model()->countBySql($sql,$params);
// check if there is at least a row satisfyingthe specified condition
$exists=Post::model()->exists($condition,$params);
UPDATE
例子:
$post=Post::model()->findByPk(10);
$post->title='new posttitle';
$post->save(); // save thechange to database
// update the rows matching the specifiedcondition
Post::model()->updateAll($attributes,$condition,$params);

例子:或者参考上面例子
$c=new CDbCriteria;
$c->condition='something=1';
$c->limit=10;
$a=array('name'=>'NewName');
Post::model()->updateAll($a,$c);
// update the rows matching the specifiedcondition and primary key(s)
Post::model()->updateByPk($pk,$attributes,$condition,$params);

例子
$profile =profile::model()->updateByPk(
Yii::app()->user->user_id,
$attributes = array('pass' =>md5($_POST['password']), 'role' => 1));
// update counter columns in the rowssatisfying the specified conditions
Post::model()->updateCounters($counters,$condition,$params);

DELETE
例子:
$post=Post::model()->findByPk(10);// assuming there is a post whose ID is 10
$post->delete(); // delete therow from the database table
// delete the rows matching the specifiedcondition
Post::model()->deleteAll($condition,$params);
// delete the rows matching the specifiedcondition and primary key(s)
Post::model()->deleteByPk($pk,$condition,$params);
COMPARE

目前可以取出的
1.//$allquestion=field::model()->findAllBySql("selectlabel from field where step_id = :time1 ", array(':time1'=>1));
2. //$criteria=new CDbCriteria;
//$criteria->select='label,options';
//$criteria->condition='step_id=:postID';
//$criteria->params=array(':postID'=>1);
//$allquestion=field::model()->findAll($criteria);
//$allquestion=field::model()->find("",array("label"));
可以与在models文件夹中的 库连接文件relations()函数合用,这样可以联合查询
$criteria=newCDbCriteria;
$criteria->condition='field.step_id=1';
$this->_post=field::model()->with('step')->findAll($criteria);
这样出来的数组里面包含step表中的值,且这个值的条件为step.id=field.step_id
public functionrelations()
{
return array(
'step'=>array(self::BELONGS_TO,'step', 'step_id'),
);
}
PHP 相关文章推荐
Php Ctemplate引擎开发相关内容
Mar 03 PHP
php设计模式之单例、多例设计模式的应用分析
Jun 30 PHP
百度ping方法使用示例 自动ping百度
Jan 26 PHP
带密匙的php加密解密示例分享
Jan 29 PHP
PHP实现算式验证码和汉字验证码实例
Mar 09 PHP
php递归删除指定文件夹的方法小结
Apr 20 PHP
PHP中对数组的一些常用的增、删、插操作函数总结
Nov 27 PHP
php获取访问者浏览页面的浏览器类型
Jan 23 PHP
PHP如何根据文件头检测文件类型实例代码
Oct 14 PHP
PHP基于curl实现模拟微信浏览器打开微信链接的方法示例
Feb 15 PHP
使用PHPWord生成word文档的方法详解
Jun 06 PHP
Laravel 使用查询构造器配合原生sql语句查询的例子
Oct 12 PHP
在yii中新增一个用户验证的方法详解
Jun 20 #PHP
浅析Yii中使用RBAC的完全指南(用户角色权限控制)
Jun 20 #PHP
php中0,null,empty,空,false,字符串关系的详细介绍
Jun 20 #PHP
解析PHP中数组元素升序、降序以及重新排序的函数
Jun 20 #PHP
解析php中的fopen()函数用打开文件模式说明
Jun 20 #PHP
深入解析PHP内存管理之谁动了我的内存
Jun 20 #PHP
解析php中die(),exit(),return的区别
Jun 20 #PHP
You might like
使用dump函数,给php加断点测试
2013/06/25 PHP
PHP生成随机密码类分享
2014/06/25 PHP
php实现扫描二维码根据浏览器类型访问不同下载地址
2014/10/15 PHP
php遍历解析xml字符串的方法
2016/05/05 PHP
thinkPHP订单数字提醒功能的实现方法
2016/12/01 PHP
php数值计算num类简单操作示例
2020/05/15 PHP
jQuery textarea的长度进行验证
2009/05/06 Javascript
键盘 keycode的值 javascript时触发事件时很有用的要素
2009/11/02 Javascript
javascript下判断一个元素是否存在的代码
2010/03/05 Javascript
js隐藏与显示回到顶部按钮及window.onscroll事件应用
2013/01/25 Javascript
js实时获取系统当前时间实例代码
2013/06/28 Javascript
等待指定时间后自动跳转或关闭当前页面的js代码
2013/07/09 Javascript
javascript获取web应用根目录的方法
2014/02/12 Javascript
jQuery .tmpl() 用法示例介绍
2014/08/21 Javascript
js点击列表文字对应该行显示背景颜色的实现代码
2015/08/05 Javascript
Javascript获取数组中的最大值和最小值的方法汇总
2016/01/01 Javascript
JQuery的常用选择器、过滤器、方法全面介绍
2016/05/25 Javascript
js数组操作方法总结(必看篇)
2016/11/22 Javascript
浅谈Node.js:fs文件系统模块
2016/12/08 Javascript
AngularJS指令与控制器之间的交互功能示例
2016/12/14 Javascript
使用AngularJS 跨站请求如何解决jsonp请求问题
2017/01/16 Javascript
jQuery实现别踩白块儿网页版小游戏
2017/01/18 Javascript
解决vue里碰到 $refs 的问题的方法
2017/07/13 Javascript
详解vue-cli项目中用json-sever搭建mock服务器
2017/11/02 Javascript
Angular2使用SVG自定义图表(条形图、折线图)组件示例
2019/05/10 Javascript
vue中keep-alive组件的入门使用教程
2019/06/06 Javascript
layer.msg()去掉默认时间,实现手动关闭的方法
2019/09/12 Javascript
python常见字符串处理函数与用法汇总
2019/10/30 Python
Python持续监听文件变化代码实例
2020/07/22 Python
打印机墨盒:123Inkjets
2017/02/16 全球购物
日本小田急百货官网:Odakyu
2018/07/19 全球购物
导师评语大全
2014/04/26 职场文书
英语系本科生求职信
2014/07/15 职场文书
公证委托书格式
2014/09/13 职场文书
2014年人事行政工作总结
2014/12/03 职场文书
2015年感恩节演讲稿(优选篇)
2015/03/20 职场文书