Home > Backend Development > PHP Tutorial > Example tutorial on using database configuration and SQL operation in PHP's Yii framework, yii example tutorial_PHP tutorial

Example tutorial on using database configuration and SQL operation in PHP's Yii framework, yii example tutorial_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-12 08:56:32
Original
955 people have browsed it

Using database configuration and SQL operation example tutorials in PHP's Yii framework, yii example tutorials

Database access (DAO)
Yii includes a data access layer (DAO) built on PHP PDO. DAO provides a unified API for different databases. ActiveRecord provides database and model (M, Model in MVC) Interaction, QueryBuilder is used to create dynamic query statements. DAO provides simple and efficient SQL queries, which can be used in various places to interact with the database.

Yii supports the following databases (DBMS) by default:

  • MySQL
  • MariaDB
  • SQLite
  • PostgreSQL
  • CUBRID: Version >= 9.3 . (Due to a bug in the PHP PDO extension, the reference value will be invalid, so you need to use 9.3 on both the client and server side of CUBRID)
  • Oracle
  • MSSQL: Version>=2005.

Configuration

To start using the database, you first need to configure the database connection component. This is achieved by adding the db component to the application configuration (the "basic" Web application is config/web.php). DSN (Data Source Name) is the data source name, used to specify Database information. As shown below:

return [
  // ...
  'components' => [
    // ...
    'db' => [
      'class' => 'yii\db\Connection',
      'dsn' => 'mysql:host=localhost;dbname=mydatabase', // MySQL, MariaDB
      //'dsn' => 'sqlite:/path/to/database/file', // SQLite
      //'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL
      //'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID
      //'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver
      //'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver
      //'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver
      //'dsn' => 'oci:dbname=//localhost:1521/mydatabase', // Oracle
      'username' => 'root', //数据库用户名
      'password' => '', //数据库密码
      'charset' => 'utf8',
    ],
  ],
  // ...
];
Copy after login

Please refer to the PHP manual for more information about the DSN format. After configuring the connection component, it can be accessed using the following syntax:

$connection = \Yii::$app->db;

Copy after login

Please refer to yiidbConnection for a list of configurable properties. If you want to connect to the database through ODBC, you need to configure the yiidbConnection::driverName attribute, for example:

'db' => [
  'class' => 'yii\db\Connection',
  'driverName' => 'mysql',
  'dsn' => 'odbc:Driver={MySQL};Server=localhost;Database=test',
  'username' => 'root',
  'password' => '',
],
Copy after login

Note: If you need to use multiple databases at the same time, you can define multiple connection components:

return [
  // ...
  'components' => [
    // ...
    'db' => [
      'class' => 'yii\db\Connection',
      'dsn' => 'mysql:host=localhost;dbname=mydatabase', 
      'username' => 'root',
      'password' => '',
      'charset' => 'utf8',
    ],
    'secondDb' => [
      'class' => 'yii\db\Connection',
      'dsn' => 'sqlite:/path/to/database/file', 
    ],
  ],
  // ...
];
Copy after login

is used in code via:

$primaryConnection = \Yii::$app->db;
$secondaryConnection = \Yii::$app->secondDb;
Copy after login

If you don’t want to define the database connection as a global application component, you can initialize it directly in the code:

$connection = new \yii\db\Connection([
  'dsn' => $dsn,
   'username' => $username,
   'password' => $password,
]);
$connection->open();
Copy after login

Tip: If you need to perform additional SQL queries after creating the connection, you can add the following code to the application configuration file:

return [
  // ...
  'components' => [
    // ...
    'db' => [
      'class' => 'yii\db\Connection',
      // ...
      'on afterOpen' => function($event) {
        $event->sender->createCommand("SET time_zone = 'UTC'")->execute();
      }
    ],
  ],
  // ...
];
Copy after login

If executing SQL does not return any data, you can use the execute method in the command:

$command = $connection->createCommand('UPDATE post SET status=1 WHERE id=1');
$command->execute();
Copy after login

You can use the insert, update, and delete methods, which will generate appropriate SQL based on the parameters and execute them.

// INSERT
$connection->createCommand()->insert('user', [
  'name' => 'Sam',
  'age' => 30,
])->execute();

// INSERT 一次插入多行
$connection->createCommand()->batchInsert('user', ['name', 'age'], [
  ['Tom', 30],
  ['Jane', 20],
  ['Linda', 25],
])->execute();

// UPDATE
$connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();

// DELETE
$connection->createCommand()->delete('user', 'status = 0')->execute();

Copy after login

Referenced table name and column name

Most of the time use the following syntax to safely reference table and column names:

$sql = "SELECT COUNT($column) FROM {{table}}";
$rowCount = $connection->createCommand($sql)->queryScalar();
Copy after login

The above code $column will be converted to reference the appropriate column name, and {{table}} will be converted to reference the appropriate table name. The table name has a special variable {{%Y}}. If a table prefix is ​​set, use this variant to automatically add a prefix before the table name:

$sql = "SELECT COUNT($column) FROM {{%$table}}";
$rowCount = $connection->createCommand($sql)->queryScalar();
Copy after login

If the table prefix is ​​set as follows in the configuration file, the above code will query the results in the tbl_table table:

return [
  // ...
  'components' => [
    // ...
    'db' => [
      // ...
      'tablePrefix' => 'tbl_',
    ],
  ],
];
Copy after login

Another option for manually quoting table and column names is to use yiidbConnection::quoteTableName() and yiidbConnection::quoteColumnName():

$column = $connection->quoteColumnName($column);
$table = $connection->quoteTableName($table);
$sql = "SELECT COUNT($column) FROM $table";
$rowCount = $connection->createCommand($sql)->queryScalar();
Copy after login

Prepared statements

To safely pass query parameters, you can use preprocessing statements. First, you should use: placeholder, and then bind the variable to the corresponding placeholder:

$command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
$command->bindValue(':id', $_GET['id']);
$post = $command->query();
Copy after login

Another usage is to prepare a prepared statement once and execute multiple queries:

$command = $connection->createCommand('DELETE FROM post WHERE id=:id');
$command->bindParam(':id', $id);

$id = 1;
$command->execute();

$id = 2;
$command->execute();

Copy after login

Tip, it is more efficient to bind variables before execution and then change the value of the variable in each execution (generally used in loops).
Transactions

When you need to execute multiple related queries sequentially, you can encapsulate them into a transaction to protect data consistency. Yii provides a simple interface to implement transaction operations. Execute the SQL transaction query statement as follows:

$transaction = $connection->beginTransaction();
try {
  $connection->createCommand($sql1)->execute();
   $connection->createCommand($sql2)->execute();
  // ... 执行其他 SQL 语句 ...
  $transaction->commit();
} catch(Exception $e) {
  $transaction->rollBack();
}
Copy after login

We start a transaction through yiidbConnection::beginTransaction() and catch the exception through try catch. When the execution is successful, the transaction is submitted and ended through yiidbTransaction::commit(). When an exception occurs and the transaction fails, the transaction is performed through yiidbTransaction::rollBack(). Rollback.

You can also nest multiple transactions if necessary: ​​

// 外部事务
$transaction1 = $connection->beginTransaction();
try {
  $connection->createCommand($sql1)->execute();

  // 内部事务
  $transaction2 = $connection->beginTransaction();
  try {
    $connection->createCommand($sql2)->execute();
    $transaction2->commit();
  } catch (Exception $e) {
    $transaction2->rollBack();
  }

  $transaction1->commit();
} catch (Exception $e) {
  $transaction1->rollBack();
}

Copy after login

Note that the database you use must support Savepoints to execute correctly. The above code can be executed in all relational data, but security can only be guaranteed by supporting Savepoints.
Yii also supports setting isolation levels for transactions. When executing a transaction, the default isolation level of the database will be used. You can also specify the isolation level for things. Yii provides the following constants as commonly used isolation levels

  • yiidbTransaction::READ_UNCOMMITTED - allows reading changed uncommitted data, which may lead to dirty reads, non-repeatable reads and phantom reads
  • yiidbTransaction::READ_COMMITTED - allows concurrent transactions to be read after they are committed, which can avoid dirty reads, which may lead to repeated reads and phantom reads.
  • yiidbTransaction::REPEATABLE_READ - Multiple reads of the same field have consistent results, which can lead to phantom reads.
  • yiidbTransaction::SERIALIZABLE - Fully obeys the ACID principle to ensure that dirty reads, non-repeatable reads and phantom reads do not occur.

You can use the above constants or use a string command and execute the command in the corresponding database to set the isolation level. For example, the effective command for postgres is SERIALIZABLE READ ONLY DEFERRABLE.

注意:某些数据库只能针对连接来设置事务隔离级别,所以你必须要为连接明确制定隔离级别.目前受影响的数据库:MSSQL SQLite

注意:SQLite 只支持两种事务隔离级别,所以你只能设置READ UNCOMMITTED 和 SERIALIZABLE.使用其他隔离级别会抛出异常.

注意:PostgreSQL 不允许在事务开始前设置隔离级别,所以你不能在事务开始时指定隔离级别.你可以在事务开始之后调用yii\db\Transaction::setIsolationLevel() 来设置.
关于隔离级别[isolation levels]: http://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels

数据库复制和读写分离

很多数据库支持数据库复制 http://en.wikipedia.org/wiki/Replication_(computing)#Database_replication">database replication来提高可用性和响应速度. 在数据库复制中,数据总是从主服务器 到 从服务器. 所有的插入和更新等写操作在主服务器执行,而读操作在从服务器执行.

通过配置yii\db\Connection可以实现数据库复制和读写分离.

[
  'class' => 'yii\db\Connection',

  // 配置主服务器
  'dsn' => 'dsn for master server',
  'username' => 'master',
  'password' => '',

  // 配置从服务器
  'slaveConfig' => [
    'username' => 'slave',
    'password' => '',
    'attributes' => [
      // use a smaller connection timeout
      PDO::ATTR_TIMEOUT => 10,
    ],
  ],

  // 配置从服务器组
  'slaves' => [
    ['dsn' => 'dsn for slave server 1'],
    ['dsn' => 'dsn for slave server 2'],
    ['dsn' => 'dsn for slave server 3'],
    ['dsn' => 'dsn for slave server 4'],
  ],
]

Copy after login

以上的配置实现了一主多从的结构,从服务器用以执行读查询,主服务器执行写入查询,读写分离的功能由后台代码自动完成.调用者无须关心.例如:

// 使用以上配置创建数据库连接对象
$db = Yii::createObject($config);

// 通过从服务器执行查询操作
$rows = $db->createCommand('SELECT * FROM user LIMIT 10')->queryAll();

// 通过主服务器执行更新操作
$db->createCommand("UPDATE user SET username='demo' WHERE id=1")->execute();

Copy after login

注意:通过yii\db\Command::execute() 执行的查询被认为是写操作,所有使用yii\db\Command来执行的其他查询方法被认为是读操作.你可以通过$db->slave得到当前正在使用能够的从服务器.
Connection组件支持从服务器的负载均衡和故障转移,当第一次执行读查询时,会随即选择一个从服务器进行连接,如果连接失败则又选择另一个,如果所有从服务器都不可用,则会连接主服务器。你可以配置yii\db\Connection::serverStatusCache来记住那些不能连接的从服务器,使Yii 在一段时间[[yii\db\Connection::serverRetryInterval].内不会重复尝试连接那些根本不可用的从服务器.

注意:在上述配置中,每个从服务器连接超时时间被指定为10s. 如果在10s内不能连接,则被认为该服务器已经挂掉.你也可以自定义超时参数.
你也可以配置多主多从的结构,例如:

[
  'class' => 'yii\db\Connection',

  // 配置主服务器
  'masterConfig' => [
    'username' => 'master',
    'password' => '',
    'attributes' => [
      // use a smaller connection timeout
      PDO::ATTR_TIMEOUT => 10,
    ],
  ],

  // 配置主服务器组
  'masters' => [
    ['dsn' => 'dsn for master server 1'],
    ['dsn' => 'dsn for master server 2'],
  ],

  // 配置从服务器
  'slaveConfig' => [
    'username' => 'slave',
    'password' => '',
    'attributes' => [
      // use a smaller connection timeout
      PDO::ATTR_TIMEOUT => 10,
    ],
  ],

  // 配置从服务器组
  'slaves' => [
    ['dsn' => 'dsn for slave server 1'],
    ['dsn' => 'dsn for slave server 2'],
    ['dsn' => 'dsn for slave server 3'],
    ['dsn' => 'dsn for slave server 4'],
  ],
]

Copy after login

上述配置制定了2个主服务器和4个从服务器.Connection组件也支持主服务器的负载均衡和故障转移,与从服务器不同的是,如果所有主服务器都不可用,则会抛出异常.

注意:当你使用yii\db\Connection::masters来配置一个或多个主服务器时,Connection中关于数据库连接的其他属性(例如:dsn,username, password)都会被忽略.
事务默认使用主服务器的连接,并且在事务执行中的所有操作都会使用主服务器的连接,例如:

// 在主服务器连接上开始事务
$transaction = $db->beginTransaction();

try {
  // 所有的查询都在主服务器上执行
  $rows = $db->createCommand('SELECT * FROM user LIMIT 10')->queryAll();
  $db->createCommand("UPDATE user SET username='demo' WHERE id=1")->execute();

  $transaction->commit();
} catch(\Exception $e) {
  $transaction->rollBack();
  throw $e;
}

Copy after login

如果你想在从服务器上执行事务操作则必须要明确地指定,比如:

$transaction = $db->slave->beginTransaction();
Copy after login

有时你想强制使用主服务器来执行读查询,你可以调用seMaster()方法.

$rows = $db->useMaster(function ($db) {
  return $db->createCommand('SELECT * FROM user LIMIT 10')->queryAll();
});
Copy after login

你也可以设置$db->enableSlaves 为false来使所有查询都在主服务器上执行.

  • 操作数据库模式
  • 获得模式信息

你可以通过 yii\db\Schema实例来获取Schema信息:

$schema = $connection->getSchema();
Copy after login

该实例包括一系列方法来检索数据库多方面的信息:

$tables = $schema->getTableNames();
Copy after login

更多信息请参考yii\db\Schema

修改模式

除了基础的 SQL 查询,yii\db\Command还包括一系列方法来修改数据库模式:

  • 创建/重命名/删除/清空表
  • 增加/重命名/删除/修改字段
  • 增加/删除主键
  • 增加/删除外键
  • 创建/删除索引

使用示例:

// 创建表
$connection->createCommand()->createTable('post', [
  'id' => 'pk',
  'title' => 'string',
  'text' => 'text',
]);
Copy after login

完整参考请查看yii\db\Command.

SQL查询示例:

// find the customers whose primary key value is 10
$customers = Customer::findAll(10);
$customer = Customer::findOne(10);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => 10])->all();

// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findAll([10, 11, 12]);
$customers = Customer::find()->where(['IN','id',[10,11,12]])->all();

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();

// find customers whose age is 30 and whose status is 1
$customers = Customer::findAll(['age' => 30, 'status' => 1]);

// the above code is equivalent to:
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();

// use params binding
$customers = Customer::find()->where('age=:age AND status=:status')->addParams([':age'=>30,':status'=>1])->all();

// use index
$customers = Customer::find()->indexBy('id')->where(['age' => 30, 'status' => 1])->all();

// get customers count
$count = Customer::find()->where(['age' => 30, 'status' => 1])->count();

// add addition condition
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->andWhere('score > 100')->orderBy('id DESC')->offset(5)->limit(10)->all();

// find by sql
$customers = Customer::findBySql('SELECT * FROM customer WHERE age=30 AND status=1 AND score>100 ORDER BY id DESC LIMIT 5,10')->all();

Copy after login

修改:

// update status for customer-10
$customer = Customer::findOne(10);
$customer->status = 1;
$customer->update();

// the above code is equivalent to:
Customer::updateAll(['status' => 1], 'id = :id',[':id'=>10]);

Copy after login

删除:

// delete customer-10
Customer::findOne(10)->delete();

// the above code is equivalent to:
Customer::deleteAll(['status' => 1], 'id = :id',[':id'=>10]);

Copy after login

--------------------------------使用子查询------------------------------------------

$subQuery = (new Query())->select('COUNT(*)')->from('customer');

// SELECT `id`, (SELECT COUNT(*) FROM `customer`) AS `count` FROM `customer`
$query = (new Query())->select(['id', 'count' => $subQuery])->from('customer');

Copy after login

--------------------------------手写SQL-------------------------------------------

// select
$customers = Yii::$app->db->createCommand('SELECT * FROM customer')->queryAll();

// update
Yii::$app->db->createCommand()->update('customer',['status'=>1],'id=10')->execute();

// delete
Yii::$app->db->createCommand()->delete('customer','id=10')->execute();

//transaction
// outer 
$transaction1 = $connection->beginTransaction();
try {
  $connection->createCommand($sql1)->execute();

  // internal
  $transaction2 = $connection->beginTransaction();
  try {
    $connection->createCommand($sql2)->execute();
    $transaction2->commit();
  } catch (Exception $e) {
    $transaction2->rollBack();
  }

  $transaction1->commit();
} catch (Exception $e) {
  $transaction1->rollBack();
}

Copy after login

-----------------------------主从配置--------------------------------------------

[
  'class' => 'yii\db\Connection',

  // master 
  'dsn' => 'dsn for master server',
  'username' => 'master',
  'password' => '',

  // slaves
  'slaveConfig' => [
    'username' => 'slave',
    'password' => '',
    'attributes' => [
      // use a smaller connection timeout
      PDO::ATTR_TIMEOUT => 10,
    ],
  ],

  'slaves' => [
    ['dsn' => 'dsn for slave server 1'],
    ['dsn' => 'dsn for slave server 2'],
    ['dsn' => 'dsn for slave server 3'],
    ['dsn' => 'dsn for slave server 4'],
  ],
]

Copy after login

您可能感兴趣的文章:

  • PHP的Yii框架中移除组件所绑定的行为的方法
  • PHP的Yii框架中行为的定义与绑定方法讲解
  • 详解在PHP的Yii框架中使用行为Behaviors的方法
  • 深入讲解PHP的Yii框架中的属性(Property)
  • 深入解析PHP的Yii框架中的event事件机制
  • 全面解读PHP的Yii框架中的日志功能
  • Yii使用find findAll查找出指定字段的实现方法
  • 解析yii数据库的增删查改
  • Yii PHP Framework实用入门教程(详细介绍)
  • 详解PHP的Yii框架中组件行为的属性注入和方法注入

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1111911.htmlTechArticleUsing database configuration and SQL operation example tutorial in PHP's Yii framework, yii example tutorial database access (DAO) Yii Contains a data access layer (DAO) built on top of PHP PDO. DAO is...
Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template