I’m just getting started with Yii and I have a problem with a database query.
My registration form (View)
[html]<h1>Registration</h1>
<?php if(Yii::app()->user->hasFlash(‘register’)): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('register'); ?>
</div>
<?php else: ?>
<div class="form">
<?php $form=$this->beginWidget(‘CActiveForm’, array(
'id'=>'register-form-register-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username'); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->textField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<?php endif; ?>[/html]
Controller
<?php
class SiteController extends Controller
{
//other methods
.
.
.
//registration
public function actionRegister()
{
$model=new RegisterForm;
if(isset($_POST['RegisterForm']))
{
$model->attributes=$_POST['RegisterForm'];
if($model->validate())
{
$model->myInsert(); //calling method
Yii::app()->user->setFlash('register','Thank you');
$this->refresh();
}
}
$this->render('register',array('model'=>$model));
}
}
and Model with my ‘insert’ method
class RegisterForm extends CActiveRecord
{
//other methods
.
.
.
public function myInsert()
{
$connection=Yii::app()->db;
$sql="INSERT INTO tbl_user (username,password,email) VALUES(:username,:password,:email)";
$command=$connection->createCommand($sql);
$command->bindParam(":username",$username,PDO::PARAM_STR);
$command->bindParam(":password",$password,PDO::PARAM_STR);
$command->bindParam(":email",$email,PDO::PARAM_STR);
$command->execute();
}
}
But it does not work and throws exception CDbException:
[b]
[size="4"]EDIT:[/size][/b]
I solved it differently, but I would like to know why the previous code does not work.
I changed the previous code to:
$command = Yii::app()->db->createCommand()
->insert('tbl_user', array(
'username'=>$this->username,
'password'=>MD5($this->password),
'email'=>$this->email,
));