//获取DB连接
$connection = Yii::app()->db();
//创建新连接
//$connection = new CDbConnection($dns, $username, $password);
//绑定SQL语句
$command = $connection->createCommand('select * from `tbl_user`');
//执行
$data = $command->queryAll() ; //执行一个SQL查询
/* $data = $command->execute(); //执行无查询SQL
$data = $command->query(); //执行一个SQL查询
$data = $command->quereyAll(); //查询并返回结果中的所有行
$data = $command->queryRow(); //查询并返回结果中的第一行
$data = $command->queryColumn(); //查询并返回结果中的第一列
$data = $command->queryScalar(); //查询并返回结果中第一行的第一个字段
*/
/*表前缀设置*/
//设置后写法
$command = $connection->createCommand('select * from {{user}}');
//即表名用{{表名}}代替
/*关联查询*/
$data = Yii::app()->db()->createCommand()
->select('u.id as a, p.user')
->from('tbl_user u')
->join('tbl_user2 p', 'u.id = p.id')
->where('u.id<:id', array(':id'=>3))
->queryAll();
//ORM(对象关系模型)
//以User模型为例
//增加数据:
$user = new User();
$user->username = 'test';
$user->password = '123';
$user->email = 'aaa@dddaa.com';
$user-save();
//查询数据
//查询一条数据
$data = User::model()->find('id = :id', array(':id'=>2)); //查询一条记录
echo $data->username;
$data = User::model()->findByPk(4); //根据主键查询一条数据
echo $data->username;
$data = User::model()->findByAttributes(array('username' =>'zhangsan ')); //查询置顶条件的一条数据
echo $data->email;
//根据SQL语句查询一条数据
$data = User::model()->findBysql('select * from `tbl_user` where id =:id', array(':id' => 3));
echo $data->email;
//数组作为条件查询
$data = User::model()->find(array (
'select' => 'username',
'condition' =>'id =:id',
'params' => array(':id'=>5),
));
echo $data->username;
//以上都为查询一条记录,以上查询方式都可以改写为查询多条,只需将查询中的find改为findAll即可
//查询多条
$data = User::model()->findAllBysql('select * from `tbl_user` where id >:id', array(':id'=>3));
//这样遍历结果集
foreach ($data as $v) {
echo $v->username; echo '<br>'
}