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.
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.
- <?php
- return [
- 'components' => [
- 'db' => [
- 'class' => 'yii\db\Connection',
- 'dsn' => 'mysql:host=localhost;dbname=student',
- 'username' => 'root',
- 'password' => 'mysql',
- 'charset' => 'utf8',
- ],
- 'mailer' => [
- 'class' => 'yii\swiftmailer\Mailer',
- 'viewPath' => '@common/mail',
- // send all mails to a file by default. You have to set
- // 'useFileTransport' to false and configure a transport
- // for the mailer to send real emails.
- 'useFileTransport' => true,
- ],
- ],
- ];
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.
- <?php
- namespace app\models;
- use Yii;
- class Child extends \yii\db\ActiveRecord
- {
- /**
- * @inheritdoc
- */
- public static function tableName()
- {
- return 'child';
- }
- /**
- * @inheritdoc
- */
- public function rules()
- {
- return [
- [['name', 'meaning', 'gender'], 'required'],
- [['name', 'meaning'], 'string', 'max' => 100],
- [['gender'], 'string', 'max' => 15]
- ];
- }
- }
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.
- <?php
- namespace frontend\controllers;
- use Yii;
- use app\models\Child;
- use yii\web\Controller;
- /**
- * manual CRUD
- **/
- class ChildController extends Controller
- {
- /**
- * Create
- */
- public function actionCreate()
- {
- $model = new Child();
- // new record
- if($model->load(Yii::$app->request->post()) && $model->save()){
- return $this->redirect(['index']);
- }
- return $this->render('create', ['model' => $model]);
- }
- }
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.
Now create a file child_view.php in frontend/views/child folder.
- <?php
- use yii\helpers\Html;
- use yii\widgets\ActiveForm;
- ?>
- <?php $form = ActiveForm::begin(); ?>
- <?= $form->field($model, 'name'); ?>
- <?= $form->field($model, 'meaning'); ?>
- <?= $form->field($model, 'gender'); ?>
- <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->
- isNewRecord ? 'btn btn-success' : 'btn btn-primary']); ?>
- <?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
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.
- <?php
- namespace app\models;
- use Yii;
- class Child extends \yii\db\ActiveRecord
- {
- /**
- * @inheritdoc
- */
- public static function tableName()
- {
- return 'child';
- }
- /**
- * @inheritdoc
- */
- public function rules()
- {
- return [
- [['name', 'meaning', 'gender'], 'required'],
- [['name', 'meaning'], 'string', 'max' => 100],
- [['gender'], 'string', 'max' => 15]
- ];
- }
- }
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.
- <?php
- namespace frontend\controllers;
- use Yii;
- use app\models\Child;
- use yii\web\Controller;
- /**
- * manual CRUD
- **/
- class ChildController extends Controller
- {
- /**
- * Create
- */
- public function actionCreate()
- {
- $model = new Child();
- // new record
- if($model->load(Yii::$app->request->post()) && $model->save()){
- return $this->redirect(['index']);
- }
- return $this->render('create', ['model' => $model]);
- }
- /**
- * Read
- */
- public function actionIndex()
- {
- $child = Child::find()->all();
- return $this->render('index', ['model' => $child]);
- }
- }
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.
- <?php
- use yii\helpers\Html;
- ?>
- <style>
- table th,td{
- padding: 10px;
- }
- </style>
- <?= Html::a('Create', ['child/create'], ['class' => 'btn btn-success']); ?>
- <table border="1">
- <tr>
- <th>Name</th>
- <th>Meaning</th>
- <th>Gender</th>
- </tr>
- <?php foreach($model as $field){ ?>
- <tr>
- <td><?= $field->name; ?></td>
- <td><?= $field->meaning; ?></td>
- <td><?= $field->gender; ?></td>
- <td><?= Html::a("Edit", ['child/edit', 'id' => $field->id]); ?> | <?= Html::a("Delete", ['child/delete', 'id' => $field->id]); ?></td>
- </tr>
- <?php } ?>
Step 4 Run it
Run it on the browser,.
http://localhost/read/frontend/web/index.php?r=child%2Findex
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.
- <?php
- namespace app\models;
- use Yii;
- class Child extends \yii\db\ActiveRecord
- {
- /**
- * @inheritdoc
- */
- public static function tableName()
- {
- return 'child';
- }
- /**
- * @inheritdoc
- */
- public function rules()
- {
- return [
- [['name', 'meaning', 'gender'], 'required'],
- [['name', 'meaning'], 'string', 'max' => 100],
- [['gender'], 'string', 'max' => 15]
- ];
- }
- }
Step 2 Add action in controllers
Add the update action actionEdit in controllers file ChildController.php.
- <?php
- namespace frontend\controllers;
- use Yii;
- use app\models\Child;
- use yii\web\Controller;
- /**
- * manual CRUD
- **/
- class ChildController extends Controller
- {
- /**
- * Create
- */
- public function actionCreate()
- {
- $model = new Child();
- // new record
- if($model->load(Yii::$app->request->post()) && $model->save()){
- return $this->redirect(['index']);
- }
- return $this->render('create', ['model' => $model]);
- }
- /**
- * Read
- */
- public function actionIndex()
- {
- $child = Child::find()->all();
- return $this->render('index', ['model' => $child]);
- }
- /**
- * Edit
- * @param integer $id
- */
- public function actionEdit($id)
- {
- $model = Child::find()->where(['id' => $id])->one();
- // $id not found in database
- if($model === null)
- throw new NotFoundHttpException('The requested page does not exist.');
- // update record
- if($model->load(Yii::$app->request->post()) && $model->save()){
- return $this->redirect(['index']);
- }
- return $this->render('edit', ['model' => $model]);
- }
- }
Step 3 Create View file
Create a file edit.php in frontend/view/child folder.
Step 4 Run it
Run it on the browser.
http://localhost/dbb/frontend/web/index.php?r=child%2Fedit&id=6
Click on Update, information will be updated.
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.
- <?php
- namespace app\models;
- use Yii;
- class Child extends \yii\db\ActiveRecord
- {
- /**
- * @inheritdoc
- */
- public static function tableName()
- {
- return 'child';
- }
- /**
- * @inheritdoc
- */
- public function rules()
- {
- return [
- [['name', 'meaning', 'gender'], 'required'],
- [['name', 'meaning'], 'string', 'max' => 100],
- [['gender'], 'string', 'max' => 15]
- ];
- }
- }
Step 2 Create action in controllers
Create an action actionDelete in ChildController.php file.
- <?php
- namespace frontend\controllers;
- use Yii;
- use app\models\Child;
- use yii\web\Controller;
- /**
- * manual CRUD
- **/
- class ChildController extends Controller
- {
- /**
- * Create
- */
- public function actionCreate()
- {
- $model = new Child();
- // new record
- if($model->load(Yii::$app->request->post()) && $model->save()){
- return $this->redirect(['index']);
- }
- return $this->render('create', ['model' => $model]);
- }
- /**
- * Read
- */
- public function actionIndex()
- {
- $child = Child::find()->all();
- return $this->render('index', ['model' => $child]);
- }
- /**
- * Edit
- * @param integer $id
- */
- public function actionEdit($id)
- {
- $model = Child::find()->where(['id' => $id])->one();
- // $id not found in database
- if($model === null)
- throw new NotFoundHttpException('The requested page does not exist.');
- // update record
- if($model->load(Yii::$app->request->post()) && $model->save()){
- return $this->redirect(['index']);
- }
- return $this->render('edit', ['model' => $model]);
- }
- /**
- * Delete
- * @param integer $id
- */
- public function actionDelete($id)
- {
- $model = Child::findOne($id);
- // $id not found in database
- if($model === null)
- throw new NotFoundHttpException('The requested page does not exist.');
- // delete record
- $model->delete();
- return $this->redirect(['index']);
- }
- }
Step 3 Run it
Run it on the browser.
http://localhost/delete/frontend/web/index.php?r=child%2Findex
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.
No comments:
Post a Comment