Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Automatic fetching of PostgreSQL connection is deprecated

Description

Many pg_* functions, such as pg_query() and pg_query_params(), accept a PostgreSQL connection as their first argument, but this parameter used to be optional: when omitted, PHP implicitly reused the last connection opened with pg_connect() or pg_pconnect().

This implicit default_link behavior makes it easy to accidentally query the wrong connection when a script opens more than one, and it forces the pgsql extension to keep a hidden, mutable global state. As of PHP 8.1.0, relying on this default connection is deprecated, and an explicit connection must be passed instead.

Example

<?php

pg_connect('host=localhost dbname=test');

// The connection argument is omitted: PHP implicitly reuses
// the last connection opened by pg_connect()/pg_pconnect().
$result = pg_query('SELECT 1');

?>

Alternatives

  • Store the resource/object returned by pg_connect() or pg_pconnect() and pass it explicitly as the first argument to every pg_* function used afterwards.

Changed Behavior

This error may appear following an evolution in behavior, in previous versions. See pg_query