Contents / Previous / Next


Connect to DB

You open a PostgreSQL connection with pg_connect:
db_connection_resource  pg_connect("

         host=myHost 
         port=myPort 
         tty=myTTY 
         options=myOptions 
         dbname=myDB 
         user=myUser 
         password=myPassword ");  

pg_connect() returns a connection resource (just refered to as resource below) on success or FALSE if the connection could not be made.

All parameter have default values, often it will be enough to specify "dbname=" and maybe "user=" and/or "password=".

Usually you use a quoted connection string containing all connection values as parameter to pg_connect:

db_connection_resource pg_connect ( string conn_string )
Example: $con = "dbname=workshop user=felix"; $dbh = pg_connect( $con ); if( $dbh ) { echo "<P>connected<P>\n"; echo ( "<P>close: ".pg_close( $dbh )."<P>\n" ); } else { echo "connection error<BR>\n"; }

If a second call is made to pg_connect() with the same connection_string, no new connection will be established, but instead, the connection resource of the already opened connection will be returned. You can have multiple connections to the same database if you use different connection string.

bool pg_close ( resource connection): Closes the non-persistent connection and returns TRUE on success or FALSE on failure.
Note: Using pg_close() is not usually necessary, as non-persistent open connections are automatically closed at the end of the script.
If there is open large object resource on the connection, do not close the connection before closing all large object resources.


bool pg_ping ( resource connection):
Pings database connection and returns TRUE if connection is alive, otherwise FALSE. Example:

<?php $conn = pg_pconnect ("dbname=publisher"); if (!$conn) { echo "An error occured.\n"; exit; } if (!pg_ping($conn)) die("Connection is broken\n"); ?>


int pg_connection_status ( resource connection ):
Returns a connection status. Possible statuses are PGSQL_CONNECTION_OK and PGSQL_CONNECTION_BAD.


bool pg_connection_reset ( resource connection ):
Resets the connection and returns TRUE on success or FALSE on failure. It is useful for error recovery.


string pg_options ( resource connection ):
Returns the options associated with the connection.