tylersriver/php-simple-sql

PHP 中 MySQLi 的简单自管理包装器

2.3.3 2019-02-17 18:39 UTC

This package is auto-updated.

Last update: 2024-09-18 07:30:12 UTC


README

PHP 中 MySQLi 的简单自管理包装器。这个类对于只有一个数据库连接的小型网站非常有用。

1.1 为什么?

我制作了一些小型个人网站,并想要减少使用 MySQLi 编写代码的数量,同时保持安全性以帮助防止 SQL 注入。我通过这个类将其简化为一个函数调用。

1.2 功能

  • 单例维护单个连接
  • 易于使用
  • 单个灵活的查询函数
  • 它运行任何查询(选择、更新、删除、插入),并且会参数化查询
  • 插入返回插入 ID

1.3 示例

1.3.1 定义 MySQL 服务器常量

这些常量将由 SQL 类使用

define("MYSQL_SERVER", "localhost");
define("MYSQL_USER", "testUser");
define("MYSQL_PASSWORD", "test");
define("MYSQL_DB", "test");

1.3.2 使用类

<?php
require_once "SimpleSQL.php";
use SimpleSQL\SQL as SQL;
$sql = 'select * from test where field = ? and field2 = ?';
$params = ['fieldValue', 'field2Value']; // Params added in order of '?' placement in query
$result = SQL::query($sql, $params);

2 SimpleORM

一个简单的可扩展类,用于执行数据库调用。使用模型,您可以封装您的 SQL 查询到类中。它还提供基本的 CRUD 功能。

2.1 功能

  • CRUD 函数
    • 获取 - 通过 ID 从表中获取记录
    • 获取列表 - 通过简单的 WHERE 过滤器获取记录列表
    • 获取一个 - 从 GetList 返回 1 条记录
    • 添加 - 插入记录
    • 更新 - 通过 ID 更新记录
    • 更新多个 - 通过简单的 WHERE 过滤器更新记录
    • 删除 - 通过 ID 删除记录
    • 删除多个 - 通过 WHERE 过滤器删除记录
  • 易于设置
  • 简单的数据库操作封装
  • 包装 SimpleSQL 类以用于 MySQLi

2.2 示例

这是一个快速用例。每个 CRUD 函数的更多示例可以在测试目录中找到。

require_once "SimpleSQL.php";
require_once "SimpleORM.php";

// This class will hold all operations for 1 DB table
use SimpleSQL\SQL as SQL;
class TestUser extends SimpleSQL\ORM
{
    protected static $table = "testUser"; // Exact mysql table name
    protected static $key = "id"; // the primary key field name
    protected static $fields = "id, firstName, lastName, startDate, isActive"; // the fields you want returned fromt the table

    public static function GetUsersForStuff()
    {
        // Additional functions can be added for custom operations
        $sql = "SELECT * FROM testUser ... ";
        return SQL::query($sql);
    }
}

// Using the class
$results = TestUser::Get(123) // parameter is id of record
$newRecord = TestUser::Add(['firstName' => 'Tyler']);