PHP code example of boxphp / database

1. Go to this page and download the library: Download boxphp/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/ */

    

boxphp / database example snippets


use BoxPHP\Database\Database\PdoConnection;

$db = new PdoConnection([
    'driver' => 'mysql',
    'host' => '127.0.0.1',
    'port' => 3306,
    'database' => 'myapp',
    'username' => 'root',
    'password' => '',
]);

$db->connect();
$users = $db->select('SELECT * FROM users WHERE id = ?', [1]);

use BoxPHP\Database\Database\QueryBuilder;

// SELECT
$users = (new QueryBuilder('users'))
    ->select('id', 'name', 'email')
    ->where('status', 'active')
    ->orderBy('created_at', 'DESC')
    ->limit(10)
    ->get();

// INSERT
$id = (new QueryBuilder('users'))
    ->insert(['name' => 'John', 'email' => '[email protected]']);

// UPDATE
=count = (new QueryBuilder('users'))
    ->where('id', 1)
    ->update(['status' => 'inactive']);

// DELETE
=count = (new QueryBuilder('users'))
    ->where('id', 1)
    ->delete();

// 聚合
$count = (new QueryBuilder('users'))
    ->where('status', 'active')
    ->count();

$sum = (new QueryBuilder('orders'))
    ->where('user_id', 1)
    ->sum('amount');

use BoxPHP\Database\Database\DatabasePool;

$pool = new DatabasePool([
    'driver' => 'mysql',
    'host' => '127.0.0.1',
    'database' => 'myapp',
    'username' => 'root',
    'password' => '',
    'pool_max_size' => 10,
]);

$db = $pool->get();
$users = $db->select('SELECT * FROM users');
$pool->put($db);

$db->beginTransaction();
try {
    $db->execute('UPDATE accounts SET balance = balance - ? WHERE id = ?', [100, 1]);
    $db->execute('UPDATE accounts SET balance = balance + ? WHERE id = ?', [100, 2]);
    $db->commit();
} catch (\Exception $e) {
    $db->rollBack();
    throw $e;
}