pixxel/dbal

一个简单的PDO包装器/DBAL,语法比pdo更简单

1.1.2 2022-08-02 08:58 UTC

This package is auto-updated.

Last update: 2024-09-30 02:10:36 UTC


README

这是一个简单的PDO包装器,因为我们讨厌它的语法,所以决定用简单的类来简化它。也许我们将来会扩展它,但现在它已经实现了预期的功能(而且目前只支持mysql,但将来会改变)。

安装

一个简单的示例,用于从名为pages的表中读取(手动安装/无composer)

require_once(__DIR__.'/Pixxel/Dbal.php');

$dbal = new \Pixxel\Dbal('dbusername', 'dbpassword', 'dbname');
$pages = $dbal->read('select * from `pages` limit 20 order by `id` desc');

使用composer安装和使用的相同示例

在终端(在所需目录中):composer require pixxel/dbal

然后,在那个目录中,创建一个php文件并使用以下代码

require_once(__DIR__.'/vendor/autoload.php');

$dbal = new \Pixxel\Dbal('dbusername', 'dbpassword', 'dbname');
$pages = $dbal->read('select * from `pages` limit 20 order by `id` desc');

如你所见,它主要是普通的SQL,但没有围绕pdo连接字符串和语句等易忘的东西。请注意,我们始终使用预处理语句,所以请确保您使用其最大优势,例如,将可能受攻击的内容作为参数传递

$singlePage = $dbal->read('select * from `pages` where `id` = :id', [':id' => 5]);

这样,您在传递用户可控的参数时就不必担心SQL注入。以下是您可以使用此类执行的一些简要操作:

1.) 创建PDO连接

$dbal = new \Pixxel\Dbal('dbusername', 'dbpassword', 'dbname');

2.) 选择数据

$pages = $dbal->read('select * from `pages` limit 20 order by `id` desc');          // Return array containing objects
$pages = $dbal->readSingle('select * from `pages` limit 1 order by `id` desc');     // Return a single object, regardless of how many rows the query returns

3.) 插入、更新或删除数据

$dbal->save('insert into `pages` (`title`, `content`) values (:title, :content)', [':title' => 'New page', ':content' => '<h1>Title</h1><p>My content</p>']);

4.) 获取最后插入行的ID

$dbal->lastInsertId();

5.) 获取最后的SQL错误(用于调试目的)

$dbal->lastError();

6.) 获取最后执行的查询(或尝试执行的)

$dbal->lastQuery();

这就是现在所有的内容!