PHP code example of techone / database

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

    

techone / database example snippets




use Leeqvip\Database\Manager;

$config = [
    'type'     => 'mysql', // mysql, pgsql, sqlite, sqlsrv
    'hostname' => '127.0.0.1',
    'database' => 'test',
    'username' => 'root',
    'password' => 'abc-123',
    'hostport' => '3306',
    'charset'  => 'utf8mb4',
];

$manager = new Manager($config);
$connection = $manager->getConnection(); // lazily creates and caches one Connection

// Returns all matching rows as an array of associative arrays
$rows = $connection->query('SELECT * FROM `users` WHERE `id` = :id', ['id' => 1]);

// Returns the number of affected rows
$count = $connection->execute(
    'UPDATE `users` SET `name` = :name WHERE `id` = :id',
    ['name' => 'joker', 'id' => 1]
);

$rows = $connection->query('SELECT * FROM `users` WHERE `id` = ?', [1]);

[
    PDO::ATTR_CASE              => PDO::CASE_NATURAL,
    PDO::ATTR_ERRMODE           => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_ORACLE_NULLS      => PDO::NULL_NATURAL,
    PDO::ATTR_STRINGIFY_FETCHES => false,
    PDO::ATTR_EMULATE_PREPARES  => false,
]

$connection = (new Manager([
    'type'     => 'sqlite',
    'database' => '/path/to/database.sqlite',
]))->getConnection();

$config = [
    'type'     => 'mysql',
    'dsn'      => 'mysql:unix_socket=/tmp/mysql.sock;dbname=test;charset=utf8mb4',
    'username' => 'root',
    'password' => 'abc-123',
];

$pdo = $connection->getPdo(); // lazily connects on first access
$connection->connect();       // or connect explicitly

$statement = $connection->getPdo()->prepare('SELECT VERSION()');
$statement->execute();

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

use Leeqvip\Database\Connection;

$balance = $connection->transaction(function (Connection $db) {
    $db->execute(
        'UPDATE `accounts` SET `balance` = `balance` - :amount WHERE `id` = :id',
        ['amount' => 100, 'id' => 1]
    );
    return $db->query('SELECT `balance` FROM `accounts` WHERE `id` = :id', ['id' => 1])[0]['balance'];
});