Yii 1.0 数据库操作 增、删、改、查 、对象转数组
$objectResult=Post::model()->findAll($condition,$params);2、根据主键查询一个集合,可以使用多个主键 findAllByPk
$objectResult=Post::model()->findAll("username=:name",array(":name"=>$username));
$objectResult=RepairItem::model()->findAll("orderno=:orderno and orderpostid=:orderpostid",array(":orderno"=>$orderInfo["orderno"],":orderpostid"=>$orderInfo["orderpostid"]));
$infoArr = NewsList::model()->findAll("status = "1" ORDER BY postid DESC limit 10 ");
$objectResult=Post::model()->findAllByPk($postIDs,$condition,$params);3、根据条件查询一个集合,可以是多个条件,把条件放到数组里面 findAllByAttributes
$objectResult=Post::model()->findAllByPk($postid,"name like :name and age=:age",array(":name"=>$name,"age"=>$age)); $objectResult=Post::model()->findAllByPk(array(1,2));
$objectResult=Post::model()->findAllByAttributes($attributes,$condition,$params);4、根据SQL语句查询一个数组 findAllBySql
$objectResult=Post::model()->findAllByAttributes(array("username"=>"jack"));
$arrResult=Post::model()->findAllBySql($sql,$params);5、根据主键查询出一个对象 eg:findByPk(1);
$arrResult=Post::model()->findAllBySql("select * from tbl_post where username like :name",array(":name"=>"?%"));
$arrResult=Post::model()->findByPk($postID,$condition,$params); $arrResult=Post::model()->findByPk(1);6、根据条件查询出一组数据,【可能是多个,但是他只返回第一行数据】
$arrRow=Post::model()->find($condition,$params); $arrRow=Post::model()->find("username=:name",array(":name"=>"jack"));7、根据条件查询一组数据,【可以是多个条件,把条件放到数组里面,查询的也是第一条数据】
$objectResult=Post::model()->findByAttributes($attributes,$condition,$params); $objectResult=Post::model()->findByAttributes(array("username"=>"objectResult"));8、根据SQL语句查询一组数据,【查询的也是第一条数据】
$objectResult=Post::model()->findBySql($sql,$params); $objectResult=Post::model()->findBySql("select * from objectResult where username=:name",array(":name"=>"objectResult"));9、通过CDbCriteria类find查询出一个对象
$criteria=new CDbCriteria;10、多条件查询的语句
$criteria->select="username";
// 限制显示哪些字段
$criteria->condition="username=:username";
//一个查询条件用aCondition.多条件用addCondition $criteria->params=array(":username=>"jack"");
$criteria->order = "postsort DESC";
$criteria->limit = "3";
$post=Post::model()->find($criteria);
$criteria = new CDbCriteria;二、查询个数,判断查询是否有结果
$criteria->addCondition("postid=1");
//等同于 where postid = 1
$criteria->addInCondition("postid", array(1,2,3,4,5));
//等同于 where postid IN (1,2,3,4,5,);
$criteria->addNotInCondition("postid", array(1,2,3,4,5));
//等同于 NOT IN (1,2,3,4,5,)
$criteria->addCondition("postid=1","OR");
//等同于 OR而非AND
$criteria->addSearchCondition("username", "jack");
//等同于 where name like "%jack%"
$criteria->addBetweenCondition("postid", 1, 4);
// 等同于 between 1 and 4 $criteria->compare("postid", 1);
//根据你的参数自动处理成addCondition或者addInCondition. $criteria->compare("postid", array(1,2,3));
//数组就会调用addInCondition
$criteria->select = "postid,parentid,name";
//限制显示哪些字段
$criteria->join = "xxx";
//连接表 $criteria->with = "xxx";
//调用relations
$criteria->limit = 10;
//取1条数据,如果小于0,则不作处理
$criteria->offset = 1;
//两条合并起来,则表示 limit 10 offset 1,或者代表了。limit 1,10
$criteria->order = "xxx DESC,XXX ASC" ;
//排序条件
$criteria->group = "group 条件";
$criteria->having = "having 条件 ";
$criteria->distinct = FALSE; //是否唯一查询
根据一个条件查询一个集合有多少条记录,返回一个int型数字三、添加的方法
$intCount=Post::model()->count($condition,$params);
$intCount=Post::model()->count("username=:name",array(":name"=>$username));
根据SQL语句查询一个集合有多少条记录,返回一个int型数字
$intCount=Post::model()->countBySql($sql,$params);
$intCount=Post::model()->countBySql("select * from objectResult where username=:name",array(":name"=>"objectResult"));
根据一个条件查询查询得到的数组有没有数据,有数据返回一个true,否则没有找到
$boolExists=Post::model()->exists($condition,$params);
$boolExist=Post::model()->exists("name=:name",array(":name"=>$username));
$objectPost = new Post;四、修改的方法
$objectPost->username = $username;
$objectPost->password = $password;
或许
$objectPost->attributes = $arrNewData;
if($objectPost->save()){
$intPostId= $objectPost->primaryKey;
//生成主键id
echo "添加成功";
}else{
echo "添加失败";
}
Post::model()->updateAll($attributes,$condition,$params);五、删除的方法
$count =Post::model()->updateAll(array("username"=>"11111","password"=>"11111"),"password=:pass",array(":pass"=>"1111a1"));
if($count > 0){
echo "修改成功";
}else{
echo "修改失败";
}
$rt = PostList::model()->updateAll(array("status"=>"1"),"staff_postid=:staff AND host_postid=:host",array(":staff"=>$staff_postid,":host"=>$host_postid)); Post::model()->updateByPk($pk,$attributes,$condition,$params); $count=Post::model()->updateByPk(1,array("username"=>"jack","password"=>"jack"));
$count=Post::model()->updateByPk(array(1,2),array("username"=>"jack1","password"=>"jack1"),"username=:name",array(":name"=>"jack"));
if($count > 0){
echo "修改成功";
}else{
echo "修改失败";
}
Post::model()->updateCounters($counters,$condition,$params); $count=Post::model()->updateCounters(array("status"=>1),"username=:name",array(":name"=>"jack"));
if($count > 0){
echo "修改成功";
}else{
echo "修改失败";
}
//array("status"=>1)代表数据库中的post表根据条件username="jack",查询出的所有结果status字段都自加1
//deleteAll Post::model()->deleteAll($condition,$params);六、执行原生的SQL语句
$count = Post::model()->deleteAll("username=:name and password=:pass",array(":name"=>"jack",":pass"=>"jack"));
$count = Post::model()->deleteAll("postid in("1,2,3")");
//删除postid为这些的数据
if($count>0){
echo "删除成功";
}else{
echo "删除失败";
}
//deleteByPk
Post::model()->deleteByPk($pk,$condition,$params);
$count = Post::model()->deleteByPk(1);
$count =Post::model()->deleteByPk(array(1,2),"username=:name",array(":name"=>"jack"));
if($count>0){
echo "删除成功";
}else{
echo "删除失败";
}
$sql = "select t.*, t1.userphone, t1.truename, t1.usermail from {{member_contact}} t left join {{member}} t1 on t.userid = t1.userid where t.contactid in (1,2,3)";七、事务处理 【多表更新插入操作请使用事务处理】
$arrRows=Yii::app()->db->createCommand($sql)->query();
foreach ($arrRows as $k => $v){ }
$transaction = Yii::app()->db->beginTransaction();
try{
$arrOrderProfile = array(
"orderid"=> $orderId,
"userip"=> $userip,
"contactid" => $contactId,
"updatetime"=> $now
);
$modelOrderProfile = new RepairOrderProfile();
$modelOrderProfile->attributes = $arrOrderProfile;
if(!$modelOrderProfile->save()){
throw new CException("维修订单生成失败,通知事务回滚");
}
$recordCounter = Counter::model()->updateByPk(1,array("max_id"=>$orderId));
if($recordCounter <= 0 )
throw new CException("订单计数器更新失败,通知事务回滚");
$transaction->commit(); //提交事务会真正的执行数据库操作
}catch(Exception $e){
file_put_contents("action.log", $e->getCode().":".$e->getMessage()."--".date("Y-m-d H:i:s",time()),FILE_APPEND); $transaction->rollback();
}
八、对象转换为数组
第二种是使用很简单的方法:/**
* 简化findall数据
* */
function simplifyData($data){
foreach($data as $key=>$val){
$newData[$key] = $val->attributes;
}
return $newData;
}
[html] view plain copy
$products = ProTuan::model()->findAll($criteria);
$products = json_decode(CJSON::encode($products),TRUE);
作用是就先将findAll结果先转成JSON格式,然后再转为数组.
至于findALL转为JOSN格式其实就是使用
CJSON::encode
九、php 事务处理
当在一个应用执行一些查询时, 每次读取 或 写入数据库中的信息, 确保数据库不是只执行了一部分查询, 这一点非常重要.
一个事务处理, 在 Yii 的代表是一个CDbTransaction 实例, may be initiated in this case:
开始事务处理.
逐个执行查询. 任何对数据库的更新对于外部都是不可见的.
提交(Commit)事务. 若事务成功执行, 对数据库的更改变得可见.
若其中一个查询失败, 整个事务被回滚(rolle back).
上面的流程可以使用下面的代码来执行:
$transaction = $connection->beginTransaction ( ) ;
try
{
$connection->createCommand( $sql1 ) ->execute ( ) ;
$connection->createCommand( $sql2 ) ->execute ( ) ;
//.... other SQL executions
$transaction ->commit( ) ;
}
catch ( Exception $e) // an exception is raised if a query fails
{
$transaction ->rollBack( ) ;
}
AR中使用方法:
每个 AR 实例都含有一个属性名叫 dbConnection ,是一个 CDbConnection 的实例,这样我们可以在需要时配合 AR 使用由 Yii DAO 提供的 事务 功能:
$model=Post::model();
$transaction=$model->dbConnection->beginTransaction();
try
{
// 查找和保存是可能由另一个请求干预的两个步骤
// 这样我们使用一个事务以确保其一致性和完整性
$post=$model->findByPk(10);
$post->title="new post title";
$post->save();
$transaction->commit();
}
catch(Exception $e)
{
$transaction->rollBack();
}
注意:上面红色部分其实都是CDbconnection的实例
原文地址:http://hnlixf.iteye.com/blog/1560116
原文地址:http://blog.csdn.net/ajaxchen_615/article/details/6973922
- 上一篇: php----(简1)后台强制用户退出
- 下一篇: php禁止同一账户同时登陆