Yii2.0 framework database operation simple example [add, modify, delete, query, print, etc.]

Time:2021-1-22

This paper describes the yii2.0 framework database operation with an example. The details are as follows:

add to

$id = \Yii::$app->db
->createCommand()
->Insert ('table name ', ['car_ num' => $car_ num, 'lg_ shop_ id' => $shop_ id])
->execute();
Batchinsert(): add multiple rows at a time
// table name, column names, column values
Yii::$app->db->createCommand()->batchInsert('user', ['name', 'age'], [
  ['Tom', 30],
  ['Jane', 20],
  ['Linda', 25],
])->execute();

modify


// UPDATE (table name, column values, condition)
Yii::$app->db->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();


delete


// DELETE (table name, condition)
Yii::$app->db->createCommand()->delete('user', 'status = 0')->execute();

query criteria


$status = 10;
$search = 'yii';
$query->where(['status' => $status]);
if (!empty($search)) {
  $query->andWhere(['like', 'title', $search]);
}


If $search is not empty, the following SQL statement will be generated:


... WHERE (`status` = 10) AND (`title` LIKE '%yii%')

Query and print query SQL

$query = new Query();
    $query->from('{{%shop_info}}');
    $query->where('shop_type=1');
    $query->select('shop_name');
    $rea = $query - > all(); // query
    $res = $query - > createcommand(); // print SQL
    echo $res->sql;die;
    var_dump($rea);die;

For more information about Yii, readers who are interested in it can see the following topics: Yii framework introduction and common skills summary, PHP excellent development framework summary, smart template introduction basic course, PHP object-oriented programming introduction course, PHP string usage summary, PHP + MySQL database operation introduction course and PHP common database operation introduction course Summary of writing skills

I hope this article will be helpful to the PHP Programming Based on Yii framework.