PHP - PostgreSQL connection

Sample code for connecting to a PostgreSQL database using PHP and simple queries.

The USERNAME, PASSWORD and DATABASE_NAME variables must be substituted with those supplied for your web hosting account.


  • <?php
    // make our connection
    $connection = pg_connect("host=localhost dbname=DATABASE_NAME user=USERNAME password=PASSWORD");
    
    // let me know if the connection fails
    if (!$connection) {
        print("Connection Failed.");
        exit;
    }
    
    // declare my query and execute
    $myresult = pg_exec($connection, "SELECT somevalue FROM sometable WHERE something = 1");
    
    // process results
    $myvalue = pg_result($myresult);
    
    // print results
    print("My Value: $myvalue<br />\n");