Skip to content

About

Laravel风格的数据库操作类!一个文件解决SQL注入,链式查询优雅到极致/Still struggling with tedious SQL statements? Still worried about SQL injection risks? Introducing a treasure-class PHP database operation library, fully designed in Laravel style, with incredibly elegant chainable queries and ironclad security protection!

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SimpleDatabase - 轻量级Laravel风格数据库操作类

PHP Version License Style

一个轻量级、零依赖的PHP数据库操作类,完全参考Laravel风格实现链式查询,优雅的代码设计彻底解决SQL注入问题,简洁易用,只需要一个文件即可开始使用。

✨ 特性

  • 🔗 链式查询 - 完全参考Laravel Eloquent风格,流畅的API设计
  • 🛡️ 安全防护 - 内置SQL注入防护,使用PDO预处理语句
  • 📦 零依赖 - 只需要PDO扩展,无需其他依赖
  • 🎯 简单易用 - 单文件部署,即开即用
  • 🔧 功能完整 - 支持复杂查询、事务、分页等高级功能
  • 🐛 调试友好 - 内置调试模式,方便开发调试
  • 📝 类型安全 - 完整的PHPDoc注释和类型声明

🚀 快速开始

安装

直接下载 Database.php 文件到你的项目中:

wget https://raw.githubusercontent.com/Julian-cloud-max/SimpleDatabase/main/Database.php

或者在 composer.json 中添加:

{
    "autoload": {
        "files": ["path/to/Database.php"]
    }
}

基本使用

<?php
require_once 'Database.php';

use SimpleDatabase\Database;

// 创建数据库实例
$db = new Database();
$db->setConnectionParams('localhost', 'your_database', 'username', 'password');
$db->connect();

// 或者使用全局常量配置
define('DB_HOST', 'localhost');
define('DB_NAME', 'your_database');
define('DB_USER', 'username');
define('DB_PASS', 'password');

// 使用静态门面(推荐)
use SimpleDatabase\DB;

📖 使用示例

基础查询

// 查询所有记录
$users = DB::table('users')->get();

// 查询第一条记录
$user = DB::table('users')->where('id', 1)->first();

// 根据ID查找
$user = DB::table('users')->find(1);

// 查询特定字段
$names = DB::table('users')->select('name', 'email')->get();

条件查询

// 基础条件
$activeUsers = DB::table('users')
    ->where('status', 'active')
    ->where('age', '>', 18)
    ->get();

// 数组条件
$users = DB::table('users')->where([
    'status' => 'active',
    'role' => 'admin'
])->get();

// OR条件
$users = DB::table('users')
    ->where('status', 'active')
    ->orWhere('role', 'admin')
    ->get();

// IN查询
$users = DB::table('users')
    ->whereIn('id', [1, 2, 3])
    ->get();

// NULL查询
$users = DB::table('users')
    ->whereNull('deleted_at')
    ->get();

// BETWEEN查询
$users = DB::table('users')
    ->whereBetween('age', [18, 65])
    ->get();

排序和限制

// 排序
$users = DB::table('users')
    ->orderBy('created_at', 'desc')
    ->orderBy('name', 'asc')
    ->get();

// 限制和偏移
$users = DB::table('users')
    ->orderBy('id')
    ->limit(10)
    ->offset(20)
    ->get();

// 简化的分页
$users = DB::table('users')
    ->orderBy('id')
    ->limit(10)
    ->offset(0)
    ->get(); // 第一页

聚合查询

// 计数
$count = DB::table('users')->count();
$activeCount = DB::table('users')->where('status', 'active')->count();

// 检查存在
$hasUsers = DB::table('users')->exists();
$hasAdmins = DB::table('users')->where('role', 'admin')->exists();

JOIN查询

// 内连接
$users = DB::table('users')
    ->join('profiles', 'users.id', '=', 'profiles.user_id')
    ->select('users.*', 'profiles.avatar')
    ->get();

// 左连接
$users = DB::table('users')
    ->leftJoin('orders', 'users.id', '=', 'orders.user_id')
    ->select('users.*', 'COUNT(orders.id) as order_count')
    ->groupBy('users.id')
    ->get();

插入数据

// 插入单条记录
$insertId = DB::table('users')->insertGetId([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'created_at' => date('Y-m-d H:i:s')
]);

// 插入多条记录
$success = DB::table('users')->insert([
    [
        'name' => 'User 1',
        'email' => 'user1@example.com'
    ],
    [
        'name' => 'User 2',
        'email' => 'user2@example.com'
    ]
]);

更新数据

// 更新记录
$affectedRows = DB::table('users')
    ->where('id', 1)
    ->update([
        'name' => 'Updated Name',
        'updated_at' => date('Y-m-d H:i:s')
    ]);

删除数据

// 删除记录
$deletedRows = DB::table('users')
    ->where('status', 'inactive')
    ->delete();

事务处理

// 使用事务
DB::transaction(function($db) {
    $db->table('users')->insert(['name' => 'John']);
    $db->table('profiles')->insert(['user_id' => $insertId, 'bio' => 'Developer']);
});

// 或者手动控制事务
DB::beginTransaction();
try {
    DB::table('users')->insert(['name' => 'John']);
    DB::table('profiles')->insert(['user_id' => $insertId]);
    DB::commit();
} catch (Exception $e) {
    DB::rollBack();
    throw $e;
}

原始SQL

// 执行原始查询
$results = DB::select('SELECT * FROM users WHERE created_at > ?', ['2023-01-01']);

// 执行原始语句
DB::statement('UPDATE users SET status = ? WHERE role = ?', ['active', 'user']);

// 使用Raw表达式
$users = DB::table('users')
    ->select(DB::raw('COUNT(*) as user_count, status'))
    ->groupBy('status')
    ->get();

调试模式

// 启用调试模式(本地环境自动启用)
$db = new Database();
$db->debugMode = true;

// 查看最后执行的SQL
$users = DB::table('users')->where('id', 1)->get();
echo DB::getConnection()->getLastQuery();
print_r(DB::getConnection()->getLastBindings());

🔧 配置选项

数据库配置

$db = new Database();
$db->setConnectionParams($host, $database, $username, $password);
$db->setUTF8(true); // 启用UTF8编码
$db->connect();

全局配置常量

// 在配置文件中定义这些常量
define('DB_HOST', 'localhost');
define('DB_NAME', 'your_database');
define('DB_USER', 'username');
define('DB_PASS', 'password');

调试配置

// 本地环境自动启用调试
// 生产环境可以手动控制
$db = new Database();
$db->debugMode = false; // 关闭调试
$db->showErr = false;   // 关闭错误显示

📝 API 参考

主要方法

方法 描述 示例
table($table) 指定查询表 DB::table('users')
get() 获取所有结果 ->get()
first() 获取第一条结果 ->first()
find($id) 根据ID查找 ->find(1)
count() 统计记录数 ->count()
exists() 检查记录是否存在 ->exists()

查询条件方法

方法 描述 示例
where($column, $operator, $value) WHERE条件 ->where('age', '>', 18)
orWhere($column, $operator, $value) OR WHERE条件 ->orWhere('status', 'active')
whereIn($column, $values) WHERE IN条件 ->whereIn('id', [1,2,3])
whereNotIn($column, $values) WHERE NOT IN条件 ->whereNotIn('status', ['banned'])
whereNull($column) WHERE NULL条件 ->whereNull('deleted_at')
whereNotNull($column) WHERE NOT NULL条件 ->whereNotNull('email')
whereBetween($column, $values) WHERE BETWEEN条件 ->whereBetween('age', [18,65])

排序和限制方法

方法 描述 示例
orderBy($column, $direction) 排序 ->orderBy('created_at', 'desc')
limit($limit) 限制记录数 ->limit(10)
offset($offset) 偏移记录数 ->offset(20)
select($fields) 选择字段 ->select('name', 'email')

数据操作方法

方法 描述 示例
insert($values) 插入数据 ->insert(['name' => 'John'])
insertGetId($values) 插入并返回ID ->insertGetId(['name' => 'John'])
update($values) 更新数据 ->update(['name' => 'Jane'])
delete() 删除数据 ->delete()

事务方法

方法 描述 示例
transaction($callback) 执行事务 DB::transaction(function($db) { ... })
beginTransaction() 开始事务 DB::beginTransaction()
commit() 提交事务 DB::commit()
rollBack() 回滚事务 DB::rollBack()

🛡️ 安全性

  • SQL注入防护: 所有查询都使用PDO预处理语句
  • 输入验证: 自动处理参数绑定和类型转换
  • 错误处理: 生产环境下隐藏敏感错误信息
  • 连接安全: 支持SSL连接和字符集设置

🔄 兼容性

  • PHP版本: >= 7.4
  • 数据库: MySQL 5.7+ / MariaDB 10.2+
  • 扩展: PDO + PDO_MySQL
  • 系统: 跨平台支持(Windows, Linux, macOS)

📊 性能

  • 轻量级: 单文件设计,内存占用极小
  • 高效查询: 直接使用PDO,性能优异
  • 连接复用: 支持持久连接和连接池
  • 查询缓存: 内置查询结果缓存机制

🤝 贡献

欢迎提交Issue和Pull Request!

  1. Fork 本项目
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 打开Pull Request

📄 许可证

本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。

🔗 相关链接

⭐ Star History

如果这个项目对你有帮助,请给个Star支持一下!


SimpleDatabase - 让数据库操作变得简单优雅 ✨

About

Laravel风格的数据库操作类!一个文件解决SQL注入,链式查询优雅到极致/Still struggling with tedious SQL statements? Still worried about SQL injection risks? Introducing a treasure-class PHP database operation library, fully designed in Laravel style, with incredibly elegant chainable queries and ironclad security protection!

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages