benclerc/datamanagement

PHP类,提供简单紧凑的数据库请求。适用于无需ORM的小型项目。

1.6 2021-03-15 15:15 UTC

This package is auto-updated.

Last update: 2024-09-15 23:02:33 UTC


README

PHP类,提供简单紧凑的数据库请求。适用于无需ORM的小型项目。使用此类,您可以

  • 选择、插入、更新、删除数据
  • 计数行数
  • 求和行数
  • 使用SQL事务
  • 执行自定义SQL请求

此类未在PHP版本 < 7.3 上进行测试,因此不建议在 < 7.3 PHP项目中使用此类。

目录

入门

  1. 获取 Composer
  2. 使用composer安装此库: composer require benclerc/datamanagement
  3. 将以下内容添加到应用程序的主PHP文件中 require 'vendor/autoload.php';
  4. 使用数据库的连接信息实例化该类 $db = \DataManagement\DataManagement('pgsql', 'localhost', 5432, 'myDb', 'myUser', 'myUserPassword');
  5. 开始使用此库 $books = $db->select('BOOKS');

文档

您可以在这里找到完整的文档。

connector()

此方法返回连接到数据库的PDO对象。

beginTransaction()

此方法开始一个SQL事务。在此方法之后的所有其他方法调用都将在此事务中,直到您使用 commit()rollback() 结束它。

commit()

此方法通过应用更改来结束SQL事务。请注意,此方法不会返回提交的状态;即使它返回 TRUE,这也不意味着提交成功,而是意味着提交已成功发送到数据库。如果您想了解事务是否成功,您必须检查事务期间进行的每个请求的状态。

rollback()

此方法通过回滚更改来结束SQL事务。事务期间所做的任何操作都不会被应用。

debug()

此方法用于为下一个请求启用调试模式(仅适用于像 select()insert()update()delete()count()sum() 这样的构建SQL请求的方法)。而不是执行构建的请求,它将以字符串的形式返回。

参数

  • $state bool : 设置调试状态的值,默认为 TRUE。

返回值:自身。

示例

// "SELECT * FROM BOOKS;"
$db->debug()->select('BOOKS');
// "SELECT * FROM BOOKS WHERE BOOKS.books_id = :whereBOOKSbooks_id;"
$db->debug()->select('BOOKS', NULL, NULL, ['BOOKS'=>['books_id'=>42]]);
// "SELECT * FROM BOOKS INNER JOIN AUTHORS ON BOOKS.books_refauthor = AUTHORS.authors_id ORDER BY books_name ASC;"
$db->debug()->select('BOOKS', ['books_name'], ['AUTHORS'=>['INNER', 'books_refauthor', 'authors_id']]);
// "INSERT INTO BOOKS (books_name, books_refauthor) VALUES (:books_name, :books_refauthor);"
$db->debug()->insert('BOOKS', ['books_name'=>htmlentities('Super book'), 'books_refauthor'=>42]);
// "UPDATE BOOKS SET books_name=:books_name WHERE BOOKS.books_id = :whereBOOKSbooks_id;"
$db->debug()->update('BOOKS', ['books_name'=>htmlentities('Super book 2')], ['books_id'=>42]);
// "DELETE FROM BOOKS WHERE BOOKS.books_id = :whereBOOKSbooks_id;"
$db->debug()->delete('BOOKS', ['books_id'=>42]);
// "SELECT COUNT(books_id) FROM BOOKS WHERE BOOKS.books_isavailable IS NULL;"
$db->debug()->count('BOOKS', 'books_id', ['BOOKS'=>['books_isavailable'=>TRUE]]);
// "SELECT SUM(books_pages) FROM BOOKS WHERE BOOKS.books_isavailable IS NULL;"
$db->debug()->sum('BOOKS', 'books_pages', ['BOOKS'=>['books_isavailable'=>TRUE]]);

select()

此方法用于从数据库检索数据。它可以是获取整个表或更复杂的请求,如排序、表连接、筛选、限制和偏移量。

参数

  • $table string : 表名。
  • $order array (可选) : 以列名和所需顺序为键的数组,例如 ['column' => 'ASC/DESC']。如果没有传递值,则使用默认值:'ASC'。
  • $join array (可选) : 以所需连接表名作为键的数组,其中包含所需的值作为值,例如 ['table' => [type(inner, left, right ...), 'foreignkey', 'primarykey', /*from table*\]]。从表参数是可选的,如果未设置,则使用 $table 代替。
  • $where array (可选) : 以表名作为键的数组,其中包含列名和筛选值的数组,例如 ['table'=>['columnname'=>'data']]。'data'有保留值用于空值和布尔值:'NULL'、'!NULL'、'TRUE'、'FALSE'。'data'也可以是值的数组。
  • $limit int (可选) : 最大行数,例如 50。
  • $offset int (可选) : 返回行的偏移量,例如 100。
  • 列数组(可选):列名的数组。

返回值:如果调试设置为 TRUE:返回伪造的 SQL 请求,否则返回 fetchAll 结果。

示例

// Get all books
$res = $db->select('BOOKS');
// Get one book, id = 42
$res = $db->select('BOOKS', NULL, NULL, ['BOOKS'=>['books_id'=>42]])[0]; // Note the NULL values because we do not want order or join. And also note [0] because we know we have only one result so we can select it directly.
// Get all books with their authors, results ordered on the book name from A to Z
$res = $db->select('BOOKS', ['books_name'], ['AUTHORS'=>['INNER', 'books_refauthor', 'authors_id']]);
// Get all books with the reference in the list + their authors, results ordered on the book name from A to Z and author name from Z to A, limit to 10 results with an offset of 10 (page 2)
$referenceList = [37483, 27949, 49303, 20438];
$res = $db->select('BOOKS', ['books_name', 'authors_name'=>'DESC'], ['AUTHORS'=>['INNER', 'books_refauthor', 'authors_id']], ['BOOKS'=>['books_reference'=>$referenceList]], 10, 10);
// Get all books with their subcategories and categories
$res = $db->select('BOOKS', NULL, ['SUBCATEGORIES'=>['INNER', 'books_refsubcategory', 'subcategories_id'], 'CATEGORIES'=>['INNER', 'subcategories_refcategory', 'categories_id', 'SUBCATEGORIES']]); // Note the fourth element in the element 'CATEGORIES' in the join array.

customSelect()

此方法用于使用自定义 SQL 请求从数据库中检索数据。

参数

  • $sql 字符串:SQL 请求。
  • $data 数组(可选):数据数组,例如 ['columnname'=>'data'] 或在请求中使用 ?['data1', 'data2']

返回值:fetchAll 结果的数组。

示例

// For request with subqueries for example 
$res = $db->customSelect('SELECT * FROM BOOKS WHERE books_id IN (SELECT orders_refbook FROM ORDERS WHERE orders_refclient = :id);', ['id'=>42]);
// Or to filter using an other operator than =
$res = $db->customSelect('SELECT * FROM BOOKS WHERE books_release > 2000-01-01');

insert()

此方法用于在数据库中插入数据。强烈建议在插入数据时使用事务。

参数

  • $table string : 表名。
  • $data 数组:数据数组,例如 ['columnname'=>'data']

返回值:如果调试设置为 TRUE:返回伪造的 SQL 请求,否则返回包含 2 行的数组:'raw' => 数据库的原始响应,'lastInsertId' => 最后插入 ID。

示例

// Simple insert, without transaction
if ($db->insert('BOOKS', ['books_name'=>htmlentities('Super book'), 'books_refauthor'=>42])['raw']) {
	echo('Success');
} else {
	echo('Error');
}

// Simple insert, with transaction
$db->beginTransaction();
$resAuthor = $db->insert('AUTHORS', ['authors_name'=>htmlentities('Super Author')]);
if ($resAuthor['raw']) {
	if ($db->insert('BOOKS', ['books_name'=>htmlentities('Super book'), 'books_refauthor'=>$resAuthor['lastInsertId']])['raw']) {
		$db->commit();
		echo('Success');
	} else {
		$db->rollback();
		echo('Error when inserting book.');
	}
} else {
	$db->rollback();
	echo('Error when inserting author.');
}

customInsert()

此方法用于使用自定义 SQL 请求在数据库中插入数据。

参数

  • $sql 字符串:SQL 请求。
  • $data 数组(可选):数据数组,例如 ['columnname'=>'data'] 或在请求中使用 ?['data1', 'data2']

返回值:包含 2 行的数组:'raw' => 数据库的原始响应,'lastInsertId' => 最后插入 ID。

示例

// For insert using SQL functions for example
$res = $db->customInsert('INSERT INTO BOOKS (books_name, books_release) VALUES (?, NOW());', [htmlentities('Super book')]);

update()

此方法用于在数据库中更新数据。强烈建议在更新数据时使用事务。

参数

  • $table string : 表名。
  • $data 数组:数据数组,例如 ['columnname'=>'data']
  • $where 数组:指向要更新行的数据的数组,例如 ['columnname'=>'data']。'data' 具有用于 null 和布尔值的保留值:'NULL','!NULL','TRUE','FALSE'。'data' 也可以是值的数组。

返回值:如果调试设置为 TRUE:返回伪造的 SQL 请求,否则返回请求的状态作为布尔值。

示例

// Simple update, without transaction
if ($db->update('BOOKS', ['books_name'=>htmlentities('Super book 2')], ['books_id'=>42])) {
	echo('Success');
} else {
	echo('Error');
}

// Simple update, with transaction
$db->beginTransaction();
$resBook1 = $db->update('BOOKS', ['books_name'=>htmlentities('Super book 1')], ['books_id'=>41]);
if ($resBook1) {
	if ($db->update('BOOKS', ['books_name'=>htmlentities('Super book 2')], ['books_id'=>42])) {
		$db->commit();
		echo('Success');
	} else {
		$db->rollback();
		echo('Error when updating book 2.');
	}
} else {
	$db->rollback();
	echo('Error when updating book 1.');
}

delete()

此方法用于从数据库中删除数据。强烈建议在删除数据时使用事务。

参数

  • $table string : 表名。
  • $where 数组:指向要更新行的数据的数组,例如 ['columnname'=>'data']。'data' 具有用于 null 和布尔值的保留值:'NULL','!NULL','TRUE','FALSE'。'data' 也可以是值的数组。

返回值:如果调试设置为 TRUE:返回伪造的 SQL 请求,否则返回请求的状态作为布尔值。

示例

// Simple delete, without transaction
if ($db->delete('BOOKS', ['books_id'=>42])) {
	echo('Success');
} else {
	echo('Error');
}

// Simple delete, with transaction
$db->beginTransaction();
$resBook1 = $db->delete('BOOKS', ['books_id'=>41]);
if ($resBook1) {
	if ($db->delete('BOOKS', ['books_id'=>42])) {
		$db->commit();
		echo('Success');
	} else {
		$db->rollback();
		echo('Error when deleting book 2.');
	}
} else {
	$db->rollback();
	echo('Error when deleting book 1.');
}

count()

此方法用于计算满足条件的行数。

参数

  • $table string : 表名。
  • $column 字符串:列名。
  • $where 数组:具有表名作为键,以及具有列名和筛选值的数组的值,例如 ['table'=>['columnname'=>'data']]。'data' 具有用于 null 和布尔值的保留值:'NULL','!NULL','TRUE','FALSE'。'data' 也可以是值的数组。
  • $join 数组(可选):具有所需的连接表名作为键和所需值的数组,例如 ['table' => [type(inner, left, right ...), 'foreignkey', 'primarykey', /*from table*\]]

返回值:如果调试设置为 TRUE:返回伪造的 SQL 请求,否则返回请求的状态作为布尔值在失败或成功时返回整数。

示例

// Simple count
$res = $db->count('BOOKS', 'books_id', ['books_isavailable'=>TRUE]);
// Count with join
$res = $db->count('BOOKS', 'authors_id', ['books_isavailable'=>TRUE], ['AUTHORS'=>['INNER', 'books_refauthor', 'authors_id']]); // Return the number of authors who have at least one book available.

sum()

此方法用于计算满足条件的几行数据的总和。

参数

  • $table string : 表名。
  • $column 字符串:列名。
  • $where 数组:具有表名作为键,以及具有列名和筛选值的数组的值,例如 ['table'=>['columnname'=>'data']]。'data' 具有用于 null 和布尔值的保留值:'NULL','!NULL','TRUE','FALSE'。'data' 也可以是值的数组。
  • $join 数组(可选):具有所需的连接表名作为键和所需值的数组,例如 ['table' => [type(inner, left, right ...), 'foreignkey', 'primarykey', /*from table*\]]

返回值:如果调试设置为 TRUE:返回伪造的 SQL 请求,否则返回请求的状态作为布尔值在失败或成功时返回整数。

示例

// Simple sum
$res = $db->sum('BOOKS', 'books_pages', ['books_isavailable'=>TRUE]); // Return the total number of pages of available books.

customSQL()

此方法用于执行自定义 SQL 请求。

参数

  • $sql 字符串:SQL 请求。
  • $data 数组(可选):数据数组,例如 ['columnname'=>'data'] 或在请求中使用 ?['data1', 'data2']

返回值:原始响应的数组。

示例

// For uncommon SQL queries
$res = $db->customSQL('UPDATE BOOKS SET books_isold IS TRUE WHERE books_release < 2000-01-01');