database-basics.md 8.73 KB
Newer Older
1 2 3
Database basics
===============

4
Yii has a database access layer built on top of PHP's [PDO](http://www.php.net/manual/en/book.pdo.php). It provides
5 6 7
uniform API and solves some inconsistencies between different DBMS. By default Yii supports the following DBMS:

- [MySQL](http://www.mysql.com/)
8
- [MariaDB](https://mariadb.com/)
9 10
- [SQLite](http://sqlite.org/)
- [PostgreSQL](http://www.postgresql.org/)
Qiang Xue committed
11
- [CUBRID](http://www.cubrid.org/): version 9.1.0 or higher.
12
- [Oracle](http://www.oracle.com/us/products/database/overview/index.html)
Qiang Xue committed
13 14
- [MSSQL](https://www.microsoft.com/en-us/sqlserver/default.aspx): version 2012 or above is required if you
  want to use LIMIT/OFFSET.
15

16

17 18 19 20 21 22 23
Configuration
-------------

In order to start using database you need to configure database connection component first by adding `db` component
to application configuration (for "basic" web application it's `config/web.php`) like the following:

```php
Alexander Makarov committed
24
return [
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    // ...
    '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',
        ],
    ],
    // ...
Alexander Makarov committed
44
];
45
```
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60
There is a peculiarity when you want to work with the database through the `ODBC` layer. When using `ODBC`,
connection `DSN` doesn't indicate uniquely what database type is being used. That's why you have to override
`driverName` property of [[yii\db\Connection]] class to disambiguate that:

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

61 62
Please refer to the [PHP manual](http://www.php.net/manual/en/function.PDO-construct.php) for more details
on the format of the DSN string.
63

64
After the connection component is configured you can access it using the following syntax:
65 66 67 68 69

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

70
You can refer to [[yii\db\Connection]] for a list of properties you can configure. Also note that you can define more
71
than one connection component and use both at the same time if needed:
72 73 74 75 76 77

```php
$primaryConnection = \Yii::$app->db;
$secondaryConnection = \Yii::$app->secondDb;
```

78
If you don't want to define the connection as an application component you can instantiate it directly:
79 80

```php
Alexander Makarov committed
81
$connection = new \yii\db\Connection([
82 83 84
    'dsn' => $dsn,
     'username' => $username,
     'password' => $password,
Alexander Makarov committed
85
]);
86 87 88
$connection->open();
```

89

90 91 92 93 94
> **Tip**: if you need to execute additional SQL queries right after establishing a connection you can add the
> following to your application configuration file:
>
```php
return [
95 96 97 98 99 100 101 102 103 104 105 106
    // ...
    'components' => [
        // ...
        'db' => [
            'class' => 'yii\db\Connection',
            // ...
            'on afterOpen' => function($event) {
                $event->sender->createCommand("SET time_zone = 'UTC'")->execute();
            }
        ],
    ],
    // ...
107 108 109
];
```

110 111 112
Basic SQL queries
-----------------

113
Once you have a connection instance you can execute SQL queries using [[yii\db\Command]].
114 115 116 117 118 119

### SELECT

When query returns a set of rows:

```php
120
$command = $connection->createCommand('SELECT * FROM post');
121 122 123 124 125 126
$posts = $command->queryAll();
```

When only a single row is returned:

```php
127
$command = $connection->createCommand('SELECT * FROM post WHERE id=1');
128
$post = $command->queryOne();
129 130 131 132 133
```

When there are multiple values from the same column:

```php
134
$command = $connection->createCommand('SELECT title FROM post');
135 136 137 138 139 140
$titles = $command->queryColumn();
```

When there's a scalar value:

```php
141
$command = $connection->createCommand('SELECT COUNT(*) FROM post');
142 143 144 145 146 147 148 149
$postCount = $command->queryScalar();
```

### UPDATE, INSERT, DELETE etc.

If SQL executed doesn't return any data you can use command's `execute` method:

```php
150
$command = $connection->createCommand('UPDATE post SET status=1 WHERE id=1');
151 152 153
$command->execute();
```

154
Alternatively the following syntax that takes care of proper table and column names quoting is possible:
155 156 157

```php
// INSERT
158
$connection->createCommand()->insert('user', [
159 160
    'name' => 'Sam',
    'age' => 30,
Alexander Makarov committed
161
])->execute();
162 163

// INSERT multiple rows at once
164
$connection->createCommand()->batchInsert('user', ['name', 'age'], [
165 166 167
    ['Tom', 30],
    ['Jane', 20],
    ['Linda', 25],
Alexander Makarov committed
168
])->execute();
169 170

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

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

177 178 179
Quoting table and column names
------------------------------

180
Most of the time you would use the following syntax for quoting table and column names:
181 182

```php
183
$sql = "SELECT COUNT([[$column]]) FROM {{$table}}";
184 185 186
$rowCount = $connection->createCommand($sql)->queryScalar();
```

187
In the code above `[[X]]` will be converted to properly quoted column name while `{{Y}}` will be converted to properly
188 189
quoted table name.

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
For table names there's a special variant `{{%Y}}` that allows you to automatically appending table prefix if it is set:

```php
$sql = "SELECT COUNT([[$column]]) FROM {{%$table}}";
$rowCount = $connection->createCommand($sql)->queryScalar();
```

The code above will result in selecting from `tbl_table` if you have table prefix configured like the following in your
config file:

```php
return [
    // ...
    'components' => [
        // ...
        'db' => [
            // ...
            'tablePrefix' => 'tbl_',
        ],
    ],
];
```

213 214
The alternative is to quote table and column names manually using [[yii\db\Connection::quoteTableName()]] and
[[yii\db\Connection::quoteColumnName()]]:
215 216 217 218 219 220 221

```php
$column = $connection->quoteColumnName($column);
$table = $connection->quoteTableName($table);
$sql = "SELECT COUNT($column) FROM $table";
$rowCount = $connection->createCommand($sql)->queryScalar();
```
222 223 224 225 226 227 228

Prepared statements
-------------------

In order to securely pass query parameters you can use prepared statements:

```php
229
$command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
230 231 232 233 234 235 236
$command->bindValue(':id', $_GET['id']);
$post = $command->query();
```

Another usage is performing a query multiple times while preparing it only once:

```php
237
$command = $connection->createCommand('DELETE FROM post WHERE id=:id');
238 239 240 241 242 243 244 245 246 247 248 249
$command->bindParam(':id', $id);

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

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

Transactions
------------

250
You can perform transactional SQL queries like the following:
251 252 253 254

```php
$transaction = $connection->beginTransaction();
try {
255 256 257 258
    $connection->createCommand($sql1)->execute();
     $connection->createCommand($sql2)->execute();
    // ... executing other SQL statements ...
    $transaction->commit();
259
} catch(Exception $e) {
260
    $transaction->rollBack();
261 262 263
}
```

264 265 266 267 268 269
You can also nest multiple transactions, if needed:

```php
// outer transaction
$transaction1 = $connection->beginTransaction();
try {
270 271 272 273 274 275 276 277 278 279 280 281
    $connection->createCommand($sql1)->execute();

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

    $transaction1->commit();
282
} catch (Exception $e) {
283
    $transaction1->rollBack();
284 285 286 287
}
```


288 289 290 291 292
Working with database schema
----------------------------

### Getting schema information

293
You can get a [[yii\db\Schema]] instance like the following:
294 295 296 297 298 299 300 301 302 303 304

```php
$schema = $connection->getSchema();
```

It contains a set of methods allowing you to retrieve various information about the database:

```php
$tables = $schema->getTableNames();
```

305
For the full reference check [[yii\db\Schema]].
306 307 308

### Modifying schema

309
Aside from basic SQL queries [[yii\db\Command]] contains a set of methods allowing to modify database schema:
310 311 312 313 314 315 316 317 318 319

- createTable, renameTable, dropTable, truncateTable
- addColumn, renameColumn, dropColumn, alterColumn
- addPrimaryKey, dropPrimaryKey
- addForeignKey, dropForeignKey
- createIndex, dropIndex

These can be used as follows:

```php
320
// CREATE TABLE
321
$connection->createCommand()->createTable('post', [
322 323 324
    'id' => 'pk',
    'title' => 'string',
    'text' => 'text',
Alexander Makarov committed
325
]);
326 327
```

328
For the full reference check [[yii\db\Command]].