查询
Yii::app()->db->createCommand($sql)->query()//返回DataReader对象,并返回查询结果集
Yii::app()->db->createCommand($sql)->queryOne()//返回结果集的第一行数据
Yii::app()->db->createCommand($sql)->queryAll();//查询所有行数据
Yii::app()->db->createCommand($sql)->queryRow();//查询第一行数据
Yii::app()->db->createCommand($sql)->queryColumn();//返回结果集每一行的第一列元素
Yii::app()->db->createCommand($sql)->queryScalar();//返回结果集中第一行第一列的值(如成功返回该值,失败则返回false)
执行
Yii::app()->db->createCommand($sql)->execute();//创建、更新、删除,的执行
插入insert
$result =Yii::app()->db->createCommand()->insert('table表名', array(
'column1'=>$value1,
'column2'=>$value2,
'column3'=>$value3,
'create_time'=> time(),
));
获取插入id号:
Yii::app()->db->getLastInsertID()
更新update
$result =Yii::app()->db->createCommand()->update('table表名', array(
'column1'=>$value1,
'column2'=>$value2,
'column3'=>$value3,
'update_time'=> time(),
),
"id=:id",array(':id'=>$id)
);
删除delete
$result =Yii::app()->db->createCommand()->delete('table表名',"id=:id",array(':id'=>$id));
select其他写法
单表查询
$goodsTypes =
Yii::app()->db->createCommand()
->select('type_id, type_name')
->from('goods_type')
->where('status=1')
->queryAll();
#连表查询
goods =
Yii::app()->db->createCommand()
->from('goods g')
->select('g.good_id, g.good_name, gt.type_name, g.price, g.buy_nums, g.commit_nums, g.create_time')
->join('goods_type gt', 'g.good_type=gt.type_id')
->where('g.`status`=1 and gt.`status`=1')
->order('g.create_time desc')
->queryAll();
支持绑定参数
# bindParam(name, &value, dataType=null,length = null, $driverOptions = null)
Yii::$app->db->createCommand("select * from article_status where id=:id")->bindParam(":id",$name)->getRawSql();
# 得到sql语句(注意绑定参数后获取参数不能用getsql()要用getRawSql()函数)
# string(39) "select * from article_status where id=1"
# bindValue(name,value, $dataType = null) 绑定一个参数,直接写值不用变量
Yii::$app->db->createCommand("select * from article_status where id=:id")->bindValue(':id',1)->getRawSql()
# bindValues($values) 绑定一堆参数(用数组形式)
Yii::$app->db->createCommand("select * from article_status where id=:id AND name = :name")->bindValues([':name'=>'ss