[![Total Downloads](https://img.shields.io/packagist/dt/cakephp/database.svg?style=flat-square)](https://packagist.org/packages/cakephp/database)
[![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](LICENSE.txt)
# A flexible and lightweight Database Library for PHP
This library abstracts and provides help with most aspects of dealing with relational
databases such as keeping connections to the server, building queries,
preventing SQL injections, inspecting and altering schemas, and with debugging and
profiling queries sent to the database.
It adopts the API from the native PDO extension in PHP for familiarity, but solves many of the
inconsistencies PDO has, while also providing several features that extend PDO's capabilities.
A distinguishing factor of this library when compared to similar database connection packages,
is that it takes the concept of "data types" to its core. It lets you work with complex PHP objects
or structures that can be passed as query conditions or to be inserted in the database.
The typing system will intelligently convert the PHP structures when passing them to the database, and
convert them back when retrieving.
## Connecting to the database
This library is able to work with the following databases:
* MySQL
* Postgres
* SQLite
* Microsoft SQL Server (2008 and above)
The first thing you need to do when using this library is create a connection object.
Before performing any operations with the connection, you need to specify a driver
to use:
```php
use Cake\Database\Connection;
use Cake\Database\Driver\Mysql;
$driver = new Mysql([
'database' => 'test',
'username' => 'root',
'password' => 'secret'
]);
$connection = new Connection([
'driver' => $driver
]);
```
Drivers are classes responsible for actually executing the commands to the database and
correctly building the SQL according to the database specific dialect. Drivers can also
be specified by passing a class name. In that case, include all the connection details
directly in the options array:
```php
use Cake\Database\Connection;
$connection = new Connection([
'driver' => Cake\Database\Driver\Sqlite::class,
'database' => '/path/to/file.db'
]);
```
### Connection options
This is a list of possible options that can be passed when creating a connection:
* `persistent`: Creates a persistent connection
* `host`: The server host
* `database`: The database name
* `username`: Login credential
* `password`: Connection secret
* `encoding`: The connection encoding (or charset)
* `timezone`: The connection timezone or time offset
## Using connections
After creating a connection, you can immediately interact with the database. You can choose
either to use the shorthand methods `execute()`, `insert()`, `update()`, `delete()` or use the
`newQuery()` for using a query builder.
The easiest way of executing queries is by using the `execute()` method, it will return a
`Cake\Database\StatementInterface` that you can use to get the data back:
```php
$statement = $connection->execute('SELECT * FROM articles');
while($row = $statement->fetch('assoc')) {
echo $row['title'] . PHP_EOL;
}
```
Binding values to parametrized arguments is also possible with the execute function:
```php
$statement = $connection->execute('SELECT * FROM articles WHERE id = :id', ['id' => 1], ['id' => 'integer']);
$results = $statement->fetch('assoc');
```
The third parameter is the types the passed values should be converted to when passed to the database. If
no types are passed, all arguments will be interpreted as a string.
Alternatively you can construct a statement manually and then fetch rows from it:
```php
$statement = $connection->prepare('SELECT * from articles WHERE id != :id');
$statement->bind(['id' => 1], ['id' => 'integer']);
$results = $statement->fetchAll('assoc');
```
The default types that are understood by this library and can be passed to the `bind()` function or to `execute()`
are:
* biginteger
* binary
* date
* float
* decimal
* integer
* time
* datetime
* timestamp
* uuid
More types can be added dynamically in a bit.
Statements can be reused by binding new values to the parameters in the query:
```php
$statement = $connection->prepare('SELECT * from articles WHERE id = :id');
$statement->bind(['id' => 1], ['id' => 'integer']);
$results = $statement->fetchAll('assoc');
$statement->bind(['id' => 1], ['id' => 'integer']);
$results = $statement->fetchAll('assoc');
```
### Updating Rows
Updating can be done using the `update()` function in the connection object. In the following
example we will update the title of the article with id = 1:
```php
$connection->update('articles', ['title' => 'New title'], ['id' => 1]);
```
The concept of data types is central to this library, so you can use the last parameter of the function
to specify what types should be used:
```php
$connection->update(
'articles',
['title' => 'New title'],
['created >=' => new DateTime('-3 day'), 'created <' => new DateTime('now')],
['created' => 'datetime']
);
```
The example above will execute the following SQL:
```sql
UPDATE articles SET title = 'New Title' WHERE created >= '2014-10-10 00:00:00' AND created < '2014-10-13 00:00:00';
```
More on creating complex where conditions or more complex update queries later.
### Deleting Rows
Similarly, the `delete()` method is used to delete rows from the database:
```php
$connection->delete('articles', ['created <' => DateTime('now')], ['created' => 'date']);
```
Will generate the following SQL
```sql
DELETE FROM articles where created < '2014-10-10'
```
### Inserting Rows
Rows can be inserted using the `insert()` method:
```php
$connection->insert(
'articles',
['title' => 'My Title', 'body' => 'Some paragraph', 'created' => new DateTime()],
['created' => 'datetime']
);
```
More complex updates, deletes and insert queries can be generated using the `Query` class.
## Query Builder
One of the goals of this library is to allow the generation of both simple and complex queries with
ease. The query builder can be accessed by getting a new instance of a query:
```php
$query = $connection->newQuery();
```
### Selecting Fields
Adding fields to the `SELECT` clause:
```php
$query->select(['id', 'title', 'body']);
// Results in SELECT id AS pk, title AS aliased_title, body ...
$query->select(['pk' => 'id', 'aliased_title' => 'title', 'body']);
// Use a closure
$query->select(function ($query) {
return ['id', 'title', 'body'];
});
```
### Where Conditions
Generating conditions:
```php
// WHERE id = 1
$query->where(['id' => 1]);
// WHERE id > 2
$query->where(['id >' => 1]);
```
As you can see you can use any operator by placing it with a space after the field name.
Adding multiple conditions is easy as well:
```php
$query->where(['id >' => 1])->andWhere(['title' => 'My Title']);
// Equivalent to
$query->where(['id >' => 1, 'title' => 'My title']);
```
It is possible to generate `OR` conditions as well
```php
$query->where(['OR' => ['id >' => 1, 'title' => 'My title']]);
```
For even more complex conditions you can use closures and expression objects:
```php
$query->where(function ($exp) {
return $exp
->eq('author_id', 2)
->eq('published', true)
->notEq('spam', true)
->gt('view_count', 10);
});
```
Which results in:
```sql
SELECT * FROM articles
WHERE
author_id = 2
AND published = 1
AND spam != 1
AND view_count > 10
```
Combining expressions is also possible:
```php
$query->where(function ($exp) {
$orConditions = $exp->or(['author_id' => 2])
->eq('author_id', 5);
return $exp
->not($orConditions)
->lte('view_count', 10);
});
```
That generates:
```sql
SELECT *
FROM articles
WHERE
NOT (author_id = 2 OR author_id = 5)
AND view_count <= 10
```
When using the expression objects you can use the following methods to create conditions:
* `eq()` Creates an equality condition.
没有合适的资源?快使用搜索试试~ 我知道了~
CakePHP(PHP快速开发框架) v4.2.6 最新版
共780个文件
php:722个
md:17个
txt:16个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 152 浏览量
2023-11-03
23:28:31
上传
评论
收藏 1.41MB ZIP 举报
温馨提示
Cakephp是一款专用于php开发的编程工具,能够为强悍的程序员们提供更加方便的编程服务,让他们能够对php框架快发拥有更多的想法 CakePHP软件简介: CakePHP是一个用来开发php的框架,目前已经更新到了3.6.8版本,这是一个机遇MVC的php开发框,可以帮助编程人员快速开发作品,信息全面,使用方面
资源推荐
资源详情
资源评论
收起资源包目录
CakePHP(PHP快速开发框架) v4.2.6 最新版 (780个子文件)
sample.a68 409B
dumpHeader.html 7KB
sample.html 405B
composer.json 4KB
composer.json 1KB
composer.json 1KB
composer.json 1KB
composer.json 1KB
composer.json 1KB
composer.json 1KB
composer.json 1KB
composer.json 1KB
composer.json 1KB
composer.json 982B
composer.json 970B
composer.json 956B
composer.json 919B
composer.json 906B
composer.json 833B
LICENSE 1KB
README.md 10KB
README.md 7KB
README.md 5KB
README.md 3KB
README.md 3KB
README.md 3KB
README.md 3KB
README.md 2KB
README.md 2KB
README.md 2KB
README.md 2KB
README.md 1KB
README.md 1KB
SECURITY.md 1KB
README.md 1KB
README.md 1KB
README.md 1KB
Table.php 107KB
Validator.php 100KB
FormHelper.php 91KB
Query.php 77KB
Validation.php 60KB
ServerRequest.php 55KB
Message.php 51KB
BelongsToMany.php 51KB
View.php 50KB
Response.php 49KB
Query.php 46KB
PaginatorHelper.php 45KB
IntegrationTestTrait.php 45KB
Hash.php 42KB
CollectionInterface.php 42KB
Text.php 40KB
Association.php 40KB
HtmlHelper.php 38KB
Debugger.php 37KB
RouteBuilder.php 36KB
TreeBehavior.php 36KB
TestCase.php 34KB
EntityTrait.php 34KB
Router.php 33KB
AuthComponent.php 33KB
Marshaller.php 33KB
EagerLoader.php 31KB
Folder.php 30KB
I18nExtractCommand.php 30KB
ConsoleOptionParser.php 30KB
QueryExpression.php 29KB
Shell.php 29KB
Route.php 28KB
CollectionTrait.php 28KB
Controller.php 27KB
Connection.php 27KB
Client.php 23KB
HasMany.php 23KB
EntityContext.php 23KB
PostgresSchemaDialect.php 22KB
SqlserverSchemaDialect.php 22KB
Paginator.php 22KB
MysqlSchemaDialect.php 21KB
ConsoleIo.php 21KB
Cookie.php 21KB
SecurityComponent.php 20KB
ShadowTableStrategy.php 20KB
Cache.php 20KB
Session.php 20KB
SqliteSchemaDialect.php 19KB
TableSchema.php 19KB
QueryTrait.php 19KB
Mailer.php 18KB
FormProtector.php 18KB
RequestHandlerComponent.php 18KB
SelectLoader.php 18KB
Log.php 17KB
EavStrategy.php 17KB
File.php 17KB
FixtureManager.php 17KB
Number.php 17KB
Inflector.php 17KB
MemcachedEngine.php 17KB
共 780 条
- 1
- 2
- 3
- 4
- 5
- 6
- 8
资源评论
DNCS高级工程师
- 粉丝: 761
- 资源: 551
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功