arinze arinze - 5 months ago 84
MySQL Question

insert into database in yii2?

i am trying to insert data to mysql table in yii2 but it gives me errors. i have a textbox in the view. it is meant to get the data the user inputs in the textbox with

name=Topic[topic]
; and insert it into the database. when i try it a different way like
$topic->topic = 'good things';
it works well. but when i try to change it like
$topic->topic = $topic_data['topic'];.

i get this error
Undefined index: topic`

this is the controller


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');
}


this is the view

<?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(); ?>


How do i fix this or is their a better way to do it

Answer

Try using proper $model->load

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