Pdo\Pgsql::getNotify

(PHP 8 >= 8.4.0)

Pdo\Pgsql::getNotifyGet asynchronous notification

Description

public function Pdo\Pgsql::getNotify(int $fetchMode = PDO::FETCH_DEFAULT, int $timeoutMilliseconds = 0): array|false

Returns a result set representing a pending asynchronous notification.

Parameters

fetchMode

The format the result set should be returned as, one of the following constants:

timeoutMilliseconds
The length of time to wait for a response, in milliseconds.

Return Values

If a notification is pending, returns a single row, otherwise returns false. The row has a message field (the channel name) and a pid field (the process ID of the notifying backend). If the notification carries a non-empty payload, the row also has a payload field. With PDO::FETCH_NUM, these fields are at indexes 0, 1, and 2.

Errors/Exceptions

A ValueError is thrown if fetchMode is not one of the valid PDO::FETCH_* constants.

A ValueError is thrown if timeoutMilliseconds is less than 0.

A E_WARNING is raised when timeoutMilliseconds is greater than the value that can be contained in a signed 32-bit integer, in which case it will be the maximum value of a signed 32-bit integer.

Examples

Example #1 Pdo\Pgsql::getNotify() example

Subscribe to a channel with LISTEN, then read the next pending notification with a one-second timeout.

<?php
$db = new Pdo\Pgsql('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->exec('LISTEN messages');
$db->exec("NOTIFY messages, 'hello'");

$notification = $db->getNotify(PDO::FETCH_ASSOC, 1000);
var_export($notification);
?>

The above example will output something similar to:

array (
  'message' => 'messages',
  'pid' => 1928,
  'payload' => 'hello',
)

See Also

add a note

User Contributed Notes 1 note

up
0
sage at sage dot sk
5 months ago
This page needs an example to understand that you **need** to explicitly call LISTEN before using getNotify, like shown in https://www.php.net/manual/en/function.pg-get-notify.php

<?php

$db = new PDO($dsn, $user, $password, $options);
$db->query('LISTEN test');
$notification = $db->pgsqlGetNotify(PDO::FETCH_ASSOC, 10000);

// or

$db = new Pdo\Pgsql($dsn, $user, $password, $options);
$db->query('LISTEN test');
$notification = $db->getNotify(PDO::FETCH_ASSOC, 10000);

// now you can call NOTIFY elsewhere
// PG> NOTIFY test, 'payload string';
var_dump($notification);

?>

array(3) {
  ["message"]=>
  string(4) "test"
  ["pid"]=>
  int(123565)
  ["payload"]=>
  string(14) "payload string"
}

If you called NOTIFY before calling LISTEN, nothing will be returned!

You receive the first notification only, and you have to call getNotify again. And call LISTEN again if DB connection drops.
To Top