PHP code example of solophp / database

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

    

solophp / database example snippets


use Solo\Database\{Config, Connection};
use Solo\Logger;
use PDO;

$config = new Config(
    hostname: 'localhost',
    username: 'user',
    password: 'pass',
    dbname: 'mydb',
    prefix: 'prefix_',
    fetchMode: PDO::FETCH_OBJ
);

$logger = new Logger('/path/to/logs/db.log');
$connection = new Connection($config, $logger);
$db = new Database($connection);

// Basic SELECT
$users = $db->query("SELECT * FROM ?t", 'users')->fetchAll();

// INSERT with associative array
$userData = [
    'name' => 'John Doe',
    'email' => '[email protected]',
    'age' => 25,
    'created_at' => new DateTimeImmutable()
];
$db->query("INSERT INTO ?t SET ?A", 'users', $userData);

// INSERT multiple rows
$data = [['John', 30], ['Alice', 25]];
$db->query("INSERT INTO ?t (name, age) VALUES ?M", 'users', $data);

// Handling null values
$userData = [
    'name' => 'Jane Doe',
    'created_at' => new DateTimeImmutable(),
    'updated_at' => null,
];
$db->query("INSERT INTO ?t SET ?A", 'users', $userData);

// Fetch single row
$user = $db->query("SELECT * FROM ?t WHERE id = ?i", 'users', 1)->fetch();

// Override fetch mode
$userArray = $db->query("SELECT * FROM ?t WHERE id = ?i", 'users', 1)->fetch(PDO::FETCH_ASSOC);

// IN clause
$ids = [1, 2, 3];
$result = $db->query("SELECT * FROM ?t WHERE id IN ?a", 'users', $ids)->fetchAll();

// Dynamic column
$column = 'email';
$userEmail = $db->query("SELECT ?c FROM ?t WHERE id = ?i", $column, 'users', 1)->fetchColumn();

// Transaction (classic)
try {
    $db->beginTransaction();
    
    $db->query("INSERT INTO ?t SET ?A", 'orders', ['product' => 'Laptop']);
    $db->query("UPDATE ?t SET balance = balance - ?f WHERE id = ?i", 'accounts', 799.99, 1);
    
    $db->commit();
} catch (Exception $e) {
    if ($db->inTransaction()) {
    $db->rollBack();
    }
    throw $e;
}

// Transaction (preferred)
$db->withTransaction(function () use ($db) {
    $db->query("INSERT INTO ?t SET ?A", 'orders', ['product' => 'Laptop']);
    $db->query("UPDATE ?t SET balance = balance - ?f WHERE id = ?i", 'accounts', 799.99, 1);
});

// Prepare only
$sql = $db->prepare("SELECT * FROM ?t WHERE user_id = ?i AND status = ?s", 'orders', 15, 'pending');

// Fetch column
$email = $db->query("SELECT email FROM ?t WHERE id = ?i", 'users', 1)->fetchColumn();

// Raw expressions
use Solo\Database\Expressions\RawExpression;
$db->query("UPDATE ?t SET ?A WHERE id = ?i", 'orders', [
    'number' => new RawExpression("CONCAT(RIGHT(phone, 4), '-', id)")
], 42);