PHP code example of reactphp-x / cycle-database
1. Go to this page and download the library: Download reactphp-x/cycle-database library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
reactphp-x / cycle-database example snippets
Cycle\Database\Config as Config;
use ReactphpX\CycleDatabase\{AsyncDatabaseManager, AsyncMySQLDriverConfig, AsyncTcpConnectionConfig};
$dbal = new AsyncDatabaseManager(new Config\DatabaseConfig([
'default' => 'default',
'databases' => [
'default' => [
'driver' => 'mysql',
'prefix' => ''
],
],
'connections' => [
'mysql' => new AsyncMySQLDriverConfig(
connection: new AsyncTcpConnectionConfig(
database: getenv('DB_NAME') ?: 'test',
host: getenv('DB_HOST') ?: '127.0.0.1',
port: (int)(getenv('DB_PORT') ?: 3306),
charset: getenv('DB_CHARSET') ?: 'utf8mb4',
user: getenv('DB_USER') ?: 'root',
password: getenv('DB_PASSWORD') ?: '123456'
),
options: [
'minConnections' => (int)(getenv('DB_POOL_MIN') ?: 1),
'maxConnections' => (int)(getenv('DB_POOL_MAX') ?: 10),
'waitQueue' => (int)(getenv('DB_POOL_QUEUE') ?: 100),
'waitTimeout' => (int)(getenv('DB_POOL_TIMEOUT') ?: 0),
],
),
],
]));
$db = $dbal->database('default');
// 简单查询
$stmt = $db->query('SELECT 1 AS one');
var_dump($stmt->fetchAll());
// DDL / DML
$db->execute('CREATE TABLE IF NOT EXISTS demo_basic (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255))');
$affected = $db->execute('INSERT INTO demo_basic (title) VALUES (?)', ['hello']);
echo "Inserted rows: {$affected}\n";
echo 'Last ID: ' . $db->getDriver()->lastInsertID() . "\n";
// 原生 SQL 查询
$stmt = $db->query('SELECT * FROM users WHERE id > ?', [100]);
foreach ($stmt as $row) {
echo json_encode($row) . "\n";
}
// 执行写操作
$affected = $db->execute('UPDATE users SET name=? WHERE id=?', ['new', 123]);
// 读取结果
$oneRow = $db->query('SELECT id, name FROM users LIMIT 1')->fetch();
$rows = $db->query('SELECT id FROM users')->fetchAll();
$firstId = $db->query('SELECT id FROM users')->fetchColumn();
// SELECT
$rows = $db->select('*')
->from('users')
->where(['status' => 'active'])
->orderBy('id', 'DESC')
->limit(10)
->fetchAll();
// INSERT
$db->insert('users')->values(['email' => '[email protected] ', 'name' => 'Adam'])->run();
// UPDATE
$db->update('users', ['name' => 'Updated'], ['id' => 1])->run();
// DELETE
$db->delete('users', ['id' => 100])->run();
// UPSERT(见 examples/mysql_upsert.php)
$db->upsert('users')
->columns('email', 'name')
->values(['email' => '[email protected] ', 'name' => 'Adam'])
->run();
use ReactphpX\CycleDatabase\AsyncMysqlDriver;
use function React\Async\await;
/** @var AsyncMysqlDriver $driver */
$driver = $db->getDriver();
$result = $driver->transaction(function ($conn) {
await($conn->query('INSERT INTO logs (val) VALUES (?)', [100]));
await($conn->query('INSERT INTO logs (val) VALUES (?)', [200]));
return 'ok';
});
/** @var AsyncMysqlDriver $driver */
$driver = $db->getDriver();
$stream = $driver->queryStream('SELECT * FROM big_table');
// 结合 reactphp-x/mysql-pool 的流式 API 消费数据
// 建表(email 唯一)
$db->execute('DROP TABLE IF EXISTS users_upsert');
$db->execute('CREATE TABLE users_upsert (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(191) NOT NULL UNIQUE,
age INT NOT NULL DEFAULT 0,
name VARCHAR(191) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
// 插入一行
$db->upsert('users_upsert')
->columns('email', 'name')
->values('[email protected] ', 'Adam')
->run();
// 多行,第二行会更新已存在的 email
$db->upsert('users_upsert')
->columns('email', 'name')
->values(['email' => '[email protected] ', 'name' => 'Adam Updated'])
->values(['email' => '[email protected] ', 'name' => 'Bill'])
->run();
// 仅更新指定列(age、name)。未在 updates() 中的列不被更新
$db->upsert('users_upsert')
->columns('email', 'name', 'age')
->updates('age', 'name')
->values([
['email' => '[email protected] ', 'name' => 'Charlie2', 'age' => 10],
['email' => '[email protected] ', 'name' => 'Dave10', 'age' => 40],
])
->run();
bash
composer install
export DB_HOST=127.0.0.1
export DB_PORT=3306
export DB_NAME=test
export DB_USER=root
export DB_PASSWORD=123456
export DB_CHARSET=utf8mb4
php examples/mysql_basic.php
php examples/mysql_queries.php
php examples/mysql_transactions.php
php examples/mysql_upsert.php