1
0
mirror of https://github.com/danog/postgres.git synced 2024-12-02 09:27:54 +01:00
postgres/examples/2-transaction.php

41 lines
1.2 KiB
PHP
Raw Normal View History

2017-05-26 21:41:02 +02:00
#!/usr/bin/env php
<?php
2018-07-01 19:33:12 +02:00
require \dirname(__DIR__) . '/vendor/autoload.php';
2017-05-26 21:41:02 +02:00
use Amp\Postgres;
2020-06-05 16:28:09 +02:00
use Amp\Postgres\Transaction;
use Amp\Sql\Result;
use Amp\Sql\Statement;
2017-05-26 21:41:02 +02:00
Amp\Loop::run(function () {
2018-10-15 17:44:40 +02:00
$config = Postgres\ConnectionConfig::fromString('host=localhost user=postgres');
2018-10-14 17:48:07 +02:00
2018-10-15 17:44:40 +02:00
$pool = Postgres\pool($config);
2017-05-26 21:41:02 +02:00
yield $pool->query('DROP TABLE IF EXISTS test');
2020-06-05 16:28:09 +02:00
/** @var Transaction $transaction */
2018-10-14 17:48:07 +02:00
$transaction = yield $pool->beginTransaction();
2017-05-26 21:41:02 +02:00
yield $transaction->query('CREATE TABLE test (domain VARCHAR(63), tld VARCHAR(63), PRIMARY KEY (domain, tld))');
2020-06-05 16:28:09 +02:00
/** @var Statement $statement */
$statement = yield $transaction->prepare('INSERT INTO test VALUES (?, ?)');
2017-05-26 21:41:02 +02:00
yield $statement->execute(['amphp', 'org']);
yield $statement->execute(['google', 'com']);
yield $statement->execute(['github', 'com']);
2017-05-26 21:41:02 +02:00
2020-06-05 16:28:09 +02:00
/** @var Result $result */
$result = yield $transaction->execute('SELECT * FROM test WHERE tld = :tld', ['tld' => 'com']);
2017-05-26 21:41:02 +02:00
$format = "%-20s | %-10s\n";
2018-07-01 19:33:12 +02:00
\printf($format, 'TLD', 'Domain');
2020-05-22 07:00:03 +02:00
while ($row = yield $result->continue()) {
2018-07-01 19:33:12 +02:00
\printf($format, $row['domain'], $row['tld']);
2017-05-26 21:41:02 +02:00
}
yield $transaction->rollback();
});