Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-26.11.1 | composer require openswoole/core:26.11.1
<?php OpenSwoole\Coroutine\PostgreSQL->query(string $query): OpenSwoole\Coroutine\PostgreSQLStatement|false
The full SQL statement you want to execute with the client.
When the query is successful it returns an OpenSwoole\Coroutine\PostgreSQLStatement object that holds the result. If the query produced an error it returns false, check $pg->error and $pg->resultDiag.
Execute SQL statements in a non-blocking coroutine context. Enabling you to run SQL queries asynchronously.
Rows are read from the returned statement with fetchAll(), fetchRow(), fetchAssoc(), fetchArray() or fetchObject().
Do not put untrusted values into the SQL string, use prepare() with parameters or the escape methods instead.
Selecting data
<?php
use OpenSwoole\Coroutine\PostgreSQL;
co::run(function()
{
$pg = new PostgreSQL();
$pg->connect("host=127.0.0.1 port=5432 dbname=test user=postgres password=***");
$stmt = $pg->query('SELECT * FROM test;');
$arr = $stmt->fetchAll();
var_dump($arr);
});
Returning insert ID
<?php
use OpenSwoole\Coroutine\PostgreSQL;
co::run(function()
{
$pg = new PostgreSQL();
$pg->connect("host=127.0.0.1 port=5432 dbname=test user=postgres password=***");
$stmt = $pg->query("INSERT INTO test (id, text) VALUES (24, 'text') RETURNING id;");
$arr = $stmt->fetchRow();
var_dump($arr);
});
Transaction query
<?php
use OpenSwoole\Coroutine\PostgreSQL;
co::run(function()
{
$pg = new PostgreSQL();
$pg->connect("host=127.0.0.1 port=5432 dbname=test user=postgres password=***");
$pg->query('BEGIN;');
$stmt = $pg->query('SELECT * FROM test;');
$arr = $stmt->fetchAll();
$pg->query('COMMIT;');
var_dump($arr);
});