PHP 8.4.1 Released!

pg_pconnect

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_pconnectAbre una conexión persistente a PostgreSQL

Descripción

pg_pconnect(string $connection_string, int $connect_type = ?): resource

pg_pconnect() Abre una conexión con una base de datos PostgreSQL. Devuelve un recurso de conexión que es necesario por otras funciones para PostgreSQL.

Si se hace una segunda llamada a la función pg_pconnect() con la misma connection_string y hay una conexión existente, la conexión existente será devuelta a menos que pase la constante PGSQL_CONNECT_FORCE_NEW como connect_type.

Para habilitar la conexión persistente, la directiva de php.ini pgsql.allow_persistent se debe establecer en "On" (que es el predeterminado). El número máximo de conexiones persistentes se pueden definir con la directiva de php.ini pgsql.max_persistent (por defecto es -1 para sin límite). El número total de conexiones se pueden establecer con la directiva de php.ini pgsql.max_links.

pg_close() no cerrará enlaces persistentes generados por pg_pconnect().

Parámetros

connection_string

El parametro connection_string puede estar vacío para usar todos los parámetros por defecto, o puede contener uno o más parámetros separados por espacios en blanco. Cada ajuste de parámetros se encuentra en la forma keyword = value. Los espacios alrededor del signo igual son opcionales. Para escribir un valor vacío o un valor que contiene espacios, hay que encerrarlo entre comillas simples, por ejemplo, keyword = 'a value'. Las comillas simples y barras invertidas en el valor se pueden colocar utilizando el caracter de escapado barra invertida, es decir, \'y \\.

Las palabras clave reconocidas actualmente como parámetros son: host, hostaddr, port, dbname, user, password, connect_timeout, options, tty (ignored), sslmode, requiressl (obsoleto a favor de sslmode), y service. Cada uno de estos argumentos existen dependiendo de su versión de PostgreSQL.

connect_type

Si PGSQL_CONNECT_FORCE_NEW es pasado, entonces una nueva conexión es creada, inclusive si la connection_string es idéntica a la de la conexión existente.

Valores devueltos

Recurso de conexión PostgreSQL en caso de éxito, false en caso de fallo.

Ejemplos

Ejemplo #1 Usando pg_pconnect()

<?php
$dbconn
= pg_pconnect("dbname=mary");
//conectar a la base de datos llamada "mary"

$dbconn2 = pg_pconnect("host=localhost port=5432 dbname=mary");
// conectar a la base de datos llamada "mary" en "localhost" en el puerto "5432"

$dbconn3 = pg_pconnect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//conectar a la base de datos llamada "mary" en el host "sheep" con usuario y password

$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_pconnect($conn_string);
//conectar a la base de datos llamada "test" en el host "sheep" con usuario y password
?>

Ver también

add a note

User Contributed Notes 7 notes

up
0
Dennis Fogg
17 years ago
As of Aug 2007, some suggestions from the postgresql forums
on pg_pconnect(), faster postgres connections, and connection pooling:

Summary:
http://archives.postgresql.org/pgsql-general/2007-08/msg01406.php

Good details: http://archives.postgresql.org/pgsql-general/2007-08/msg00660.php
Also: http://archives.postgresql.org/pgsql-general/2007-08/msg01489.php
up
-1
robertb
15 years ago
You should not use pg_pconnect - it's broken. It will work but it doesn't really pool, and it's behaviour is unpredictable. It will only make you rise the max_connections parameter in postgresql.conf file until you run out of resources (which will slow your database down).

If you have many concurrent connections to your database, you should use the PostgreSQL connection pooler PgBouncer (developed by the Skype-team). When using pgbouncer, make sure you use pg_connect and NOT pg_pconnect. Also, make sure you close your connections with pg_close.

* PGBouncer homepage:
http://developer.skype.com/SkypeGarage/DbProjects/PgBouncer

* PostgreSQL pooling article by Last.fm:
http://www.last.fm/user/Russ/journal/2008/02/21
/zd_postgres_connection_pools:_pgpool_vs._pgbouncer
up
-1
Spiros Ioannou
21 years ago
Instead of reducing MaxClients in apache you may try to
reduce pgsql.max_links in php to at least the number of
postmasters. It should work and leave
you with more available httpds for static html pages.
up
-2
garrett at bgb dot cc
22 years ago
If a transaction is in progress when page processing ends, is it aborted before the connection placed bak in the pool? Or is the connection added "as is"?

It would seem that the correct thing to do is to always 'ABORT' before adding to the pool.

As a note, this would be a good time to check and see if the connection is still open before readding it. Thus allowing closed connections to be cleaned up over time, instead of hanging around for ever as they do now.
up
-3
ts at dev dot websafe dot pl
17 years ago
<?php
//
// Using pg_pconnect in a class.
//
// Why this? Because the manual says:
//
// If a second call is made to pg_pconnect() with the same
// connection_string as an existing connection, the existing
// connection will be returned unless you pass
// PGSQL_CONNECT_FORCE_NEW as connect_type.
//
// This is not always true.
//
/**
* MyClassA creates a postgresql connection using pg_pconnect
* and stores the resulting resource id to $this->conn
*/
class MyClassA
{
function
__construct($connection_string)
{
$this->conn =
pg_pconnect($connection_string)
or die(
'Wrong CONN_STRING');
}
}

//
// Showing current php.ini settings to be sure
// that persistent connections s are allowed.
// -1 means 'unlimited'
//
echo '<br>pgsql.allow_persistent: ' . ini_get('pgsql.allow_persistent');
echo
'<br>pgsql.max_persistent: ' . ini_get('pgsql.max_persistent');
echo
'<br>pgsql.max_links: ' . ini_get('pgsql.max_links');
echo
'<br><br>';

// setting one custom connection string for all objects
// (modify $connection_string to fit your needs)
$connection_string =
'host=localhost port=5432' .
' dbname=test user=test password=test';

//
// Creating 10 MyClassA objects using the same $connection_string
//
$objArr = Array();
for (
$i = 0; $i < 10; $i++)
{
$objArr[] = new MyClassA($connection_string);
}

//
// Human readable result:
//
foreach($objArr as $id => $object)
{
printf(
'%s: Object %s: using db %s<br>',
get_class($object), $id, $object->conn
);
}

/* ------------------------------------------------------------- */
// The result
// pgsql.allow_persistent: 1
// pgsql.max_persistent: -1
// pgsql.max_links: -1
//
// MyClassA: Object 0: using db Resource id #2
// MyClassA: Object 1: using db Resource id #3
// MyClassA: Object 2: using db Resource id #4
// MyClassA: Object 3: using db Resource id #5
// MyClassA: Object 4: using db Resource id #6
// MyClassA: Object 5: using db Resource id #7
// MyClassA: Object 6: using db Resource id #8
// MyClassA: Object 7: using db Resource id #9
// MyClassA: Object 8: using db Resource id #10
// MyClassA: Object 9: using db Resource id #11
//
/* ------------------------------------------------------------- */
//
// Each MyClassA object will use its _own_ database Resource id
//
?>
up
-2
raggaflo at libertysurf dot fr
22 years ago
Be careful when using Apache/PHP dynamic module/PostgreSQL :
in httpd.conf (Apache conf) default MaxClients is 150, whereas default PG's max_connections is 32 which is much fewer than 150. You have to set max_connections to at least MaxClients (and pg's shared_buffers to 2*max_connections at least) to avoid PG's errors with pg_pconnect like : "Sorry, too many clients already connected"
up
-3
etsysx dot i dot hate dot spam at teleline dot es
22 years ago
To setup a high availability server with apache as a static module and postgreSQL, change httpd.conf and set MaxClients to less than max postgreSQL simultaneous connections (like 32 or 64).
This way pg_pconnect will allways return a valid handle under heavy traffic or under a request flow attack without wasting resources and without connection problems.
To Top