pg_connect

(PHP 4, PHP 5)

pg_connect Établit une connexion PostgreSQL

Description

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

pg_connect() ouvre une connexion à une base de données PostgreSQL grâce à la chaîne de connexion connection_string.

Si un deuxième appel à pg_connect() est fait avec les mêmes arguments, aucune nouvelle connexion ne sera établie à moins que vous ne passiez PGSQL_CONNECT_FORCE_NEW à connect_type, mais la connexion précédente sera retournée.

L'ancienne syntaxe $conn = pg_connect("host", "port", "options", "tty", "dbname") est obsolète.

Liste de paramètres

connection_string

La chaîne connection_string peut être vide pour utiliser tous les paramètres par défaut ou elle peut contenir un ou plusieurs paramètres de configuration séparés par des espaces. Chaque paramètre de configuration est sous la forme code = valeur. Les espaces autour du signe égal sont optionnels. Pour écrire une valeur vide ou une valeur contenant des espaces, entourez cette valeur avec des apostrophes, par exemple : code = 'une valeur'. Les apostrophes et les antislashs à l'intérieur de la valeur doivent être échappés par un antislash, c'est-à-dire \' et \\.

Les mots-clé actuellement reconnus sont : host, hostaddr, port, dbname (valeur par défaut: user), user, password, connect_timeout, options, tty (ignoré), sslmode, requiressl (obsolète, utilisez sslmode) et service. La liste de ces arguments dépend de la version de votre serveur PostgreSQL.

Le paramètre options peut être utilisé pour passer des paramètres pour la ligne de commande invoquant le serveur.

connect_type

Si PGSQL_CONNECT_FORCE_NEW est passé en argument, alors une nouvelle connexion sera créée, même si la chaîne connection_string est identique à celle de la connexion existante.

Si PGSQL_CONNECT_ASYNC est fourni, la connexion sera établie de façon asynchrone. Le statut de la connexion peut être vérifié via la fonction pg_connect_poll() ou via la fonction pg_connection_status().

Valeurs de retour

Ressource de connexion PostgreSQL en cas de succès, FALSE en cas d'échec.

Historique

Version Description
5.6.0 Le support de la constante PGSQL_CONNECT_ASYNC pour le paramètre connect_type a été ajouté.

Exemples

Exemple #1 Exemple avec pg_connect()

<?php
$dbconn 
pg_connect("dbname=marie");
// connexion à une base de données nommée "marie"

$dbconn2 pg_connect("host=localhost port=5432 dbname=marie");
// connexion à une base de données nommée "marie" sur l'hôte "localhost" sur le port "5432"

$dbconn3 pg_connect("host=mouton port=5432 dbname=marie user=agneau password=foo");
// connexion à une base de données nommée "marie" sur l'hôte "mouton" avec un
// nom d'utilisateur et un mot de passe

$conn_string "host=mouton port=5432 dbname=test user=agneau password=bar";
$dbconn4 pg_connect($conn_string);
// connexion à une base de données nommée "test" sur l'hôte "mouton" avec un
// nom d'utilisateur et un mot de passe

$dbconn5 pg_connect("host=localhost options='--client_encoding=UTF8'");
//connexion à la base sur "localhost" et passage d'un paramètre de la ligne de
// commande concernant l'encodage UTF-8
?>

Voir aussi

add a note add a note

User Contributed Notes 23 notes

up
1
thakur at corexprts dot com
4 years ago
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');
?>
up
1
khyri at khyri dot com
12 years ago
After upgrading to PHP 4.2.3 from PHP 4.1.2 (Red Hat Linux Advanced Server with Stronghold 4.0) in order to manually compile in MHASH support, I discovered that Postgres support has disappeared, despite being specified on the command line, and compiling with no errors.

FATAL: Undefined function: pg_connect()

Confirmed by looking at the output of phpinfo() and comparing it to the output pre-upgrade - no mention of PostgreSQL in the new one.

Detective work led me to find that the old pgsql.so in /usr/lib/php4 was untouched, and the new one had ended up in /usr/lib/20020429 instead.

The fix was to edit config_vars.mk after configuration to change the value of EXTENSION_DIR, and then compile.

Not quite sure where 20020429 came from, looks like a left-over value from development testing...

Anyway, in case any one else has a similar problem, thought I'd document it here, as a problem with pg_connect is where this will first surface as a symptom.
up
1
Dave
1 year 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');
up
0
Anonymous
2 months 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.
up
0
bgalloway at citycarshare dot org
6 years ago
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.
up
0
xourge
7 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
example:

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

*** careful: I used double ' after password=, not "
up
0
borovik -at- gmail
7 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.
up
0
Anonymous
9 years ago
The values accepted by pg_connect's sslmode argument are: disable, allow, prefer, require
up
0
phpnet at benjamin dot schulz dot name
10 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()
up
0
Cybertinus
11 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.
up
0
derry at siliconriver.com dot au
11 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.
up
0
matias at nospam dot projectcast dot com
12 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.
up
0
rolf at sir-wum dot de
13 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.
up
0
kayotix at yahoo dot com
14 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.
up
-1
Sohel Taslim
7 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
up
-1
xzilla at users dot sourceforge dot net
11 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 http://www.postgresql.org/docs/7.4/static/client-authentication.html
up
-1
jtate at php dot net
11 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 http://www.postgresql.org/idocs/index.php?client-authentication.html for client authentication documentation.
up
-1
tim at buttersideup dot com
6 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.

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.
up
-1
leace at post dot cz
14 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_ .
up
-1
gutostraube at gmail dot com
5 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:

<?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.
up
-2
dreamsoundaudio at gmail dot com
3 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.
up
-2
infotirona at yahoo dot com
4 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... ;)
up
-3
Helio Ferenhof <d-m at eudoramail dot com>
12 years ago
Connection Hint:
Do you always write at the code the username and password to connect to your PostgreSQL database !?
What if your username or password changes?

Create a connection include file.

---
connection.inc
---
<?php
  $connection
= pg_connect("host=localhost port=5432 dbname=DATABASENAME user=USERNAME password=PASSWORD")
      or die (
"Nao consegui conectar ao PostGres --> " . pg_last_error($conn));
?>

// you can use $database name and pass it from the php file if you connect into different databases.

---
Phpfile.php
---

<?php
   
include('connection.php'); // Include the connection to the databank THEN start your SQL Job :)

   
$result=pg_exec("SELECT field FROM table WHERE field = '$something' "); // Sample of SQL QUERY
       
$fetch = pg_fetch_row($query_st); // Sample of SQL QUERY

   
pg_close($connection); // Close this connection
?>

[]s
Helio Ferenhof
d-m@eudoramail.com
To Top