在yii2中插入数据库?

时间:2016-06-17 11:58:58

标签: php mysql yii2

我试图在yii2中将数据插入到MySQL表中,但它给了我错误。

我在视图中有一个文本框。它旨在通过name=Topic[topic];获取用户在文本框中输入的数据,并将其插入数据库。

当我尝试使用$topic->topic = 'good things';之类的其他方式时效果很好,但是当我尝试更改它时$topic->topic = $topic_data['topic'];. 我收到此错误

Undefined index: topic`

这是控制器:     

use Yii;
use common\models\LoginForm;
use common\models\Topic;
use frontend\models\ContactForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;;

use yii\base\InvalidParamException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\BadRequestHttpException;
use yii\web\Controller;

    public function actionCompose()
    {
          $topic= new Topic(); 

       $topic_data = Yii::$app->request->post('Topic', []);

        $topic->creator = Yii::$app->user->identity->email;
          $topic->topic = $topic_data['topic'];

         $topic->save();
           return $this->render('compose');
    }  

这就是观点:

<?php

use yii\widgets\ListView;
use yii\data\ArrayDataProvider;
use app\models\MyProfile;
use app\models\LikeDiscussion;
use yii\widgets\ActiveForm;
use common\models\Topic;
use common\models\Comment;
use common\models\Users;
use common\models\Candidate;
use yii\widgets\Pjax;
use yii\helpers\Html;
use frontend\assets\AppAsset;

$this->title = 'My Yii Application';
?>
       <?php $form = ActiveForm::begin(); ?>

  <input type="name" class="form-control"  required="true" name="Topic[topic]" id="topic" placeholder="topic">

   <?= Html::submitButton('My Yii Application', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>   
    <?php ActiveForm::end(); ?>    

我如何解决这个问题,或者他们是一个更好的方法呢?

1 个答案:

答案 0 :(得分:2)

尝试使用正确的$ model-&gt;加载

   $topic= new Topic(); 
   $topic->load($_POST)
   $topic->creator = Yii::$app->user->identity->email;
   $topic->save();
   return $this->render('compose');