agjino/php-mysql-layer

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

1.1.0 2017-09-22 23:33 UTC

This package is not auto-updated.

Last update: 2024-09-23 07:42:03 UTC


README

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', array('sweet' => 1, 'spicy' => 0), 10, 'amount DESC');
// get the ids 1, 2,5,9  from products
$db->select('products', array('id' => 'in (1,2,5,9)'), false, false,'OR');

读取结果

可以通过以下函数读取结果:

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

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

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

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

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

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

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

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

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

插入

将数据插入到数据库表中

使用方法

$db->insert($table, $fields=array())

示例

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

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

更新

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

使用方法

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

如果您需要根据公式设置值,例如 {previousValue} + 1,请在字段名末尾加上感叹号(!),例如: 'amount!' => 'amount - 100'

示例

// Move an employee to another department and update their positions count
$db->update(
	'employees',
	array( // fields to be updated
		'department' => 'IT',
		'positions!' => 'positions + 1' //Note the exclamation mark (!) at the end
	),
	array( // 'WHERE' clause
		'id' => '815'
	)
);

删除

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

使用方法

$db->delete($table, $where=array())

示例

// delete all Kitkat candy
$db->delete(
	'candy',
	array( // '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
}