• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

Dialect/H03-May-2022-974521

Driver/H03-May-2022-802428

Exception/H03-May-2022-12634

Expression/H03-May-2022-2,7781,256

Log/H03-May-2022-313120

Retry/H03-May-2022-12356

Schema/H03-May-2022-4,1042,360

Statement/H03-May-2022-1,109414

Type/H03-May-2022-2,073864

Connection.phpH A D23-Oct-202128.6 KiB1,020480

Driver.phpH A D23-Oct-202110.5 KiB469221

DriverInterface.phpH A D23-Oct-20217 KiB26035

Exception.phpH A D23-Oct-2021760 256

ExpressionInterface.phpH A D23-Oct-20211.3 KiB417

FieldTypeConverter.phpH A D23-Oct-20214.5 KiB14768

FunctionsBuilder.phpH A D23-Oct-202111.7 KiB318125

IdentifierQuoter.phpH A D23-Oct-20217.5 KiB264139

Query.phpH A D23-Oct-202178 KiB2,363771

QueryCompiler.phpH A D23-Oct-202113.8 KiB393190

README.mdH A D23-Oct-202110.5 KiB365271

SchemaCache.phpH A D23-Oct-20213.5 KiB11550

SqlDialectTrait.phpH A D23-Oct-20219.5 KiB300149

SqliteCompiler.phpH A D23-Oct-2021911 326

SqlserverCompiler.phpH A D23-Oct-20212.7 KiB9538

StatementInterface.phpH A D23-Oct-20216.1 KiB19420

Type.phpH A D23-Oct-202111 KiB382186

TypeConverterTrait.phpH A D23-Oct-20212 KiB6425

TypeInterface.phpH A D23-Oct-20213.2 KiB9012

TypeMap.phpH A D23-Oct-20216.5 KiB23269

TypeMapTrait.phpH A D23-Oct-20213.6 KiB12949

TypedResultInterface.phpH A D23-Oct-20211.1 KiB356

TypedResultTrait.phpH A D23-Oct-20212 KiB7527

ValueBinder.phpH A D23-Oct-20214.3 KiB15058

composer.jsonH A D23-Oct-20211 KiB3938

README.md

1[![Total Downloads](https://img.shields.io/packagist/dt/cakephp/database.svg?style=flat-square)](https://packagist.org/packages/cakephp/database)
2[![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](LICENSE.txt)
3
4# A flexible and lightweight Database Library for PHP
5
6This library abstracts and provides help with most aspects of dealing with relational
7databases such as keeping connections to the server, building queries,
8preventing SQL injections, inspecting and altering schemas, and with debugging and
9profiling queries sent to the database.
10
11It adopts the API from the native PDO extension in PHP for familiarity, but solves many of the
12inconsistencies PDO has, while also providing several features that extend PDO's capabilities.
13
14A distinguishing factor of this library when compared to similar database connection packages,
15is that it takes the concept of "data types" to its core. It lets you work with complex PHP objects
16or structures that can be passed as query conditions or to be inserted in the database.
17
18The typing system will intelligently convert the PHP structures when passing them to the database, and
19convert them back when retrieving.
20
21
22## Connecting to the database
23
24This library is able to work with the following databases:
25
26* MySQL
27* Postgres
28* SQLite
29* Microsoft SQL Server (2008 and above)
30
31The first thing you need to do when using this library is create a connection object.
32Before performing any operations with the connection, you need to specify a driver
33to use:
34
35```php
36use Cake\Database\Connection;
37use Cake\Database\Driver\Mysql;
38
39$driver = new Mysql([
40	'database' => 'test',
41	'username' => 'root',
42	'password' => 'secret'
43]);
44$connection = new Connection([
45	'driver' => $driver
46]);
47```
48
49Drivers are classes responsible for actually executing the commands to the database and
50correctly building the SQL according to the database specific dialect. Drivers can also
51be specified by passing a class name. In that case, include all the connection details
52directly in the options array:
53
54```php
55use Cake\Database\Connection;
56
57$connection = new Connection([
58	'driver' => 'Cake\Database\Driver\Sqlite',
59	'database' => '/path/to/file.db'
60]);
61```
62
63### Connection options
64
65This is a list of possible options that can be passed when creating a connection:
66
67* `persistent`: Creates a persistent connection
68* `host`: The server host
69* `database`: The database name
70* `username`: Login credential
71* `password`: Connection secret
72* `encoding`: The connection encoding (or charset)
73* `timezone`: The connection timezone or time offset
74
75## Using connections
76
77After creating a connection, you can immediately interact with the database. You can choose
78either to use the shorthand methods `execute()`, `insert()`, `update()`, `delete()` or use the
79`newQuery()` for using a query builder.
80
81The easiest way of executing queries is by using the `execute()` method, it will return a
82`Cake\Database\StatementInterface` that you can use to get the data back:
83
84```php
85$statement = $connection->execute('SELECT * FROM articles');
86
87while($row = $statement->fetch('assoc')) {
88	echo $row['title'] . PHP_EOL;
89}
90```
91Binding values to parametrized arguments is also possible with the execute function:
92
93```php
94$statement = $connection->execute('SELECT * FROM articles WHERE id = :id', ['id' => 1], ['id' => 'integer']);
95$results = $statement->fetch('assoc');
96```
97
98The third parameter is the types the passed values should be converted to when passed to the database. If
99no types are passed, all arguments will be interpreted as a string.
100
101Alternatively you can construct a statement manually and then fetch rows from it:
102
103```php
104$statement = $connection->prepare('SELECT * from articles WHERE id != :id');
105$statement->bind(['id' => 1], ['id' => 'integer']);
106$results = $statement->fetchAll('assoc');
107```
108
109The default types that are understood by this library and can be passed to the `bind()` function or to `execute()`
110are:
111
112* biginteger
113* binary
114* date
115* float
116* decimal
117* integer
118* time
119* datetime
120* timestamp
121* uuid
122
123More types can be added dynamically in a bit.
124
125Statements can be reused by binding new values to the parameters in the query:
126
127```php
128$statement = $connection->prepare('SELECT * from articles WHERE id = :id');
129$statement->bind(['id' => 1], ['id' => 'integer']);
130$results = $statement->fetchAll('assoc');
131
132$statement->bind(['id' => 1], ['id' => 'integer']);
133$results = $statement->fetchAll('assoc');
134```
135
136### Updating Rows
137
138Updating can be done using the `update()` function in the connection object. In the following
139example we will update the title of the article with id = 1:
140
141```php
142$connection->update('articles', ['title' => 'New title'], ['id' => 1]);
143```
144
145The concept of data types is central to this library, so you can use the last parameter of the function
146to specify what types should be used:
147
148```php
149$connection->update(
150	'articles',
151	['title' => 'New title'],
152	['created >=' => new DateTime('-3 day'), 'created <' => new DateTime('now')],
153	['created' => 'datetime']
154);
155```
156
157The example above will execute the following SQL:
158
159```sql
160UPDATE articles SET title = 'New Title' WHERE created >= '2014-10-10 00:00:00' AND created < '2014-10-13 00:00:00';
161```
162
163More on creating complex where conditions or more complex update queries later.
164
165### Deleting Rows
166
167Similarly, the `delete()` method is used to delete rows from the database:
168
169```php
170$connection->delete('articles', ['created <' => DateTime('now')], ['created' => 'date']);
171```
172
173Will generate the following SQL
174
175```sql
176DELETE FROM articles where created < '2014-10-10'
177```
178
179### Inserting Rows
180
181Rows can be inserted using the `insert()` method:
182
183```php
184$connection->insert(
185	'articles',
186	['title' => 'My Title', 'body' => 'Some paragraph', 'created' => new DateTime()],
187	['created' => 'datetime']
188);
189```
190
191More complex updates, deletes and insert queries can be generated using the `Query` class.
192
193## Query Builder
194
195One of the goals of this library is to allow the generation of both simple and complex queries with
196ease. The query builder can be accessed by getting a new instance of a query:
197
198```php
199$query = $connection->newQuery();
200```
201
202### Selecting Fields
203
204Adding fields to the `SELECT` clause:
205
206```php
207$query->select(['id', 'title', 'body']);
208
209// Results in SELECT id AS pk, title AS aliased_title, body ...
210$query->select(['pk' => 'id', 'aliased_title' => 'title', 'body']);
211
212// Use a closure
213$query->select(function ($query) {
214	return ['id', 'title', 'body'];
215});
216```
217
218### Where Conditions
219
220Generating conditions:
221
222```php
223// WHERE id = 1
224$query->where(['id' => 1]);
225
226// WHERE id > 2
227$query->where(['id >' => 1]);
228```
229
230As you can see you can use any operator by placing it with a space after the field name.
231Adding multiple conditions is easy as well:
232
233```php
234$query->where(['id >' => 1])->andWhere(['title' => 'My Title']);
235
236// Equivalent to
237$query->where(['id >' => 1, 'title' => 'My title']);
238```
239
240It is possible to generate `OR` conditions as well
241
242```php
243$query->where(['OR' => ['id >' => 1, 'title' => 'My title']]);
244```
245
246For even more complex conditions you can use closures and expression objects:
247
248```php
249$query->where(function ($exp) {
250        return $exp
251            ->eq('author_id', 2)
252            ->eq('published', true)
253            ->notEq('spam', true)
254            ->gt('view_count', 10);
255    });
256```
257
258Which results in:
259
260```sql
261SELECT * FROM articles
262WHERE
263	author_id = 2
264	AND published = 1
265	AND spam != 1
266	AND view_count > 10
267```
268
269Combining expressions is also possible:
270
271```php
272$query->where(function ($exp) {
273        $orConditions = $exp->or(['author_id' => 2])
274            ->eq('author_id', 5);
275        return $exp
276            ->not($orConditions)
277            ->lte('view_count', 10);
278    });
279```
280
281That generates:
282
283```sql
284SELECT *
285FROM articles
286WHERE
287	NOT (author_id = 2 OR author_id = 5)
288	AND view_count <= 10
289```
290
291When using the expression objects you can use the following methods to create conditions:
292
293* `eq()` Creates an equality condition.
294* `notEq()` Create an inequality condition
295* `like()` Create a condition using the LIKE operator.
296* `notLike()` Create a negated LIKE condition.
297* `in()` Create a condition using IN.
298* `notIn()` Create a negated condition using IN.
299* `gt()` Create a > condition.
300* `gte()` Create a >= condition.
301* `lt()` Create a < condition.
302* `lte()` Create a <= condition.
303* `isNull()` Create an IS NULL condition.
304* `isNotNull()` Create a negated IS NULL condition.
305
306### Aggregates and SQL Functions
307
308```php
309// Results in SELECT COUNT(*) count FROM ...
310$query->select(['count' => $query->func()->count('*')]);
311```
312
313A number of commonly used functions can be created with the func() method:
314
315* `sum()` Calculate a sum. The arguments will be treated as literal values.
316* `avg()` Calculate an average. The arguments will be treated as literal values.
317* `min()` Calculate the min of a column. The arguments will be treated as literal values.
318* `max()` Calculate the max of a column. The arguments will be treated as literal values.
319* `count()` Calculate the count. The arguments will be treated as literal values.
320* `concat()` Concatenate two values together. The arguments are treated as bound parameters unless marked as literal.
321* `coalesce()` Coalesce values. The arguments are treated as bound parameters unless marked as literal.
322* `dateDiff()` Get the difference between two dates/times. The arguments are treated as bound parameters unless marked as literal.
323* `now()` Take either 'time' or 'date' as an argument allowing you to get either the current time, or current date.
324
325When providing arguments for SQL functions, there are two kinds of parameters you can use, literal arguments and bound parameters. Literal
326parameters allow you to reference columns or other SQL literals. Bound parameters can be used to safely add user data to SQL functions.
327For example:
328
329```php
330$concat = $query->func()->concat([
331    'title' => 'literal',
332    ' NEW'
333]);
334$query->select(['title' => $concat]);
335```
336
337The above generates:
338
339```sql
340SELECT CONCAT(title, :c0) ...;
341```
342
343### Other SQL Clauses
344
345Read of all other SQL clauses that the builder is capable of generating in the [official API docs](https://api.cakephp.org/3.x/class-Cake.Database.Query.html)
346
347### Getting Results out of a Query
348
349Once you’ve made your query, you’ll want to retrieve rows from it. There are a few ways of doing this:
350
351```php
352// Iterate the query
353foreach ($query as $row) {
354    // Do stuff.
355}
356
357// Get the statement and fetch all results
358$results = $query->execute()->fetchAll('assoc');
359```
360
361## Official API
362
363You can read the official [official API docs](https://api.cakephp.org/3.x/namespace-Cake.Database.html) to learn more of what this library
364has to offer.
365