lcloss / db
简单的PHP数据库管理包
dev-main
2020-10-22 19:23 UTC
Requires
- lcloss/env: dev-main
Requires (Dev)
This package is auto-updated.
Last update: 2024-08-29 05:31:13 UTC
README
简单的PHP数据库管理包
安装
$ composer require lcloss/db
要求
在根目录下,创建一个包含以下字段的 .env 文件
(根据您的配置进行更改)
[database]
driver = mysql
server = localhost
port = 3306
dbname = testdb
user = root
password =
使用方法
使用数据库
您可以直接使用数据库,从静态方法 exec
开始
Database::exec( 'DROP DATABASE IF EXISTS activerecord;'); Database::exec( 'CREATE DATABASE activerecord DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;'); Database::exec( 'USE activerecord;'); Database::exec( 'DROP TABLE IF EXISTS cliente;'); $sql = <<<EOV CREATE TABLE client ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(80) NOT NULL, address TEXT, updated_at DATETIME, created_at DATETIME ); EOV; Database::exec( $sql );
创建模型
use LCloss\DB\ActiveRecord; class Client extends ActiveRecord { // Define automatically filled columns updated_at and created_at protected $log_timestamp = true; public function lastClients( $days = 7 ) { return Client::all("created_at > '" . date('Y-m-d h:m:i', strtotime("-{$days} days") )); } }
插入行
$client = new Client(); $client->name = "Some client"; $client->address = "Some address street"; $client->save();
通过 id
选择行
$client = Client::find(1);
选择所有数据
$clients = Client::all();
导航
$cond = "name LIKE 'Some%'"; $limit = 10; $offset = 20; $clients = Client::all($cond, $limit, $offset);
更新行
$client = Client::find(1); $client->name = "Changed to this name"; $client->save();
删除行
$client = Client::find(1); $client->delete();
检索行列表
for ($i = 1; $i < 11; $i++) { $client = new Client(); $client->name = "Client {$i}"; $client->address = "Street number {$i}"; if ( $client->save(); ) { echo "Client {$i} saved!\n<br />"; } else { echo "There are a problem when saving client {$i}!\n<br />"; } } $clients = Client::all(); foreach( $clients as $client ) { echo $client->name . "\n<br />"; }
找到第一行
$client = Client::findFirst("name = 'Client 4'"); echo $client->name . "\n<br />";
根据条件检索列表
$res = Client::all("address = 'Street 1'"); foreach( $clients as $client ) { echo $client->name . "\n<br />"; }
行计数
$rows = Client::count(); echo "There are {$rows} clients on database.\n<br />";