定制 anunes/andb 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

anunes/andb

Composer 安装命令:

composer require anunes/andb

包简介

A simple and secure PDO wrapper library for PHP with support for multiple database drivers

README 文档

README

PHP Version License

AnDb is a lightweight, secure, and easy-to-use PDO wrapper for PHP that provides a simple interface for database operations while maintaining security through prepared statements.

Features

  • 🔒 Secure: Built-in SQL injection protection with prepared statements
  • 🚀 Simple: Clean, intuitive API for common database operations
  • 🗃️ Multi-database: Supports MySQL, SQLite, PostgreSQL, SQL Server, and more
  • 🔧 Flexible: Easy configuration with sensible defaults
  • 📦 Lightweight: No external dependencies except PDO
  • 🔄 Transactions: Full transaction support with rollback capabilities
  • 🏗️ Modern PHP: Requires PHP 8.0+ with full type declarations

Installation

Install AnDb using Composer:

composer require anunes/andb

Quick Start

Basic Usage

<?php
require_once 'vendor/autoload.php';

use AnDb\AnDb;

// Database configuration
$config = [
    'type' => 'mysql',
    'host' => 'localhost',
    'database' => 'myapp',
    'username' => 'user',
    'password' => 'password',
    'charset' => 'utf8mb4'
];

// Create database instance
$db = new AnDb($config);

// Insert a record
$userId = $db->insert('users', [
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'password' => password_hash('secret', PASSWORD_DEFAULT)
]);

// Fetch records
$users = $db->rows("SELECT * FROM users WHERE active = ?", [1]);

// Update a record
$affected = $db->update('users',
    ['name' => 'Jane Doe'],
    ['id' => $userId]
);

// Delete a record
$deleted = $db->deleteById('users', $userId);

Configuration

MySQL Configuration

$config = [
    'type' => 'mysql',
    'host' => 'localhost',
    'port' => 3306,
    'database' => 'myapp',
    'username' => 'user',
    'password' => 'password',
    'charset' => 'utf8mb4',
    'options' => [
        PDO::ATTR_PERSISTENT => true
    ]
];

SQLite Configuration

$config = [
    'type' => 'sqlite',
    'database' => '/path/to/database.sqlite'
];

PostgreSQL Configuration

$config = [
    'type' => 'pgsql',
    'host' => 'localhost',
    'port' => 5432,
    'database' => 'myapp',
    'username' => 'user',
    'password' => 'password'
];

Backward Compatibility

AnDb also supports the old constant-based configuration for backward compatibility:

// If no config is passed, it will look for these constants:
define('DB_TYPE', 'mysql');
define('DB_HOST', 'localhost');
define('DB_NAME', 'myapp');
define('DB_USER', 'user');
define('DB_PASS', 'password');

$db = new AnDb(); // Uses constants

API Reference

Query Methods

run(string $sql, array $args = []): object

Execute a prepared statement with optional parameters.

$stmt = $db->run("SELECT * FROM users WHERE age > ?", [18]);

rows(string $sql, array $args = [], int $fetchMode = PDO::FETCH_OBJ): array

Fetch multiple records.

$users = $db->rows("SELECT * FROM users WHERE active = ?", [1]);
foreach ($users as $user) {
    echo $user->name;
}

row(string $sql, array $args = [], int $fetchMode = PDO::FETCH_OBJ): object|false

Fetch a single record.

$user = $db->row("SELECT * FROM users WHERE email = ?", ['john@example.com']);
if ($user) {
    echo $user->name;
}

getById(string $table, int $id): object|false

Get a record by ID.

$user = $db->getById('users', 123);

count(string $sql, array $args = []): int

Count matching records.

$userCount = $db->count("SELECT * FROM users WHERE active = ?", [1]);

Insert Operations

insert(string $table, array $data): false|string

Insert a record and return the auto-increment ID.

$userId = $db->insert('users', [
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'created_at' => date('Y-m-d H:i:s')
]);

Update Operations

update(string $table, array $data, array $where): int

Update records and return the number of affected rows.

$affected = $db->update('users',
    ['last_login' => date('Y-m-d H:i:s')],
    ['id' => 123]
);

Delete Operations

delete(string $table, array $where, int $limit = 1): int

Delete records with conditions.

$deleted = $db->delete('users', ['active' => 0], 10);

deleteById(string $table, int $id): int

Delete a single record by ID.

$deleted = $db->deleteById('users', 123);

deleteByIds(string $table, string $column, array $ids): int

Delete multiple records by IDs.

$deleted = $db->deleteByIds('users', 'id', [1, 2, 3, 4, 5]);

Transaction Support

$db->beginTransaction();
try {
    $db->insert('users', ['name' => 'John']);
    $db->insert('profiles', ['user_id' => $db->lastInsertId()]);
    $db->commit();
} catch (Exception $e) {
    $db->rollback();
    throw $e;
}

Direct PDO Access

For advanced operations, you can access the PDO instance directly:

$pdo = $db->getPdo();
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();

Security Features

  • Prepared Statements: All user data is automatically escaped using prepared statements
  • Parameter Binding: Values are bound separately from SQL, preventing injection attacks
  • Input Validation: Required parameters are validated before connection attempts

Error Handling

AnDb throws exceptions for database errors:

try {
    $db = new AnDb($config);
    $users = $db->rows("SELECT * FROM users");
} catch (Exception $e) {
    echo "Database error: " . $e->getMessage();
}

Requirements

  • PHP 8.0 or higher
  • PDO extension
  • Appropriate PDO driver for your database (pdo_mysql, pdo_sqlite, pdo_pgsql, etc.)

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

v1.0.0

  • Initial release
  • Support for MySQL, SQLite, PostgreSQL, SQL Server
  • CRUD operations
  • Transaction support
  • Backward compatibility with constant-based configuration

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-10-27