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


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

add to

$id = \Yii::$app->db
->Insert ('table name ', ['car_ num' => $car_ num, 'lg_ shop_ id' => $shop_ id])
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],


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


// 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();
    $rea = $query - > all(); // query
    $res = $query - > createcommand(); // print SQL
    echo $res->sql;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.