nhrdev / nhr_db
这是一个基于PDO的MySQL或MariaDB数据库助手库
1.0.1
2022-12-26 01:48 UTC
Requires
- php: >=7.4
README
这个PHP库将帮助您使用PDO创建数据库连接,创建表,插入、更新、检索和从数据库中删除数据,而无需编写任何SQL代码。只需创建一个"DB"类的对象,那么您就拥有了所有功能! :)
如何安装
[username@host]$ composer require nhrdev/nhr_db
如何使用
- 连接
您必须传递一个包含以下键和您特定值的数组来连接到数据库。
driver
、host
、port
和charset
是可选的。
driver
默认设置为mysql
,host
默认设置为localhost
use NhrDev\NHR_DB\DB; $db = new DB(`DB_USERNAME`, `DB_PASSWORD`, `DB_NAME`, [`DB_HOST`, `DB_PORT`, `DB_CHARACTERSET`]);
- 断开连接
$db->disconnect();
- 如果未连接则连接
$db->connect();
- 检查是否连接
if($db->is_connected()){ echo "Connected!"; }
- 创建新表
$table = $db->table( 'table_name' ); $table->id() ->int( 'id', 255 ) ->unsigned_int( 'id', 255 ) ->unsigned_bigint( 'id', 255 ) ->col( 'id', DB::int(1), true ) ->str( 'username', 255) ->col( 'username', DB::str(100) ) ->text( 'details' ) ->col( 'details', DB::text() ) ->float( 'amount' ) ->col( 'amount', DB::float() ) ->enum( ['true', 'false'] ) ->col( 'enum', DB::enum(['value1', 'value2']) ) ->col( 'date', DB::date() ) ->col( 'datetime', DB::datetime() ) ->timestamp(); $table->create();
在创建表后添加列,在调用create()
方法后
$table->add(string $name, string $type_and_length, bool $is_primary = false, $is_auto_increment = false, bool $is_not_null = false, bool $is_unique = false);
- 删除任何表
$table->drop("COLUMN_NAME");
- 删除所有列或删除整个
TABLE_NAME
$table->drop_all();
注意:col
、add
、drop
、drop_all
这些方法将返回table object
$table
,因此在这种情况下,您可以像这样进行方法链:
$table->col()->add->drop->drop_all();
- 将行插入到表中
$table->insert([ 'column_name' => 'value' ]);
- 获取最后插入的ID。如果没有插入,将返回false。
$table->last_insert_id()
- 更新特定行
$table->update([ 'column_name' => 'value' ])->where("active", DB::eq(true)) ->where("user", "=", "true") ->where("amount", DB::between(10, 2001)) ->or("referrer", "=", -1) ->or("roll", DB::between(10, 59)) ->where("username", DB::begins_like("ra")) ->execute(); Returns the number of rows affected or false on failure.
- 更新所有行
$table->update([ 'column_name' => 'value' ]);
- 删除特定行
$table->delete() ->where("active", DB::eq(true)) ->where("user", "=", "true") ->where("amount", DB::between(10, 2001)) ->or("referrer", "=", -1) ->or("roll", DB::between(10, 59)) ->where("username", DB::begins_like("ra")) ->order_by('id', 'DESC') ->limit(5) ->execute(); Returns the number of rows affected or false on failure.
- 删除所有行
$table->delete();
- 检索行
此函数将返回具有一些访问检索数据的函数的\NhrDev\NHR_DB\Src\Result
对象。
$rows = $table->select([], DB::OBJ) ->where("active", DB::eq('true')) ->or("amount", DB::between(10, 500)) ->order_by("id", 'DESC') ->limit(1) ->offset(1) ->execute();
在这里,DB::OBJ
用于对象,DB::ASSOC
用于关联数组,DB::IND
用于索引数组
- 从检索数据中获取所有行
$rows->all();
- 获取第一行
$rows->first();
- 获取最后一行
$rows->last();
- 遍历行
第二个参数默认为false
。如果您将其设置为true
,则循环将按相反顺序进行。
$rows->each(function($row, $index){ # your code }, false);
- 通过索引获取单行
如果您传递的索引小于0
或大于检索的行数,将返回false
。
$rows->get(5);