首先在YII的配置文件里,数据库的配置那一段增加如下两个配置.
'components' => array(
'db' => array(
'connectionString' => 'mysql:host=localhost;dbname=test',
'username' => 'test',
'password' => 'sxaskdljfjrfnmczd',
'enableProfiling' => true, //配置1
'enableParamLogging' => true, //配置2
),
),
接着在日志配置那一段修改为如下配置
'components' => array(
'log' => array(
'class' => 'CLogRouter',
'routes' => array(
array(
'class'=>'CProfileLogRoute',
'levels'=>'profile', //这里是记录运行的级别日志,可选notice,error,trace,log,profile等
//'showInFireBug' => true,
'categories'=>'system.db.CDbCommand.query'
),
),
),
),
showInFireBug这个选项为是否在firebug里面查看运行日志记录.如果不设置的话,那默认就是在页面的底部显示,如果设置了,就在打开的firebug里面查看.
再有朋友可能不知道YII的记录日志是在什么地方.当然前提是你已经把日志记录到文件中,具体设置方法为
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'trace,log',
'categories' => 'system.db.CDbCommand',
'logFile' => 'db.log',
),
),
),
这里设置的日志记录文件为:protected/runtime/db.log 日志的记录,显示方式可以设置多种均可以生效.
$connection = Yii::app()->db; //连接
//查找
$sql = “SELECT * FROM `tbl_user` ORDER BY id DESC”;
$command = $connection->createCommand($sql);
$result = $command->queryAll();
print_r($result);
//添加
$sql = ” INSERT INTO `tbl_user` (`username`, `password`, `email`) VALUES (‘test’, ‘test’, ‘test@test.com’) “;
$command=$connection->createCommand($sql);
print_r($command->execute());
//添加 返回自增id
$command1 = $connection->createCommand(“SELECT last_insert_id()”);
$result = $command1->queryAll();
//常用函数
(1)如果你执行的SQL语句有返回结果集: 例如SELECT。通常用query开头的系列函数:
$dataReader=$command->query(); // 执行一个 SQL 查询
$rows=$command->queryAll(); // 查询并返回结果中的所有行
$row=$command->queryRow(); // 查询并返回结果中的第一行
$column=$command->queryColumn(); // 查询并返回结果中的第一列
$value=$command->queryScalar(); // 查询并返回结果中第一行的第一个字
(2)你执行的SQL语句返回的不是结果集,只是状态值,例如:INSERT ,UPDATE,DELETE.则用execute()
$this->command->execute();
//使用事务的一种常见情形:CDbTransaction
$transaction = $connection->beginTransaction();
try{
$connection->createCommand($sql1)->execute();
$connection->createCommand($sql2)->execute();
………
$transaction->commit();
}
catch(Exception $e){ // 如果有一条查询失败,则会抛出异常
$transaction->rollBack();
}
$sql = "SELECT * FROM `project` ORDER BY id DESC";
$command = $connection->createCommand($sql);
$result = $command->queryAll();
print_r($result);
$sql = "select sum(if(starttime>'09:00:00',1,0)) as late,
sum(if(endtime<'18:00:00',1,0)) as early
from present where userid=:userid and date between :date_start and :date_end"
$results = $db->createCommand($sql)->query(array(
':userid' => 115,':date_start'=>'2009-12-1',':date_end'=>'2009-12-31',
));
foreach($results as $result){
echo $result['late']," and ",$result['early']," /n";
}
说明:把查询条件作为参数(如例2),比较安全,可直接避免注入。要是直接用在SQL语句中,最好要经过防注入处理。
$sql = "select sum(if(starttime>'09:00:00',1,0)) as late,
from present where userid=115 and date between '2009-12-1' and '2009-12-31'"
$results = $db->createCommand($sql)->query();
foreach($results as $result){
echo $result['late']," and ",$result['early']," /n";
}