pg_connect

(PHP 4, PHP 5, PHP 7)

pg_connectОткрывает соединение с базой данных PostgreSQL

Описание

resource pg_connect ( string $connection_string [, int $connect_type ] )

pg_connect() открывает соединение с базой данных PostgreSQL, определенное строкой connection_string.

При повторном вызове функции pg_connect() с теми же значениями параметров в connection_string функция вернет существующее подключение. Чтобы принудительно создать новое соединение, необходимо передать строку подключения функции PGSQL_CONNECT_FORCE_NEW в качестве параметра connect_type.

Прежний синтаксис с множеством параметров $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 служит для установки параметров командной строки, которые обработаны сервером.

connect_type

Если в функцию передана константа PGSQL_CONNECT_FORCE_NEW, будет создаваться новое подключение, даже если connection_string идентична строке существующего подключения.

Если передана константа PGSQL_CONNECT_ASYNC, то соединение устанавливается асинхронным. Состояние соединения можно проверить с помощью функций pg_connect_poll() или pg_connection_status().

Возвращаемые значения

Ресурс соединения с базой данных PostgreSQL либо FALSE, если подключиться не удалось.

Список изменений

Версия Описание
5.6.0 Добавлена поддержка константы PGSQL_CONNECT_ASYNC для параметра connect_type.

Примеры

Пример #1 Использование функции pg_connect()

<?php
$dbconn 
pg_connect("dbname=mary");
//подключиться к базе "mary"

$dbconn2 pg_connect("host=localhost port=5432 dbname=mary");
//подключиться к базе "mary" на хосте "localhost", порт "5432"

$dbconn3 pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//подключиться к базе "mary" на хосте "sheep", используя имя пользователя и пароль

$conn_string "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 pg_connect($conn_string);
//подключиться к базе "test" на хосте "sheep", используя имя пользователя и пароль

$dbconn5 pg_connect("host=localhost options='--client_encoding=UTF8'");
//подключиться к базе на хосте "localhost" и передать параметр командной строки, задающий кодировку UTF-8
?>

Смотрите также

  • pg_pconnect() - Открывает постоянное соединение с сервером PostgreSQL
  • pg_close() - Закрывает соединение с базой данных PostgreSQL
  • pg_host() - Возвращает имя хоста, соответствующего подключению
  • pg_port() - Возвращает номер порта, соответствующий заданному соединению
  • pg_tty() - Возвращает имя терминала TTY, связанное с соединением
  • pg_options() - Получение параметров соединения с сервером баз данных
  • pg_dbname() - Определяет имя базы данных

Коментарии

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_ . 
2000-07-21 17:26:17
http://php5.kiev.ua/manual/ru/function.pg-connect.html
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.
2000-09-15 02:54:39
http://php5.kiev.ua/manual/ru/function.pg-connect.html
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.
2001-10-12 20:54:37
http://php5.kiev.ua/manual/ru/function.pg-connect.html
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.
2002-02-12 15:16:58
http://php5.kiev.ua/manual/ru/function.pg-connect.html
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.
2002-12-31 16:36:29
http://php5.kiev.ua/manual/ru/function.pg-connect.html
pg_connect seems to support SSL connections, on systems where Postgres has been compiled with ssl, i'm assuming this is since psql uses libpq to connect.
pg_connect can successfully connect, and use the "requiressl" argument.
2003-08-07 23:48:28
http://php5.kiev.ua/manual/ru/function.pg-connect.html
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
2003-12-09 10:22:44
http://php5.kiev.ua/manual/ru/function.pg-connect.html
Автор:
If you use pg_connect('host=localhost port=5432 user=my_username password=my_password dbname=my_dbname') and you get the following error:
"Warning: pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection refused Is the server running on host localhost and accepting TCP/IP connections on port 5432?"
then you should try to leave the host= and port= parts out of the connection string. This sounds strange, but this is an "option" of Postgre. If you have not activated the TCP/IP port in postgresql.conf then postgresql doesn't accept any incoming requests from an TCP/IP port. If you use host= in your connection string you are going to connect to Postgre via TCP/IP, so that's not going to work. If you leave the host= part out of your connection string you connect to Postgre via the Unix domain sockets, which is faster and more secure, but you can't connect with the database via any other PC as the localhost.
2003-12-15 15:47:38
http://php5.kiev.ua/manual/ru/function.pg-connect.html
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()
2004-09-01 07:28:00
http://php5.kiev.ua/manual/ru/function.pg-connect.html
Автор:
The values accepted by pg_connect's sslmode argument are: disable, allow, prefer, require
2005-04-10 12:51:37
http://php5.kiev.ua/manual/ru/function.pg-connect.html
Автор:
"If you use pg_connect('host=localhost port=5432 user=my_username password=my_password dbname=my_dbname') and you get the following error:
"Warning: pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection refused Is the server running on host localhost and accepting TCP/IP connections on port 5432?"
"
I solved this error just by setting listen_addresses = '*' in the postgresql.conf file. This error occurs probably despite of a name resolution to localhost, given in the "host" parameter. So you can set the host in the pg_connect() function.
2007-04-03 10:06:09
http://php5.kiev.ua/manual/ru/function.pg-connect.html
Автор:
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
2007-08-02 22:20:09
http://php5.kiev.ua/manual/ru/function.pg-connect.html
Автор:
remember that when you use a blank password there will be an error because of:
password= dbname= (...)
to fix this problem use '' in your $options variable
example:

$options = " host='localhost' port='5432' user='postgres' password='' dbname='test' ";
pg_connect($options);

*** careful: I used double ' after password=, not "
2007-08-20 00:17:39
http://php5.kiev.ua/manual/ru/function.pg-connect.html
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.
2007-12-28 12:41:42
http://php5.kiev.ua/manual/ru/function.pg-connect.html
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.
2008-03-27 20:33:14
http://php5.kiev.ua/manual/ru/function.pg-connect.html
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.
2009-10-02 09:51:34
http://php5.kiev.ua/manual/ru/function.pg-connect.html
It's strange how this "Fatal error: Call to undefined function pg_connect()" happens(when everything else is OK) in PHP version 5.3.3. 

I was trying to connect to my db when I got that error message the firs time. My extensions path was OK, pgsql extension  should have been loaded from php.ini(i had enabled it before), Apache started-up without errors, but i still had the "Fatal error: Call to undefined function pg_connect()" message when i tried to connect. 
Seaching a bit around i found something about dll libraries not working as they should, so deleted the new 5.3.3 version, downloaded the PHP 5.2.5 and configured it.

I'm using Windows XP Home SP3, Apache 2.2, PHP 5.2.5 and everything works fine now... ;)
2010-08-16 21:33:37
http://php5.kiev.ua/manual/ru/function.pg-connect.html
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');
?>
2010-10-27 16:45:20
http://php5.kiev.ua/manual/ru/function.pg-connect.html
Ubuntu/Debian users, specifically server versions: If you used Tasksel to build PostgreSQL, and you're banging your head against the wall with the "Fatal error: Call to undefined function pg_connect()" error, check that php5-pgsql is installed. 

Tasksel apparently doesn't install it.
2011-09-03 13:06:24
http://php5.kiev.ua/manual/ru/function.pg-connect.html
Автор:
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');
2013-06-03 15:40:45
http://php5.kiev.ua/manual/ru/function.pg-connect.html
Автор:
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.
2014-09-29 10:50:01
http://php5.kiev.ua/manual/ru/function.pg-connect.html
Автор:
If you get the following warning :
"Warning: pg_connect(): Unable to connect to PostgreSQL server: could not translate host name "server.your.trying.to.connect.to" to address:"
and the server you are trying to connect to is fine and the connecting itself should be working fine,
it might be the case that the postgres extension for PHP might be confused about something.
Try to restart your Apache to reinitialize the extension.
2015-04-24 09:41:02
http://php5.kiev.ua/manual/ru/function.pg-connect.html
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
2016-07-12 18:20:07
http://php5.kiev.ua/manual/ru/function.pg-connect.html
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.
2016-07-24 00:37:31
http://php5.kiev.ua/manual/ru/function.pg-connect.html
Автор:
<?php

class Baza {
    const 
DNS='mysql:host=localhost;dbname=news;charset=utf8';
    const 
UZYTKOWNIK='root';
    const 
HASLO='';
   
    public 
$klient;
   
    function 
__construct(){
       
$this->polacz();
    }
    public function 
polacz(){
    try{
       
$this->klient=new PDO(
           
self::DNS,
           
self::UZYTKOWNIK,
           
self::HASLO
       
);
    }
    catch (
PDOException $e){
        die(
'Wystąpił następujący błąd bazy danych: '.$e->getMessage());
    }
    return 
true;
    }
}
2018-02-21 11:25:45
http://php5.kiev.ua/manual/ru/function.pg-connect.html
Автор:
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_stringPGSQL_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
?>
2019-01-30 21:31:06
http://php5.kiev.ua/manual/ru/function.pg-connect.html

    Поддержать сайт на родительском проекте КГБ