haukurh / dbal
简单且轻量级的数据库抽象层
v1.0.0
2020-04-27 23:49 UTC
Requires (Dev)
- phpunit/phpunit: ^9.1
This package is auto-updated.
Last update: 2024-09-28 09:53:36 UTC
README
这是一个简单且轻量级的数据库抽象层,它提供了一个 API 用于基本的 CRUD 操作,但可以随意扩展以适应各种场景。
安装
在项目中实现 haukurh/dbal
最简单的方式是使用 composer 来要求它。
composer require haukurh/dbal
初始化
初始化数据库连接。
<?php require_once 'vendor/autoload.php'; use Haukurh\DBAL\DB; use Haukurh\DBAL\DSN\DSN; $db = new DB( DSN::mysql( 'example_db', 'localhost', 3306, 'UTF8' ), 'username', 'password', );
基本用法
如前所述,DB 类提供了一些最基本的 CURD 操作,这些操作易于阅读和编写。
<?php $contents = [ 'title' => 'Lorem ipsum dolor sit', 'content' => 'Pellentesque rhoncus dui vitae tincidunt pulvinar...' ]; // Insert a record to the database $db->insert('articles', $contents); // Fetch all articles in descending order $articles = $db->fetchAll('articles', 'ORDER BY id DESC'); // Fetch the next row from a result set $article = $db->fetch('articles'); // Update records $db->update('articles', [ 'title' => 'Updated title', ], 'WHERE id = :id', [':id' => 3]);
命名参数
如果 SQL 查询的动态参数没有正确实现,可能会很危险,DB 类内置了对预处理语句中命名参数的支持。这可以绕过,但并不明智。
使用命名参数的示例
<?php $articles = $db->fetchAll('articles', 'WHERE id >= :id and title like :term', [ ':id' => 10, ':term' => '%ipsum%', ]);
如何 不 实现的示例
<?php $id = 10; $term = '%ipsum%'; $articles = $db->fetchAll('articles', "WHERE id >= {$id} and title like {$term}");