PHP code example of timefrontiers / php-sql-database
1. Go to this page and download the library: Download timefrontiers/php-sql-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/ */
timefrontiers / php-sql-database example snippets
use TimeFrontiers\SQLDatabase;
$database = new SQLDatabase(
server: '127.0.0.1',
user: 'app',
pass: 'secret',
database_or_class: 'app',
port: '3306',
);
use TimeFrontiers\PDODatabase;
use TimeFrontiers\SQLDatabase;
$connection = new PDODatabase(
driver: 'mysql',
host: '127.0.0.1',
port: 3306,
database: 'app',
username: 'app',
password: 'secret',
);
$database = SQLDatabase::fromConnection($connection);
$users = $database->fetchAll(
'SELECT * FROM users WHERE status = ?',
['active'],
);
$user = $database->fetchOne(
'SELECT * FROM users WHERE id = ?',
[5],
);
$database->execute(
'UPDATE users SET name = ? WHERE id = ?',
['John', 5],
);
if (!$database->beginTransaction()) {
throw new RuntimeException('Transaction could not be started.');
}
try {
if (!$database->execute(
'UPDATE accounts SET balance = balance - ? WHERE id = ?',
[100, 10],
)) {
throw new RuntimeException('Debit failed.');
}
if (!$database->execute(
'UPDATE accounts SET balance = balance + ? WHERE id = ?',
[100, 20],
)) {
throw new RuntimeException('Credit failed.');
}
if (!$database->commit()) {
throw new RuntimeException('Transaction was not committed.');
}
} catch (Throwable $exception) {
if ($database->inTransaction()) {
$database->rollBack();
}
throw $exception;
}
use TimeFrontiers\SQLDatabase;
$invoiceId = $database->transaction(
function (SQLDatabase $database): int {
$database->execute(
'INSERT INTO invoices (account_id, status) VALUES (?, ?)',
[42, 'draft'],
);
return (int)$database->insertId();
},
);
$database->transaction(function ($database): void {
$database->execute('UPDATE orders SET status = ? WHERE id = ?', ['open', 1]);
try {
$database->transaction(function ($database): void {
$database->execute(
'INSERT INTO optional_events (order_id, type) VALUES (?, ?)',
[1, 'opened'],
);
throw new RuntimeException('Discard the optional event.');
});
} catch (RuntimeException) {
// The outer transaction may deliberately continue.
}
});
$updated = $database->transaction(function ($database): bool {
$invoice = $database->fetchOne(
'SELECT id, status, version FROM invoices WHERE id = ? FOR UPDATE',
[123],
);
if (!$invoice) {
return false;
}
$database->execute(
'UPDATE invoices SET status = ?, version = version + 1 ' .
'WHERE id = ? AND status = ? AND version = ?',
['paid', $invoice['id'], $invoice['status'], $invoice['version']],
);
return $database->affectedRows() === 1;
});