CakeFest 2017 NYC, the Official CakePHP Conference


(PHP 4, PHP 5, PHP 7)

pg_connectÖffnet eine PostgreSQL-Verbindung


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

pg_connect() öffnet eine Verbindung zu der PostgreSQL-Datenbank, die durch den connection_string bezeichnet wird.

Falls ein zweiter Aufruf von pg_connect() mit demselben connection_string gemacht wird, wird die Verbindungskennung der bereits geöffneten Verbindung zurückgegeben, es sei denn, Sie übergeben die Konstante PGSQL_CONNECT_FORCE_NEW im Parameter connect_type.

Die alte Syntax $conn = pg_connect ("host", "port", "options", "tty", "dbname") sollte nicht mehr benutzt werden.



Der connection_string darf leer sein, dann werden Standard-Parameter benutzt. Er kann auch einen oder mehrere Parameter, durch Leerzeichen getrennt, enthalten. Jeder Parameter muss in der Form keyword = value angegeben werden, wobei das Gleichheitzeichen optional ist. Um einen leeren Wert oder einen Wert, der Leerzeichen enthält, zu übergeben, muss dieser in einfache Anführungszeichen eingeschlossen sein, etwa so: keyword = 'ein Wert'. Einfache Anführungszeichen oder Backslashes innerhalb von Werten müssen mit einem Backslash maskiert werden: \' und \\.

Diese Schlüsselwörter für die Parameter werden aktuell erkannt: host, hostaddr, port, dbname (standardmäßig der Wert von user), user, password, connect_timeout, options, tty (wird ignoriert), sslmode, requiressl (zugunsten von sslmode ausgemustert) und service. Welche dieser Parameter zur Verfügung stehen, ist von Ihrer PostgreSQL-Version abhängig.

Der options Parameter kann verwendet werden, um vom Server auszuführende Kommandozeilenparameter zu setzen.


Wenn PGSQL_CONNECT_FORCE_NEW übergeben wird, wird eine neue Verbindung aufgebaut, auch wenn der connection_string identisch zu der aktuell geöffneten Verbindung ist.

Ist PGSQL_CONNECT_ASYNC angegeben, dann wird die Verbindung asynchron hergestellt. Der Zustand der Verbindung kann dann per pg_connect_poll() oder pg_connection_status() überprüft werden.


Bei Erfolg wird eine PostgreSQL-Verbindungskennung zurückgegeben oder FALSE bei einem Fehler.


Version Beschreibung
5.6.0 Unterstützung für die Übergabe der PGSQL_CONNECT_ASYNC Konstante als connect_type wurde hinzugefügt.


Beispiel #1 pg_connect() benutzen

//Verbindungsaufbau zu einer Datenbank namens "mary"

$dbconn2 pg_connect("host=localhost port=5432 dbname=mary");
// Verbindungsaufbau zu einer Datenbank namens "mary" auf dem
// Host "localhost" über den (Standard-)Port "5432"

$dbconn3 pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//Verbindungsaufbau zu einer Datenbank namens "mary" auf dem Host
//"sheep" mit dem Benutzernamen "lamb" und dem Passwort "foo"

$conn_string "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 pg_connect($conn_string);
//Verbindungsaufbau zu einer Datenbank namens "test" auf dem Host
//"sheep" mit dem Benutzernamen "lamb" und dem Passwort "bar"

$dbconn5 = pg_connect("host=localhost options='--client_encoding=UTF8'");
// Verbindungsaufbau zu einer Datenbank auf dem Host "localhost" mit Setzen
// des Kommandozeilenparameters, der die Zeichenkodierung UTF-8 angibt

Siehe auch

  • pg_pconnect() - Öffnet eine persistente PostgreSQL-Verbindung
  • pg_close() - Schließt eine PostgreSQL-Verbindung
  • pg_host() - Gibt den Namen des Host zurück, zu dem verbunden wurde
  • pg_port() - Gibt die Portnummer zurück, über die die Verbindung aufgebaut wurde
  • pg_tty() - Gibt den TTY Namen für die Verbindung zurück
  • pg_options() - Gibt die Verbindungsoptionen der aktuellen Verbindung zurück
  • pg_dbname() - Gibt den Namen der Datenbank zurück

add a note add a note

User Contributed Notes 24 notes

lukasz dot wolczak at gmail dot com
6 months ago
It is worth to know, that you can set application_name in connection string, consider this simple example:

$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");


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.
3 years ago
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');
bgalloway at citycarshare dot org
8 years ago
Beware about writing something like
function getdb_FAILS() {
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:
function getdb() {
$db = pg_connect("...") or die('connection failed');

which actually returns a handle.
11 years ago
The values accepted by pg_connect's sslmode argument are: disable, allow, prefer, require
2 years ago
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.
thakur at corexprts dot com
6 years ago
One thing is to remember, whenever trying to use pg_connect, add the timeout parameter with it

=pg_connect(' user=pgsql dbname=postgres connect_timeout=5');
floriparob at gmail dot com
7 months ago
Using the "service" parameter as the connection string -- we found that the following functions:-

$connect_string = ("service=testdb");
try {
   $pgconn_handle = pg_connect($connect_string);
   . . . . . etc.

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


for how to create your pg_service.conf
tim at buttersideup dot com
9 years ago
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.

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

phpnet at benjamin dot schulz dot name
12 years ago
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()
jtate at php dot net
14 years ago
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 for client authentication documentation.
kayotix at yahoo dot com
16 years ago
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.
gutostraube at gmail dot com
7 years ago
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:

= pg_connect('host=/var/run/postgresql user=username dbname=databasename');

2) Omitting the host name/path:

= pg_connect('user=username dbname=databasename');

Note: in this case (omitting the host value), the default socket path will be used.
leace at post dot cz
16 years ago
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_ .
xzilla at users dot sourceforge dot net
13 years ago
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
matias at nospam dot projectcast dot com
15 years ago
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.
Sohel Taslim
9 years ago
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
derry at dot au
13 years ago
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.
13 years ago
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.
borovik -at- gmail
9 years ago
"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.
rolf at sir-wum dot de
15 years ago
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.
1 year ago
If you get the following warning :
"Warning: pg_connect(): Unable to connect to PostgreSQL server: could not translate host name "" 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.
dreamsoundaudio at gmail dot com
5 years ago
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.
9 years ago
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

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

*** careful: I used double ' after password=, not "
infotirona at yahoo dot com
6 years ago
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... ;)
To Top