1
0
mirror of https://github.com/danog/postgres.git synced 2024-11-26 20:15:02 +01:00
postgres/examples/transaction.php

37 lines
1.1 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;
Amp\Loop::run(function () {
2018-07-01 19:33:12 +02:00
$pool = Postgres\pool(new Postgres\ConnectionConfig('host=localhost user=postgres'));
2017-05-26 21:41:02 +02:00
yield $pool->query('DROP TABLE IF EXISTS test');
/** @var \Amp\Postgres\Transaction $transaction */
$transaction = yield $pool->transaction();
yield $transaction->query('CREATE TABLE test (domain VARCHAR(63), tld VARCHAR(63), PRIMARY KEY (domain, tld))');
2018-07-01 19:33:12 +02:00
/** @var \Amp\Sql\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
/** @var \Amp\Postgres\ResultSet $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');
2017-05-26 21:41:02 +02:00
while (yield $result->advance()) {
$row = $result->getCurrent();
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();
});