CRUD operation in Yii framework

4 followers

Simple Yii Script for performing CRUD operations:

Greetings, This tutorial teach you the simple way to perform the crud operation in Yii framework, its easy to perform the database operation in Yii. Here we are going to see the create, update, delete and select scripts that required in almost all the applications.

Create

**// to save all the paramerters of the post request**
  $model = new Model;
  $model->attributes=$_POST['form-name'];
  $model->save();
 
**// to save parameters with changes before creation**
  $model = new Model;
**// here name will concatenate both first and last names**
  $model->name=$_POST['firstname'].$_POST['lastname'];
  $model->attributes=$_POST['form-name'];
  $model->save();

Update

// to update the the whole parameters 
  $model = new Model;
// the form that already maps the id with value
  $model->attributes=$_POST['form-name'];
  $model->save();
 
// to update few parameters
**// Model::model()->updateAll(array($parameters),$conditions);**
 Model::model()->updateAll(array('name' => $_POST['name']),'id="'.$POST['id'] );

Delete

Model::model()->deleteAll(array('condition' => 'id=:io','params' => array('io' => $_POST['id'])));

select

// in model
$criteria=new CDbCriteria;
$criteria->compare('status',$this->status,true);
$criteria->compare('name',$this->name,true);
**// if you want to select a few fields the use the following
// other wise ignore this you will get all the records**
$criteria->select='t.*,md.name';
return new CActiveDataProvider($this, array('criteria'=>$criteria));
 
// in controller
$model=new Currency('search');
$this->render('index',array('model'=>$model));

For more Related information regarding the active records Visit : http://www.bsourcecode.com/2013/06/cdbcriteria-in-yii/

Thanks.

Total 4 comments

#17673 report it
Rohit Suthar at 2014/07/14 02:35am
Less knowledge..

are you trying this youself???

#17497 report it
le_top at 2014/06/23 05:29pm
Not a very good example ..

Thanks for your effort to share, though this is not a very good example.

  1. CRUD is Create, Read, Update, Delete
  2. You can create the CRUD operations with Gii.
  3. In Yii, the 'form-name' is actually 'Model'.
  4. Why concatenate first and last name (without a space), if it should be part of Model? It seems better to create virtual attributes in Model and do the concatenation in Model.
  5. It's best to explicitally call 'validate' on the model.
  6. 'select' : you're not mentionning that the code is inside a 'search' function.
  7. UpdateAll will change all records, not just one.
  8. etc.
#17391 report it
andybegin at 2014/06/03 01:03am
this tutorials is old version. not worth to learn it.

this tutorials is old version. not worth to learn it.

#17387 report it
Ryadnov at 2014/06/02 08:11am
WTF?

WTF?

Leave a comment

Please to leave your comment.

Write new article