如何将yii中的输入保存到数据库


How to save input in yii to database

我有这段代码,我试图保存我制作的表单中的内容和标题。。它有一个id,可以自动递增id号添加到数据库中,但标题和内容不能保存在数据库中。如果我做错了什么,你能检查一下我的代码吗?或者我所缺乏的。

这是我的模型ContentForm.php

<?php
class ContentForm extends CActiveRecord{
public $content;
public $title;
public function tableName(){
    return 'tbl_content';
}
public function attributeLabels()
{
    return array(
        'contentid' => 'contentid',
        'content' => 'content',
        'title' => 'title',
        // 'email' => 'Email',
        // 'usrtype' => 'Usrtype',
    );
}

这是我的视图内容.php

<div>
<p>User: <a href="viewuserpost">
<?php 
echo Yii::app()->session['nameuser']; 
 ?>
 </a>
 </p>
 </div>
 <h1>Content</h1>
 <?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
 Title:
 <div class="row">
 <?php
echo $form->textfield($model,'title');
 ?>
 </div>
 </br>
 Body:
 <div class="row">
 <?php 
echo $form->textArea($model,'content',array('rows'=>16,'cols'=>110));
 ?>
 </div>
 <div class="row buttons">
 <?php 
echo CHtml::submitButton($model->isNewRecord? 'Create':'Save'); 
 ?>
 </div>
 <?php $this->endWidget(); ?>

这是我在sitecontroller.php 中的内容操作

public function actionContent(){
    $model=new ContentForm;
        if(isset($_POST['ContentForm'])) {
            $model->attributes=$_POST['ContentForm'];
            if($model->save())
            $this->redirect(array('content','contentid'=>$model->contentid));
            $this->redirect(array('content','title'=>$model->title));
            $this->redirect(array('content','content'=>$model->content));
            }
    $this->render('content',array('model'=>$model));        
}

请帮忙。

删除

public $content;
public $title;

来自你班的。

Yii使用PHP魔术方法。当您向类中添加属性时,PHP不会调用它们,而是引用显式编写的属性。

此外,如果使用$model->attributes=$_POST['ContentForm'];,则应该添加一些验证。另一个变体是使用不安全的$model->setAttributes($_POST[ContentForm], false),其中false告诉Yii设置所有属性,而不仅仅是被认为安全的属性。

注意,attributes不是真实的Model属性,这是通过魔术方法访问的虚拟属性。

此外,您不需要三个重定向。这是HTTP重定向到其他页面。这一次,您只需要指定路由到模型视图操作及其参数,例如id。就像这个$this->redirect(array('content/view','id'=>$model->contentid));

当然,最简单的方法是使用Gii创建新的模型和控制器。

您可能会错过规则,请将其添加到您的模型ContentForm.php 中

public function rules()
{
    return array(
       array('content,title', 'safe'),
    );
}

有关模型验证的更多信息

http://www.yiiframework.com/wiki/56/reference-model-rules-validation/