amphp / postgres

Async Postgres client for PHP based on Amp.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to get the last inserted ID?

RonEskinder opened this issue · comments

Can you provide an example with an INSERT returning the last inserted ID into a variable, thanks

I believe you can use this method. However it seems to be only available with ext-pgsql.

Anyone knows if it's possible to get last insert id with ext-pq?

On a side note I recommend using UUIDs instead.

Can you provide an example? thanks

Like this, I think.

Amp\Loop::run(function () {
    $config = Postgres\ConnectionConfig::fromString('host=localhost user=postgres');

    /** @var \Amp\Postgres\Connection $connection */
    $connection = yield Postgres\connect($config);

    /** @var \Amp\Sql\CommandResult $result */
    $result = yield $connection->query('INSERT INTO ...');

    $id = $result->getLastOid();
});

Tried, getting nothing, empty value on "id", any other ideas?

Unfortunately no.

@RonEskinder Generally, you'll get the last inserted ID via RETURNING statements in the query in postgres, e.g.

INSERT INTO person (lastname, firstname) VALUES ('Doe', 'John') RETURNING id;

Tried this and im getting an error

use Amp\Postgres;
use Amp\Postgres\ConnectionConfig;

Amp\Loop::run(function () {
    $config = Postgres\ConnectionConfig::fromString($conn);

    /** @var \Amp\Postgres\Connection $connection */
    $connection = yield Postgres\connect($config);

    /** @var \Amp\Sql\CommandResult $result */
    $statement = yield $pool->prepare('INSERT INTO "public"."tc_fuel_merchant"("merchantName", "brand", "merchantAddress", "merchantCity", "merchantState", "merchantZip") VALUES (?, ?, ?, ?, ?, ?) RETURNING id;');
    $result = yield $statement->execute([$merchantName, $brand, $merchantAddress, $merchantCity, $merchantState, $merchantZip]);

    //$id = pg_getlastoid($result);
    $id = $result->getLastOid();
});

Error:
PHP Fatal error: Uncaught Error: Call to undefined method Amp\Postgres\PooledResultSet::getLastOid()

As @kelunik suggested, you need to use RETURNING in Postgres.

$sql = "INSERT INTO person (lastname, firstname) VALUES (?, ?) RETURNING id;"
$statement = yield $pool->prepare($sql);
$result = yield $statement->execute(['Doe', 'John']);
if (!yield $result->advance()) {
    throw new \RuntimeException("Insertion failed.");
}
$id = $result->getCurrent()['id'];

Ignore PgsqlCommandResult::getLastOid(). Driver-specific methods that are misleading shouldn't have existed. I'll deprecate it and add something like the above to the docs.

This worked like a charm, thanks!