grithin / phpdb

PHP 数据库工具。

v4 2021-06-24 22:46 UTC

This package is not auto-updated.

Last update: 2024-09-16 10:37:48 UTC


README

用途

PHPDb 是 PDO 的便捷包装器,具有懒加载和单例功能,允许备份连接,并在连接丢失时尝试重新连接。

示例

Db 类的目的是减少常见数据库操作的时间。

输出

一个常见问题是格式化。比如说,我想获取数据库中的一列,并以数组形式展示。

$db->column('select name from user');

比如说,我想获取一个以用户ID为键的行数组。

$db->column_key('id', 'select name from user');

如果我只想获取某个记录中某个列的单一非数组值怎么办?

$db->value('select name from user where id = 2');

特殊查询

对于查询,普通的 ['id' => 2] 数组不适合用于非等于操作符的情况。如果我想要 name is nullid > 10 呢?Db 类内置了这些。

$table = 'users';
$query = [
	'id ? >' => 10, # '?' indicates the operator will appear next
	'name ? is not' => null # null values are presented to the database as string NULL
	'disabled' => null,
	'gender' => 'm'
	':last_login' => 'DATE()' # the ":" preface indicates not to escape the value part
];
$db->rows($table, $query)

这将产生类似 SQL 的结果:

SELECT * FROM `x` WHERE
`id` > 10 AND
`name` is not null AND
`disabled` is null AND
`gender` = 'm' AND
`last_login` = DATE()

这种特殊类型的数组解释允许在数组中维护一组完整的复杂查询过滤器,而不是需要逐步构建 SQL。

查询数组可以在所有方法中使用。

$db->delete($table, $query);
$db->insert($table, $query);
$db->insert_ignore($table, $query);
$db->insert_update($table, $query);
$db->replace($table, $query);
$db->rows($table, $query);
$db->row($table, $query);
$db->value($table, $query);
# ...

可选使用

你可以用多种方式来呈现你的 SQL。Db 支持:

  • 预处理语句
  • 纯文本
  • 查询数组和位置参数 ($table, $query, $select)
$db->row(['select name from user where id = :id', [':id'=>1]]);
$db->row('select name from user where id = `1`');
$db->row('user', ['id'=>1], 'name');

使用

连接

use \Grithin\Db;

$dbConfig = ['user'=>'root',
	'password'=>'',
	'database'=>'feed',
	'host'=>'localhost',
	'driver'=>'mysql'	];


$db = Db::init('main', $dbConfig);

$dbConfig = ['user'=>'root',
	'password'=>'',
	'database'=>'test',
	'host'=>'localhost',
	'driver'=>'mysql'	];


$db2 = Db::init('secondary', $dbConfig);

init 的第一个参数是单例实例的名称(参见 phpbase 中的 SingletonDefault 或 SDLL 类)。

当 Db 以静态方式调用时,默认为主单例实例,通常是首先初始化的实例。

$db1 = Db::init(null, $config1);
Db::row('user',$id); # on $db1 instance
$db1->row('user',$id);

$db2 = Db::init('secondary', $config2);
Db::row('user',$id); # still on $db1 instance
$db2->row('user',$id);

Db::primary_set('secondary');
Db::row('user',$id); # on $db2 instance

如果你想要主单例(单例默认)的实例变量,你可以获取它

$db =  Db::primary();

这对于循环代码很有用(因为使用静态方法有开销)。

你也可以通过名称获取实例

$db = Db::$instances['main'];

基本使用

有两种使用方式

  1. 引用查询
  2. 预处理语句

查询

引用

所有放入原始 SQL 中的用户输入都应该引用或格式化。你可以使用以下方式引用:

'select * from user where id = '.Db::quote($id);

你也可以使用以下方式引用数据库标识符:

'select '.Db::identity_quote('table.max').' from '.Db::identity_quote('table').' where id = 1'

当标识符的名称与保留的数据库标识符冲突时,这很有用。

SQL
Db::value('select name from user where id = 1');
#> 'bob'

Db::row('select * from user'); # will append a `limit 1`
#> ['id'=>'1','name'=>'bob']

Db::rows('select * from user');
#> [['id'=>'1','name'=>'bob'], ['id'=>'2','name'=>'bill']]

Db::column('select name from user');
#> ['bob','bill']

Db::columns('select * from user');
#> [['1','bob'],[['2','bill']]

list($id, $name) =  Db::enumerate('select id, name from user');

Db::column_key('id','select id, name from user');
#> ['1'=>'bob', '2'=>'bill']
# if more than 2 columns are selected, the key points to another array, ex:
#	#> ['1'=>['name'=>'bob', 'gender'=>'m'], '2'=>['name'=>'bill', 'gender'=>'m']]
快捷方式

快捷参数在需要时会自动引用。

Db::row('user',1); # select * from user where id = 1
Db::row('user',['id'=>1]); # select * from user where id = 1

Db::insert('user',['name'=>'jill']);

Db::insert_ignore('user',['name'=>'jill']);
Db::insert_update('user',['id'=>'3','name'=>'jill']);

Db::replace('user',['id'=>'2', 'name'=>'jill']);

Db::update('user',['name'=>'jan'], ['id'=>3]);

Db::delete('user',1);
Db::delete('user',['id'=>1]);
Db::delete('user',['id?>'=>1]);

还有许多其他辅助函数,如上所示。我建议你查看代码。如果你需要进一步记录某个功能,请在 GitHub 上创建一个 issue。

快捷魔法

使用自定义比较器

# `>` is used
Db::row('user', ['id?>'=>1]); # select * from user where id > 1

根据这些规则有多种行为

  • 如果键以 '"' 开头,则未转义的值被视为整个 WHERE 行
    • 例如:['" anything after the " is not used':'1=1']
  • 如果键中包含 "?",则 "?" 后的部分将作为“等号”("bob?<>>" => 'sue') -> "bob <> 'sue'")
  • 如果键以 ":" 开头,则值不转义
  • 如果值 === null,则将值设置为未转义的 "null"
  • 如果值设置为未转义的 "null",并且处于 "where" 辅助函数中,并且比较器为 '=', 则在前面加上 'is '。

预处理语句

exec 函数被重载以接受三种形式。这三种形式的结果是得到一个连接的 SQL 字符串和一个合并的变量数组。

  • 单数组 (['sql',$var_array,'sql'])
  • 作为参数 ($sql1, $var_array1, $sql2, $var_array2, $var_array3 )
$pdo_statement = $db->exec(['select * from user where id = :id',[':id'=>1]])
$pdo_statement = $db->exec('select * from','user where id = :id',[':id'=>1],'and id = :id2',[':id2'=>1] );

您可以使用pdo语句方法,或者使用Db辅助函数。大多数基于query的功能都有以as_为前缀的对应方法。

$pdo_statement = $db->exec(['select * from user where id = :id',[':id'=>1]])
$db->as_row($pdo_statement);
$db->as_rows($pdo_statement);
$db->as_value($pdo_statement);