tschoffelen/db.php

此包已被弃用且不再维护。未建议替代包。

简单的PHP类,用于执行标准的MySQL操作。

1.1.1 2018-10-16 13:01 UTC

This package is auto-updated.

Last update: 2020-03-28 12:05:12 UTC


README

Build Status codecov

Database.php是一个简单的PHP类,用于执行标准的MySQL操作,例如选择、插入、更新和删除数据库行。它还包括一些不错的功能,如自动转义以保护数据库免受恶意代码的影响,以及自动序列化数组。

用法

初始化

通过创建一个new Database()对象来初始化数据库连接。

require_once('Database.php');

$db = new Database($database_name, $username, $password, $host); // $host is optional and defaults to 'localhost'

选择

从数据库表中选择行

用法

$db->select($table, $where, $limit, $order, $where_mode, $select_fields)

参数

  • string $table - 要选择的表的名称
  • array/string $where - 包含查询的过滤器/'WHERE'子句的数组或字符串
  • int/string $limit - 包含 'LIMIT' 子句的整数或字符串
  • string $order - 包含 'ORDER BY' 子句的字符串
  • string $where_mode - 在$where数组中的每个项目后添加 'AND' 或 'OR',默认为 AND
  • string $select_fields - 要选择的字段(SELECT <$select_fields> FROM ...),默认为 *

示例

// get the first 10 candy bars that are sweet, and order them by amount
$db->select('candy', ['sweet' => 1, 'spicy' => 0], 10, 'amount DESC');
// get the ids 1, 2,5,9  from products
$db->select('products', ['id' => 'in (1,2,5,9)'], false, false,'OR');

读取结果

可以使用以下函数读取结果

  • $db->count()返回所选行的数量,等于 mysql_num_rows()

  • $db->result()返回所有匹配行作为一个包含行对象的数组

  • $db->row()返回与查询匹配的第一行作为一个对象

  • $db->result_array()返回所有匹配行作为一个包含行数组的数组

  • $db->row_array()返回与查询匹配的第一行作为一个数组

请注意,您也可以在$db->select()调用之后直接调用这些函数,如下所示

echo $db->select('candy', ['sweet' => 1], 10)->count();

还有一些其他方法可用于查询,可能很有用

  • $db->sql()返回最后执行的SQL查询

插入

将数据插入数据库表

用法

$db->insert($table, $fields=[])

示例

$db->insert(
	'candy', [
		'name' => 'Kitkat original',
		'sweet' => 1,
		'spicey' => 0,
		'brand' => 'Kitkat',
		'amount_per_pack' => 4
	]
);

提示!$db->insert()调用后立即调用$db->id(),可以获取最后插入行的ID。

更新

更新数据库表中的一行或多行

用法

$db->update($table, $fields=[], $where=[])

示例

// set amount per pack to 5 for all Kitkats
$db->update(
	'candy', [
		// fields to be updated
		'amount_per_pack' => 5
	], [
		// 'WHERE' clause
		'brand' => 'Kitkat'
	]
);

删除

从数据库表中删除一行或多行

用法

$db->delete($table, $where=[])

示例

// delete all Kitkat candy
$db->delete(
	'candy', [
		// 'WHERE' clause
		'brand' => 'Kitkat'
	]
);

单例

在初始化后,可以在全局作用域之外访问数据库实例

用法

$my_db = Database::instance();

示例

// Global scope
$db = new Database($database_name, $username, $password, $host);

// Function scope
function something() {
    // We could simply use `global $db;`, but using globals is bad. Instead we can do this:
    $db = Database::instance();

    // And now we have access to $db inside the function
}