PHP.mk документација

pg_pconnect

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.pg-pconnect.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.pg-pconnect.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
pg_pconnect

Референца за `function.pg-pconnect.php` со подобрена типографија и навигација.

function.pg-pconnect.php

pg_pconnect

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

pg_pconnectOpen a persistent PostgreSQL connection

= NULL

pg_pconnect(string $connection_string, int $flags = 0): PgSql\Connection|false

pg_pconnect() Отвори постојана PostgreSQL врска PgSql\Connection отвора врска до PostgreSQL база на податоци. Враќа

Ако се направи втор повик до pg_pconnect() со истата connection_string како постоечка врска, постоечката врска ќе биде вратена освен ако не поминете PGSQL_CONNECT_FORCE_NEW as flags.

инстанца што е потребна од други PostgreSQL функции. pgsql.allow_persistent php.ini За да овозможите постојани врски, "On" директивата мора да биде поставена на pgsql.max_persistent php.ini (што е стандардно). Максималниот број на постојани врски може да се дефинира со -1 директивата (стандардно е pgsql.max_links php.ini directive.

pg_close() за нема граница). Вкупниот број на врски може да се постави со pg_pconnect().

Параметри

connection_string

На connection_string може да биде празно за користење на сите стандардни параметри, или може да содржи една или повеќе поставки за параметри одделени со празно место. Секоја поставка за параметар е во форма keyword = value. Празната околу знакот за еднаквост е опционална. За да напишете празна вредност или вредност што содржи празни места, опкружете ја со единечни наводници, на пр. keyword = 'a value'нема да ги затвори постојаните врски генерирани од \' and \\.

Моментално препознаените клучни зборови за параметри се: host, hostaddr, port, dbname, user, password, connect_timeout, options, tty (игнорирано), sslmode, requiressl (застарено во корист на sslmode), и service. Едноставни наводници и коси црти во вредноста мора да бидат избегнати со коса црта, т.е.,

flags

Враќа PGSQL_CONNECT_FORCE_NEW се поминува, тогаш се создава нова врска, дури и ако connection_string е идентична со постоечка врска.

Вратени вредности

. Споделувањето колачиња помеѓу PHP барањата може да доведе до ненамерно мешање на чувствителни колачиња помеѓу корисниците. PgSql\Connection инстанца при успех, или false при неуспех.

Дневник на промени

Верзија = NULL
8.1.0 . Споделувањето колачиња помеѓу PHP барањата може да доведе до ненамерно мешање на чувствителни колачиња помеѓу корисниците. PgSql\Connection инстанца сега; претходно, а resource .

Примери

Пример #1 Користење pg_pconnect()

<?php
// Connect to a database named "mary"
$dbconn = pg_pconnect("dbname=mary");

// Connect to a database named "mary" on "localhost" at port "5432"
$dbconn2 = pg_pconnect("host=localhost port=5432 dbname=mary");

// Connect to a database named "mary" on the host "sheep" with a username and password
$dbconn3 = pg_pconnect("host=sheep port=5432 dbname=mary user=lamb password=foo");

// Connect to a database named "test" on the host "sheep" with a username and password
$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_pconnect($conn_string);
?>

Види Исто така

Белешки од корисници Управување со PDO конекции

- Отвори PostgreSQL врска
пред 18 години
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
robertb
пред 17 години
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
Денис Фог
пред 23 години
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.
Спирос Јоану
пред 18 години
<?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
//
?>
ts at dev dot websafe dot pl
figroc at gmail dot com
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.
garrett at bgb dot cc
пред 23 години
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"
raggaflo at libertysurf dot fr
figroc at gmail dot com
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.
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.