PHP code example of giovanniramos / pdo4you

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

    

giovanniramos / pdo4you example snippets




use PDO4You\PDO4You;

$db = PDO4You::connect(
    'mysql:host=localhost;dbname=mydb;charset=utf8mb4',
    'username',
    'password'
);



use PDO;
use PDO4You\PDO4You;
use PDO4You\Platform\MySqlPlatform;

// 1. Create your PDO instance
$pdo = new PDO(
    'mysql:host=localhost;dbname=mydb',
    'username',
    'password'
);

// 2. Instantiate the corresponding platform
$platform = new MySqlPlatform();

// 3. Inject dependencies into PDO4You
$db = new PDO4You($pdo, $platform);

// Returns an associative array
$users = $db->select(
    'SELECT * FROM users WHERE status = ?',
    ['active']
);

// Direct mapping to class instances (FETCH_CLASS)
$users = $db->select(
    'SELECT * FROM users WHERE status = ?',
    ['active'],
    UserDTO::class
);

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

if ($user) {
    echo $user['name'];
}

$total = $db->selectVal('SELECT COUNT(*) FROM users WHERE status = ?', ['active']);

$users = $db->selectObj('SELECT name, email FROM users');

foreach ($users as $user) {
    echo $user->name;
}

$rows = $db->selectNum('SELECT id, name FROM users');
// $rows[0][0] = id, $rows[0][1] = name

$affected = $db->insert('users', [
    'name' => 'John',
    'surname' => 'Wick',
    'status' => 'active'
]);

$lastId = $db->lastId();

$affected = $db->update(
    'users',
    ['status' => 'inactive'],
    'id = :id',
    ['id' => 5]
);

$affected = $db->delete(
    'users',
    'id = :id',
    ['id' => 10]
);

// UPDATE
$affected = $db->exec(
    'UPDATE users SET status = ? WHERE id = ?',
    ['inactive', 5]
);

// DELETE
$affected = $db->exec(
    'DELETE FROM users WHERE id = ?',
    [10]
);

$totalInserted = $db->exec(
    'INSERT INTO users (name, surname) VALUES (?, ?)',
    [
        ['John', 'Doe'],
        ['Jane', 'Doe'],
        ['Alice', 'Smith']
    ]
);

$db->exec('INSERT INTO users (name) VALUES (?)', ['John']);

$userId = $db->lastId();

// For PostgreSQL with specific sequences:
// $userId = $db->lastId('users_id_seq');

$db->transaction(function (PDO4You $db) {
    $db->exec('UPDATE accounts SET balance = balance - 100 WHERE id = ?', [1]);
    $db->exec('UPDATE accounts SET balance = balance + 100 WHERE id = ?', [2]);
});

PDO4You::onQuery(function (string $sql, array $params, float $durationMs) {
    if ($durationMs > 50.0) {
        // Log slow queries
        error_log(sprintf('[Slow Query: %.2fms] %s | Params: %s', $durationMs, $sql, json_encode($params)));
    }
});
bash
php quick-test.php