Inserting Data Into The Database Throws An Exception

I’m just getting started with Yii and I have a problem with a database query.

My registration form (View)


<?php if(Yii::app()->user->hasFlash(‘register’)): ?>

<div class="flash-success">

&lt;?php echo Yii::app()-&gt;user-&gt;getFlash('register'); ?&gt;


<?php else: ?>

<div class="form">

<?php $form=$this->beginWidget(‘CActiveForm’, array(



)); ?>

&lt;p class=&quot;note&quot;&gt;Fields with &lt;span class=&quot;required&quot;&gt;*&lt;/span&gt; are required.&lt;/p&gt;

&lt;?php echo &#036;form-&gt;errorSummary(&#036;model); ?&gt;

&lt;div class=&quot;row&quot;&gt;

	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'username'); ?&gt;

	&lt;?php echo &#036;form-&gt;textField(&#036;model,'username'); ?&gt;

	&lt;?php echo &#036;form-&gt;error(&#036;model,'username'); ?&gt;


&lt;div class=&quot;row&quot;&gt;

	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'password'); ?&gt;

	&lt;?php echo &#036;form-&gt;textField(&#036;model,'password'); ?&gt;

	&lt;?php echo &#036;form-&gt;error(&#036;model,'password'); ?&gt;


&lt;div class=&quot;row&quot;&gt;

	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'email'); ?&gt;

	&lt;?php echo &#036;form-&gt;textField(&#036;model,'email'); ?&gt;

	&lt;?php echo &#036;form-&gt;error(&#036;model,'email'); ?&gt;


&lt;div class=&quot;row buttons&quot;&gt;

	&lt;?php echo CHtml::submitButton('Submit'); ?&gt;


<?php $this->endWidget(); ?>

</div><!-- form -->

<?php endif; ?>[/html]



class SiteController extends Controller


        //other methods





	public function actionRegister()


		$model=new RegisterForm;







				$model->myInsert(); //calling method

				Yii::app()->user->setFlash('register','Thank you');







and Model with my ‘insert’ method

class RegisterForm extends CActiveRecord


       //other methods        




	public function myInsert()



		$sql="INSERT INTO tbl_user (username,password,email) VALUES(:username,:password,:email)";










But it does not work and throws exception CDbException:



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(





well… shouldn’t it be like this in your first code? :





I dont see where you assigned your model parameters’ values to does variables.

in your second piece of code, which works, you did use $this-> to read model values.

however I think you would get undefined variable error if those variables were not assigned before… let me know if that’s the problem please.

In the first code you use $username while in the second one you use $this->username, same for the other two attributes

$username = $this->username;

$password = $this->password;

$email = $this->email;

After declaring variables code is executed.

Why did the query constructor succeeded without a declaration?