1
0
mirror of https://github.com/danog/postgres.git synced 2024-12-02 09:27:54 +01:00
postgres/examples/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;
Amp\Loop::run(function () {
2018-10-14 17:48:07 +02:00
$host = 'localhost';
$port = Postgres\ConnectionConfig::DEFAULT_PORT;
$user = 'postgres';
$pool = Postgres\pool(new Postgres\ConnectionConfig($host, $port, $user));
2017-05-26 21:41:02 +02:00
yield $pool->query('DROP TABLE IF EXISTS test');
/** @var \Amp\Postgres\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))');
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();
});