Hi all, I’m having a problem with Yii2, expect people to help me.
I’m doing the first Yii2 project, and I’m having a problem saving the database data.
Here is my code :
File model RegisterForm.php :
<?php
namespace frontend\models;
use yii\base\Model;
use yii\db\ActiveRecord;
class RegisterForm extends ActiveRecord
{
public $username;
public $email;
public $password;
public static function tableName()
{
return 'users';
}
public function rules()
{
return [
];
}
public function attributeLabels()
{
return [
'username' =>"Username",
'email' =>"Email",
'password' =>"Password",
];
}
public function register(RegisterForm $user)
{
if (!$this->validate()) {
return null;
}
$user->username = $this->username;
//$user->username = "test";
$user->email = $this->email;
$user->password = $this->password;
$user->created_at = date("Y-m-d H:i", time());
if($user->save())
return "save successful";
else
return "save failed";
}
}
File controller DemoController.php :
<?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use frontend\models\RegisterForm;
class DemoController extends Controller
{
public function actionRegister()
{
$model = new RegisterForm();
if ($model->load(Yii::$app->request->post())) {
if ($msg = $model->register($model)) {
echo $msg;
die();
}
}
return $this->render('register', [
'model' => $model,
]);
}
}
Result I always receive is "save successful", that means save() function worked, but data is not fully inserted in the database. It only add created_at value, but three value username, password, email is not added. Although I replaced by static values, or replace save() by insert(), but result still not change. Where is error ?