Friday 6 January 2017

YII FrameWork Create DataBases

Creating Database

Earlier we performed CRUD operation with yii's Gii generating tool. Now we'll perform CRUD without Gii.
We'll perform a complete CRUD operation here.
The name of our Yii2 folder is dbb.
We have created a database named student and a table inside it named child.
YII Creating database 1
Look at the above snapshot, this is our table's structure.

Database Configuration

To configure your database in Yii2, go to common/config/main-local.php file and write the name of your database.
We have written student as the name of our database.
  1. <?php   
  2. return [   
  3.     'components' => [   
  4.         'db' => [   
  5.             'class' => 'yii\db\Connection',   
  6.             'dsn' => 'mysql:host=localhost;dbname=student',   
  7.             'username' => 'root',   
  8.             'password' => 'mysql',   
  9.             'charset' => 'utf8',   
  10.        ],   
  11.         'mailer' => [   
  12.             'class' => 'yii\swiftmailer\Mailer',   
  13.             'viewPath' => '@common/mail',   
  14.             // send all mails to a file by default. You have to set   
  15.             // 'useFileTransport' to false and configure a transport   
  16.             // for the mailer to send real emails.   
  17.             'useFileTransport' => true,   
  18.         ],   
  19.     ],   
  20. ];   

Create (Insert) Record

To insert the records in the database, following steps are there. We have named our Yii2 folder as create.
Step 1 Create Model file
Create a model file child.php in frontend/models folder.
  1. <?php   
  2. namespace app\models;   
  3.    
  4. use Yii;   
  5.    
  6. class Child extends \yii\db\ActiveRecord   
  7. {   
  8.     /**  
  9.      * @inheritdoc  
  10.      */   
  11.     public static function tableName()   
  12.     {   
  13.         return 'child';   
  14.     }   
  15.        
  16.     /**  
  17.      * @inheritdoc  
  18.      */   
  19.     public function rules()   
  20.     {   
  21.         return [   
  22.             [['name''meaning''gender'], 'required'],   
  23.             [['name''meaning'], 'string''max' => 100],   
  24.             [['gender'], 'string''max' => 15]   
  25.         ];   
  26.     }   
  27. }  
Look at the above code,
  • \yii\db\ActiveRecord is used to create a model file.
  • In function tableName put the table name you are using.
  • Function rules define the inputs of your table.
Step 2 Create Controllers file
Create a controller file ChildController.php in frontend/controllers folder.
  1. <?php   
  2. namespace frontend\controllers;   
  3.    
  4. use Yii;   
  5. use app\models\Child;   
  6. use yii\web\Controller;   
  7.   
  8. /**  
  9.  * manual CRUD  
  10.  **/   
  11. class ChildController extends Controller   
  12. {    
  13.     /**  
  14.      * Create  
  15.      */   
  16.     public function actionCreate()   
  17.     {   
  18.           
  19.         $model = new Child();   
  20.    
  21.         // new record   
  22.         if($model->load(Yii::$app->request->post()) && $model->save()){   
  23.             return $this->redirect(['index']);   
  24.         }   
  25.                    
  26.         return $this->render('create', ['model' => $model]);   
  27.     }  
  28.     }  
Step 3 Create View file
Create a view folder child in frontend/views folder. Then create a file create.php in frontend/views/child folder.
  1. <?= $this->render('child_view', [   
  2.     'model' => $model,   
  3. ]) ?>  
Now create a file child_view.php in frontend/views/child folder.
  1. <?php   
  2. use yii\helpers\Html;   
  3. use yii\widgets\ActiveForm;   
  4. ?>   
  5.    
  6. <?php $form = ActiveForm::begin(); ?>   
  7.    
  8.     <?= $form->field($model'name'); ?>   
  9.     <?= $form->field($model'meaning'); ?>   
  10.     <?= $form->field($model'gender'); ?>   
  11.       
  12.     <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->   
  13.      isNewRecord ? 'btn btn-success' : 'btn btn-primary']); ?>   
  14.    
  15.    <?php ActiveForm::end(); ?>  
Step 4 Run it
Now run your application on your browser with the following URL.
http://localhost/create/frontend/web/index.php?r=child/create
YII Insert record 1
Look at the above snpashot, after filling all the fields click on Create button and your data will be inserted into the database.
You can check it in the database from your phpmyadmin.



Read Record

Now we'll fetch the data from our table child. Here our Yiii2 folder is named as read.
Step 1 Create Model file
Create a model file child.php in frontend/models folder.
  1. <?php   
  2. namespace app\models;   
  3.    
  4. use Yii;   
  5.    
  6. class Child extends \yii\db\ActiveRecord   
  7. {   
  8.     /**  
  9.      * @inheritdoc  
  10.      */   
  11.     public static function tableName()   
  12.     {   
  13.         return 'child';   
  14.     }   
  15.        
  16.     /**  
  17.      * @inheritdoc  
  18.      */   
  19.     public function rules()   
  20.     {   
  21.         return [   
  22.             [['name''meaning''gender'], 'required'],   
  23.             [['name''meaning'], 'string''max' => 100],   
  24.             [['gender'], 'string''max' => 15]   
  25.         ];   
  26.     }   
  27. }  
Step 2 Add action to read
In the ChildController.php file, we need to add the action actionIndex to fetch the data from the table.
  1. <?php   
  2. namespace frontend\controllers;   
  3.    
  4. use Yii;   
  5. use app\models\Child;   
  6. use yii\web\Controller;   
  7.    
  8.   
  9. /**  
  10.  * manual CRUD  
  11.  **/   
  12. class ChildController extends Controller   
  13. {    
  14.     /**  
  15.      * Create  
  16.      */   
  17.     public function actionCreate()   
  18.     {   
  19.           
  20.         $model = new Child();   
  21.    
  22.         // new record   
  23.         if($model->load(Yii::$app->request->post()) && $model->save()){   
  24.             return $this->redirect(['index']);   
  25.         }   
  26.                    
  27.         return $this->render('create', ['model' => $model]);   
  28.     }   
  29.   
  30.     /**  
  31.      * Read  
  32.      */   
  33.     public function actionIndex()   
  34.     {   
  35.         $child = Child::find()->all();   
  36.            
  37.         return $this->render('index', ['model' => $child]);   
  38.     }  
  39.     }  
Look at the above code, all code is same only action to fetch data is added in the last.
Step 3 Create View file
In the frontend/views/child folder, create a file index.php.
  1. <?php   
  2. use yii\helpers\Html;   
  3. ?>   
  4.    
  5. <style>   
  6. table th,td{   
  7.     padding: 10px;   
  8. }   
  9. </style>   
  10.    
  11. <?= Html::a('Create', ['child/create'], ['class' => 'btn btn-success']); ?>   
  12.    
  13. <table border="1">   
  14.    <tr>   
  15.         <th>Name</th>   
  16.         <th>Meaning</th>   
  17.         <th>Gender</th>   
  18.     </tr>   
  19.     <?php foreach($model as $field){ ?>   
  20.     <tr>   
  21.         <td><?= $field->name; ?></td>   
  22.         <td><?= $field->meaning; ?></td>   
  23.         <td><?= $field->gender; ?></td>   
  24.         <td><?= Html::a("Edit", ['child/edit''id' => $field->id]); ?> | <?= Html::a("Delete", ['child/delete''id' => $field->id]); ?></td>   
  25.     </tr>   
  26.     <?php } ?>  
Step 4 Run it
Run it on the browser,.
http://localhost/read/frontend/web/index.php?r=child%2Findex
YII Read record 1

Update Record

To update the records in the database, following these steps. We have named our Yii2 folder as update.
Step 1 Create Model file
Create a model file child.php in frontend/models folder.
  1. <?php   
  2. namespace app\models;   
  3.    
  4. use Yii;   
  5.    
  6. class Child extends \yii\db\ActiveRecord   
  7. {   
  8.     /**  
  9.      * @inheritdoc  
  10.      */   
  11.     public static function tableName()   
  12.     {   
  13.         return 'child';   
  14.     }   
  15.        
  16.     /**  
  17.      * @inheritdoc  
  18.      */   
  19.     public function rules()   
  20.     {   
  21.         return [   
  22.             [['name''meaning''gender'], 'required'],   
  23.             [['name''meaning'], 'string''max' => 100],   
  24.             [['gender'], 'string''max' => 15]   
  25.         ];   
  26.     }   
  27. }  
Step 2 Add action in controllers
Add the update action actionEdit in controllers file ChildController.php.
  1. <?php   
  2. namespace frontend\controllers;   
  3.    
  4. use Yii;   
  5. use app\models\Child;   
  6. use yii\web\Controller;   
  7.    
  8.   
  9. /**  
  10. * manual CRUD  
  11.  **/   
  12. class ChildController extends Controller   
  13. {    
  14.     /**  
  15.      * Create  
  16.      */   
  17.     public function actionCreate()   
  18.     {   
  19.           
  20.         $model = new Child();   
  21.    
  22.         // new record   
  23.         if($model->load(Yii::$app->request->post()) && $model->save()){   
  24.             return $this->redirect(['index']);   
  25.         }   
  26.                    
  27.         return $this->render('create', ['model' => $model]);   
  28.     }   
  29.   
  30.     /**  
  31.      * Read  
  32.      */   
  33.     public function actionIndex()   
  34.     {   
  35.         $child = Child::find()->all();   
  36.            
  37.         return $this->render('index', ['model' => $child]);   
  38.     }   
  39.   
  40.     /**  
  41.      * Edit  
  42.      * @param integer $id  
  43.      */   
  44.     public function actionEdit($id)   
  45.     {   
  46.         $model = Child::find()->where(['id' => $id])->one();   
  47.    
  48.         // $id not found in database   
  49.         if($model === null)   
  50.             throw new NotFoundHttpException('The requested page does not exist.');   
  51.            
  52.         // update record   
  53.         if($model->load(Yii::$app->request->post()) && $model->save()){   
  54.             return $this->redirect(['index']);   
  55.         }   
  56.            
  57.         return $this->render('edit', ['model' => $model]);   
  58.     }   
  59.     }  
Step 3 Create View file
Create a file edit.php in frontend/view/child folder.
  1. <?= $this->render('child_view', [   
  2.     'model' => $model,   
  3. ]) ?>  
Step 4 Run it
Run it on the browser.
http://localhost/dbb/frontend/web/index.php?r=child%2Fedit&id=6
YII Update record 1
Click on Update, information will be updated.
YII Update record 2
Look at the last row in above snapshot, data is updated.

Delete Record

To delete records in the database, following these steps. We have named our Yii2 folder as delete.
Step 1 Create Model file
Create a model file child.php in frontend/models folder.
  1. <?php   
  2. namespace app\models;   
  3.    
  4. use Yii;   
  5.    
  6. class Child extends \yii\db\ActiveRecord   
  7. {   
  8.     /**  
  9.      * @inheritdoc  
  10.      */   
  11.     public static function tableName()   
  12.     {   
  13.         return 'child';   
  14.     }   
  15.        
  16.     /**  
  17.      * @inheritdoc  
  18.      */   
  19.     public function rules()   
  20.     {   
  21.         return [   
  22.             [['name''meaning''gender'], 'required'],   
  23.             [['name''meaning'], 'string''max' => 100],   
  24.             [['gender'], 'string''max' => 15]   
  25.         ];   
  26.     }   
  27. }  
Step 2 Create action in controllers
Create an action actionDelete in ChildController.php file.
  1. <?php   
  2. namespace frontend\controllers;   
  3.    
  4. use Yii;   
  5. use app\models\Child;   
  6. use yii\web\Controller;   
  7.    
  8.   
  9. /**  
  10.  * manual CRUD  
  11.  **/   
  12. class ChildController extends Controller   
  13. {    
  14.     /**  
  15.      * Create  
  16.      */   
  17.     public function actionCreate()   
  18.     {   
  19.           
  20.         $model = new Child();   
  21.    
  22.         // new record   
  23.         if($model->load(Yii::$app->request->post()) && $model->save()){   
  24.             return $this->redirect(['index']);   
  25.         }   
  26.                    
  27.         return $this->render('create', ['model' => $model]);   
  28.     }   
  29.   
  30.     /**  
  31.      * Read  
  32.      */   
  33.     public function actionIndex()   
  34.     {   
  35.         $child = Child::find()->all();   
  36.            
  37.         return $this->render('index', ['model' => $child]);   
  38.     }   
  39.   
  40.     /**  
  41.      * Edit  
  42.      * @param integer $id  
  43.      */   
  44.     public function actionEdit($id)   
  45.     {   
  46.         $model = Child::find()->where(['id' => $id])->one();   
  47.    
  48.         // $id not found in database   
  49.         if($model === null)   
  50.             throw new NotFoundHttpException('The requested page does not exist.');   
  51.            
  52.         // update record   
  53.         if($model->load(Yii::$app->request->post()) && $model->save()){   
  54.             return $this->redirect(['index']);   
  55.         }   
  56.            
  57.         return $this->render('edit', ['model' => $model]);   
  58.     }   
  59.   
  60.      /**  
  61.     * Delete  
  62.      * @param integer $id  
  63.      */   
  64.      public function actionDelete($id)   
  65.      {   
  66.          $model = Child::findOne($id);   
  67.            
  68.         // $id not found in database   
  69.         if($model === null)   
  70.             throw new NotFoundHttpException('The requested page does not exist.');   
  71.                
  72.         // delete record   
  73.         $model->delete();   
  74.            
  75.         return $this->redirect(['index']);   
  76.      }      
  77.    }  
Step 3 Run it
Run it on the browser.
http://localhost/delete/frontend/web/index.php?r=child%2Findex
YII Delete record 1
Look at the above snapshot, click the Delete option in the last row of the table.
Look at the above snapshot, respective row is deleted from the table.
YII Delete record 2

No comments:

Post a Comment