0

现在我正在构建一个网站的视图,并使用小部件 CActiveForm 作为视图。但是,我需要显示数据库的一些内容,例如,SQL 查询的结果。那我应该怎么做才能完成目标呢?谢谢!

下面提供了我的一些代码:

<div class="form">
<?php

$form=$this->beginWidget('CActiveForm', array(
    'id'=>'login-form',
    'enableClientValidation'=>true,
    'clientOptions'=>array(
        'validateOnSubmit'=>true,
    ),
));

?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>


    <div class="row buttons">
        <?php echo CHtml::submitButton('Login'); ?>
    </div>

    <div class="row radiobuttons">
        <?php echo CHtml::radioButtonList(
            $Paper,
            'Q1No',
            array('A'=>'A','B'=>'B','C'=>'C','D'=>'D'),
            array('template'=>'<span class="radio">{input}{label}</span>','separator'=>'')); 
        ?>
    </div>

<?php $this->endWidget(); ?>
</div><!-- form -->

这是我的代码。我需要在表单中添加一些数据库的内容。内容如下:

    public function actionTaketest()
    {
        // Get the ID of the test paper from the URL ---ztm
        if(isset($_GET['paperid']))
        {
            $paperid=(int)$_GET['paperid'];
            $dsn = 'mysql:host=localhost;dbname=mydatabase';
            $username = 'root';
            $password = '000000';

            $connection=new CDbConnection($dsn,$username,$password);

            // establish connection. You may try...catch possible exceptions
            $connection->active=true;

            $rawData = Yii::app()->db->createCommand()
                ->select('*')
                ->from('Paper, Question') array(':PaperNo'=>$paperid))
                ->queryAll();

            $dataProvider=new CArrayDataProvider($rawData, array(
                'id'=>'PaperNo',
            ));


            $connection->active=false; // close connection


            $model=new LoginForm;
            $this->render('form',array('model'=>$model, 'dataProvider'=>$dataProvider));

        }
        else
        {
            // Deny illegal access to the page ---ztm
            throw new CHttpException(404,'invalid request');
        }
    }

此代码在控制器中。

4

1 回答 1

1

你的代码太乱了,在某些地方看起来无效。首先,您不需要在控制器中创建 CDbConnection,您可以在 config.xml 中指定凭据。要从数据库中读取数据,您可以使用ActiveRecord

$paper = Paper::model()->findByAttributes(array('PaperNo' => $paperid));

然后在你的 html 中:

echo CHtml::activeRadioButtonList(
        $paper,
        'Q1No',
        array('A'=>'A','B'=>'B','C'=>'C','D'=>'D'),
        array('template'=>'<span class="radio">{input}{label}</span>','separator'=>'')
);

我希望它有一点帮助。

于 2012-05-21T10:08:02.707 回答