Example of CURD operation on database implemented by Yii framework
- 2021-12-19 06:07:39
- OfStack
In this paper, an example is given to describe the CURD operation of database realized by Yii framework. Share it for your reference, as follows:
First of all, to operate the database, you need to create an model with the same name as the database table and put it in the models folder
user.php
<?php
namespace app\models;
use yii\db\ActiveRecord;
// Inheritance ActiveRecord Realization CURD Operation
class user extends ActiveRecord
{
}
Namespace has been omitted in the following code
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 you only need to query 1 Bar data
$res = user::findBySql($sql,['id'=>1])->one();
print_r($res);
Second, query through find
$res = user::find()->where(['id'=>1])->one();
print_r($res);
2. Increase
$user = new user();
// The fields in the direct database are assigned as attributes, and the attribute name should be the same as the data name, otherwise an error will be reported
$user->UserName = "Doubly";
$user->Password = "123";
$user->Email = "doubly_yi@qq.com";
// Call user Object's save Method to save the
$user->save();
3. Modifications
// First, get the object to be modified
$user = user::find()->where(['UserId'=>1])->one();
// Set the properties that need to be modified
$user->UserName = " Benefit ";
// Object that calls the update()
$user->update();
4. Delete
// First, get the object to be deleted
$user = user::find()->where(['UserId'=>1])->one();
// Object of the execution object delete() Method
$user->delete();
For more readers interested in Yii related contents, please check the topics on this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Basic Tutorial of Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Usage Summary of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"
I hope this article is helpful to the PHP programming based on Yii framework.