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

pg_connect

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

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

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

function.pg-connect.php

pg_connect

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

pg_connectОтвори PostgreSQL врска

= NULL

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

pg_connect() отвора врска до PostgreSQL базата на податоци специфицирана од connection_string.

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

Стариот синтакс со повеќе параметри $conn = pg_connect("host", "port", "options", "tty", "dbname") е укинат.

Параметри

connection_string

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

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

На options параметарот може да се користи за поставување параметри на командната линија што ќе ги повика серверот.

flags

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

Враќа PGSQL_CONNECT_ASYNC е дадено, тогаш врската се воспоставува асинхроно. Состојбата на врската потоа може да се провери преку pg_connect_poll() or pg_connection_status().

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

Враќа PgSql\Connection инстанца при успех, или false при неуспех.

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

Верзија = NULL
8.1.0 Враќа PgSql\Connection инстанца сега; претходно, а resource .

Примери

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

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

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

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

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

$dbconn5 = pg_connect("host=localhost options='--client_encoding=UTF8'");
//connect to a database on "localhost" and set the command line parameter which tells the encoding is in UTF-8
?>

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

  • pg_pconnect() - Отвори постојана PostgreSQL врска
  • pg_close() - Затвори PostgreSQL врска
  • pg_host() - Returns the host name associated with the connection
  • pg_port() - Враќа име на хост поврзано со конекцијата
  • pg_tty() - Враќа број на порта поврзано со конекцијата
  • pg_options() - Враќа име на TTY поврзано со конекцијата
  • pg_dbname() - Ги добива опциите поврзани со конекцијата

Белешки од корисници 18 белешки

- Го добива името на базата на податоци
пред 9 години
It is worth to know, that you can set application_name in connection string, consider this simple example:

<?php
$appName = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$connStr = "host=localhost port=5432 dbname=postgres user=postgres options='--application_name=$appName'";

//simple check
$conn = pg_connect($connStr);
$result = pg_query($conn, "select * from pg_stat_activity");
var_dump(pg_fetch_all($result));

?>

By doing this move on cli or cgi you can see in pgAdmin what scripts are running or what requests are running on database. You can extend configuration of postgres to track slow queries and print application name to logs. It was very usuful to me to find out what and where should I optimize.
Дејв
12 години пред
If you use pgbouncer and unix socket
and you pgbouncer.ini looks like this
listen_port = 6432
unix_socket_dir = /tmp

you connect like this

pg_connect('host=/tmp port=6432 dbname=DB user=USER password=PASS');
Анонимен
пред 11 години
Getting md5 passwords was confusing because of a lack of documentation:

- set up your pg_hba.conf in order to use md5 password instead of 'trust' or 'ident'
- check if your postgres.conf has 'password_encryption=on' (depending on the version this might already be 'on').
- make sure to restart your postgres process.
- in PHP you just supply the username and password in _plain_ text:
'host=localhost port=5432 dbname=megadb user=megauser password=holyhandbagsbatmanthispasswordisinplaintext'
The postgres PHP library will automagically do the md5 encoding for you, no need to do it yourself.
bgalloway на citycarshare dot org
пред 17 години
Beware about writing something like 
<?php
function getdb_FAILS() {
    return pg_connect("...") or die('connection failed');
}
?>

It will return a boolean.  This will appear to be fine if you don't use the return value as a db connection handle, but will fail if you do.

Instead, use:
<?php
function getdb() {
    $db = pg_connect("...") or die('connection failed');
    return $db;
}
?>

which actually returns a handle.
- Враќа името на домаќинот поврзано со врската
пред 18 години
It's not explicitly stated here, but you can also connect to PostgreSQL via a UNIX domain socket by leaving the host empty.  This should have less overhead than using TCP e.g.:

$dbh = new PDO('pgsql:user=exampleuser dbname=exampledb password=examplepass');

In fact as the C library call PQconnectdb underlies this implementation, you can supply anything that this library call would take - the "pgsql:" prefix gets stripped off before PQconnectdb is called, and if you supply any of the optional arguments (e.g. user), then these arguments will be added to the string that you supplied...  Check the docs for your relevant PostgreSQL client library: e.g.

http://www.postgresql.org/docs/8.3/static/libpq-connect.html

If you really want, you can use ';'s to separate your arguments - these will just be converted to spaces before PQconnectdb is called.

Tim.
tim на buttersideup точка com
figroc at gmail dot com
At least with Postgres 7.2, connecting to local postgresdatabase requires a user in the database with the same name as the user running apache, or the connection fails.
matias на nospam точка projectcast точка com
пред 15 години
One thing is to remember, whenever trying to use pg_connect, add the timeout parameter with it

<?php
$d=pg_connect('host=example.com user=pgsql dbname=postgres connect_timeout=5');
?>
VLroyrenn
пред 7 години
For what it's worth, it should be noted that, while PHP will generally handle connection-reuse for you so long as you keep using the same connection strings, as in the following example:

<?php
$before_conn1 = microtime(true);
$db1 = pg_connect($conn_string);

$before_conn2 = microtime(true);
$db2 = pg_connect($conn_string);
$after_conn2 = microtime(true);

echo($before_conn2 - $before_conn1); // Takes ~0.03s
echo("\n");
echo($after_conn2 - $before_conn2); // Takes 0s
?>

...as nice as it would have been, this does not hold true for async connections; you have to manage those yourself and you can't follow up an async connection with a blocking one later on as an easy way to wait for the connection process to complete before sending queries.

<?php
$before_conn1 = microtime(true);
$db1 = pg_connect($conn_string, PGSQL_CONNECT_ASYNC);
sleep(1);

$before_conn2 = microtime(true);
$db2 = pg_connect($conn_string);
$after_conn2 = microtime(true);

echo($before_conn2 - $before_conn1); // Takes ~1s
echo("\n");
echo($after_conn2 - $before_conn2); // Takes ~0.025s
?>
thakur на corexprts точка com
пред 16 години
It's possible connect to a PostgreSQL database via Unix socket using the pg_connect() function by the following two ways:

1) Using the socket path:

<?php
$conn = pg_connect('host=/var/run/postgresql user=username dbname=databasename');
?>

2) Omitting the host name/path:

<?php
$conn = pg_connect('user=username dbname=databasename');
?>

Note: in this case (omitting the host value), the default socket path will be used.
Анонимен
20 години пред
The values accepted by pg_connect's sslmode argument are: disable, allow, prefer, require
gutostraube на gmail точка com
yasuo_ohgaki at hotmail dot com
If you use PostgreSQL users for authenticating into your pg database rather than using your own authentication, always specify host directive in pg_connect and edit pg_hba.conf to authenticate from this host accordingly. Otherwise, PHP will connect as 'local' using UNIX domain sockets, which is set in pg_hba.conf to 'trust' by default (so you can connect using psql on console without specifying password) and everyone can connect to db _without password_ .
Сохел Таслим
пред 18 години
I got the same problem but I have to solve that in different way.
In my postgresql.conf file the following was commented.
So, I active that under Connection Settings-

# - Connection Settings –
tcpip_socket = true
leace на post точка cz
пред 9 години
Using the "service" parameter as the connection string -- we found that the following functions:-

putenv("PGSERVICEFILE=/path/to/your/service/file/pg_service.conf");
$connect_string = ("service=testdb");
try {
   $pgconn_handle = pg_connect($connect_string);
   . . . . . etc.

Note:-
1) the environment variable has to point to the path AND file name.
2) the file has to be readable by Apache.

See:-

https://www.postgresql.org/docs/9.6/static/libpq-pgservice.html

for how to create your pg_service.conf
floriparob на gmail точка com
пред 22 години
regarding the note from  matias at nospam dot projectcast dot com
on 12-Feb-2002 01:16, you do not need a user in the database with the same name a your web user with ANY version of postgresql.  The only time that would be a requirement ifs if you set your postgresql server to only allow IDENT based authentication  (which IIRC is the default on Red Hat systems, which might be what lead to the confusion).  For more info on the various authentication methods allowed by postgresql, check out http://www.postgresql.org/docs/7.4/static/client-authentication.html
xzilla на users точка sourceforge точка net
пред 23 години
If you use host=HOSTNAME in your pg_connect string when connecting to PostgreSQL databases newer than 7.1, you need to make sure that your postmaster daemon is started with the "-i" option.  Otherwise the connection will fail.  See http://www.postgresql.org/idocs/index.php?client-authentication.html for client authentication documentation.
jtate на php точка net
21 години пред
if you need to open a new connection handle (i.e. for multiple pg_send_query()) use PGSQL_CONNECT_FORCE_NEW as second parameter to pg_connect()
phpnet на benjamin точка schulz точка name
yasuo_ohgaki at hotmail dot com
Little note that is buried in the install somewhere.  In Php 3, PostgreSQL support was activated by adding --with-postgresql=[DIR] to the options passed to ./configure.  With Php 4.0.2 (on Linux) the parameter was --with-pgsql.  The only place I found this was in the installing PHP on Unix section of the manual.
kayotix на yahoo точка com
figroc at gmail dot com
pg_connect() won't work with the authentication method 'crypt' in the pg_hba.conf. Took me an hour to figure that out till I remeberd some other issues with windows missing the crypt() call.
Навигација

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

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

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

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

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

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

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