celiovmjr / simplequery
简化SQL查询
1.1.6
2024-08-07 18:58 UTC
Requires
- php: >=8.1
- ext-pdo: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.59
- symfony/var-dumper: ^6.4
README
一个用于构建SQL查询并与数据库交互的PDO的PHP类SimpleQuery
。
目录
简介
SimpleQuery
类提供了一个流畅的接口来动态构建SQL查询。它支持基本的CRUD操作(创建、读取、更新、删除)并简化了参数绑定,使数据库交互更加安全和高效。
特性
- 构建SQL SELECT、INSERT、UPDATE和DELETE查询的流畅接口。
- 参数绑定以防止SQL注入攻击。
- 支持以数组或对象的形式获取结果。
- 易于设置和与现有的PDO连接集成。
- 处理表连接、WHERE条件、ORDER BY子句、LIMIT和OFFSET。
安装
要使用SimpleQuery
类,请确保您已安装PHP 8.1+和PDO扩展。只需将类文件包含或自动加载到项目中即可。
composer require celiovmjr/simplequery;
使用
创建实例
通过传递初始化的PDO连接创建SimpleQuery
的新实例
use Builder\Application\SimpleQuery; // Assuming $connection is your PDO connection class User extends SimpleQuery { protected string $table = 'users'; // Ignore if your table name is the same as the class (plural form) protected string $primaryKey = 'id'; // Ignore if your primary key is 'id' protected array $required = ['name', 'username', 'email', 'sector']; // Required fields protected array $safe = []; // Typically fields with default values public function __construct() { parent::__construct($connection); } } $user = new User();
设置和获取数据
您可以使用魔术方法(__set
、__get
、__isset
、__unset
)、数组转换方法(fromArray
、toArray
)或对象转换方法(fromObject
、toObject
)设置用于查询的数据
$user->fromArray(['name' => 'John Doe', 'age' => 30]);
执行查询
使用流畅方法构建和执行查询
$results = $user->select()->where('age > :age', ['age' => 25])->fetch(true);
CRUD操作
轻松执行CRUD操作
// Create $user->fromArray([ 'name' => 'Jane Doe', 'age' => 28 ]); $user->save(); // Read $user->select()->where('id = :id', ['id' => 1])->fetch(); // Update $user->name = 'New Name'; $user->save(); // Delete $user->delete(1);
贡献
欢迎贡献!请随时提出改进或修复的问题或拉取请求。
许可
本项目采用MIT许可证 - 请参阅LICENSE文件以获取详细信息。