如何在yii中执行sql查询?

时间:2014-06-21 17:55:48

标签: php mysql sql yii

我想在Yii的视图页面中执行查询,这是我的代码:

$connection=Yii::app()->db;
$connection->active=true;
$sql = "insert into news(idNews, news, display) values('', 'anything', 0)";
$command=$connection->createCommand($sql);
$command->execute();

但什么都没发生,我的代码有什么错误?

3 个答案:

答案 0 :(得分:3)

或者:

$sql = 'insert into news (news, display) values (:news, :display)';
$parameters = array(':user_id'=>'', ':created' => date('Y-m-d H:i:s'));
Yii::app()->db->createCommand($sql)->execute($parameters);

答案 1 :(得分:3)

为什么在视图页面中执行查询?在数据访问层中是您经常从中进行查询的位置。您可以先在控制器中尝试。

在这里,您可以阅读Yii中的数据访问对象: http://www.yiiframework.com/doc/guide/1.1/en/database.dao

答案 2 :(得分:0)

试试这个:

$news = new News();
$news->news = "anything";
$news->display = 0;
$news->save(false);