This article describes the Yii framework implements CURD operations on databases. Share it for your reference, as follows:
First, you need to operate on the database. You need to create a model with the same name as the database table and place it in the models folder.
<?php namespace app\models; use yii\db\ActiveRecord; //Inherit ActiveRecord to implement CURD operationclass user extends ActiveRecord { }
The namespace in the subsequent code has been omitted
namespace app\controllers; use yii\web\Controller; use app\models\user;
1. Query
The first is to query through SQL
$sql = "select * from user where UserId = :id"; $res = user::findBySql($sql,['id'=>1])->all(); print_r($res[0]); //If only one data is needed$res = user::findBySql($sql,['id'=>1])->one(); print_r($res);
The second type is to query through find
$res = user::find()->where(['id'=>1])->one(); print_r($res);
2. Add
$user = new user(); //The fields in the database are assigned as attribute values. The attribute name must be the same as the data name, otherwise an error will be reported.$user->UserName = "Doubly"; $user->Password = "123"; $user->Email = "doubly_yi@"; //Calling the save method of the user object can be saved$user->save();
3. Modify
//First get the object that needs to be modified$user = user::find()->where(['UserId'=>1])->one(); //Set the properties that need to be modified$user->UserName = "beneficial"; //Call the update() of the object$user->update();
4. Delete
//First get the object to be deleted$user = user::find()->where(['UserId'=>1])->one(); //Execute the delete() method of the object$user->delete();
For more information about Yii, readers who are interested in this site can view the topic:Yii framework introduction and common techniques summary》、《Summary of excellent development framework for php》、《Basic tutorial on getting started with smarty templates》、《PHP object-oriented programming tutorial》、《Summary of usage of php strings》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php》
I hope that this article will be helpful to everyone's PHP programming based on the Yii framework.