Yii如何从数据库中检索数据并在视图中显示


Yii How to retrieve data from DB and display in view

我正在尝试从数据库中检索数据。。。但我面临一些问题

以下是我的编码:

在控制器中:

public function actionFinalCheck()
{
    $gametitle=GamesDevelopersApp::model()->find('develper_id=1',array('gametitle'));
    $this->render('finalcheck',array('gametitle'=>$gametitle));
}

视图中(PHP):

<?php print_r($gametitle); ?>

我需要的是"select gametitle from db where developer_id=1",但在Yii中我不知道如何进行

或者有什么更好的方法可以从数据库中检索数据并在视图中显示?感谢

您可以通过下面列出的方法来实现这一点:

活动记录

你需要有一个模型,通过模型你可以获取如下数据:

$object=GamesDevelopersApp::model()->findByAttributes(array("develper_id"=>1));
echo $object->gametitle; // prints gametitle

查询生成器

$row=Yii::app()->db->createCommand()->select('gametitle')->from('db')->where('id=1')->queryRow();
echo $row['gametitle']; //prints gametitle

DAO(数据访问对象)

$sql="select gametitle from db where developer_id=1";
$command=Yii::app()->db->createCommand($sql)->queryRow();
echo $command['gametitle']; //prints gametitle

我使用它对我来说效果很好!

在控制器中

public function actionFinalCheck()
{
    $developer_id = 'developer_id=1';
    $gametitle=GamesDevelopersApp::model()->find($developer_id);
    $this->render('finalcheck',array('gametitle'=>$gametitle));
}

视图中(PHP):

<?php echo CHtml::encode($gametitle->gametitle); ?>

您正在传递参数developer_id,但没有在条件中使用它。尝试将CDBCriteria对象传递给它,如下所示:

$criteria = new CDbCriteria();
$criteria->compare('id', 1); // Check that the column gametitle is equal to 1
$gametitle=GamesDevelopersApp::model()->findAll($criteria);

请参阅ACtiveRecord的findAll方法http://www.yiiframework.com/doc/api/1.1/CActiveRecord#findAll-详细信息

public function getQuotes()
    {    
       $sql="select * from db";
        $command=Yii::app()->db->createCommand($sql)->queryAll();
        foreach($command as $commands)
        echo $commands['gametitle']; 
    }

视图:

<?php echo CHtml::encode($model->gametitle)?>