Connection to PostgreSQL 8.4/9.2 for PHP applications

  1. Creating environment
    1. Log into the
      Jelastic Manager

    2. Create environment with PostgreSQL database:



    3. Check your e-mail - your inbox should have a message from Robot@jelastic with database login and password:



    4. Now you can upload your PHP application package and deploy it to the environment.

  2. Connection to the database
    1. Click Config button for your Apache server



    2. Navigate to etc folder and open php.ini file

    3. Add extension=pgsql.so line after extension=mysql.so



    4. Save the changes and restart the node



    5. There are 2 main PG functions for connection:

      1. Connection to your postgresql database:
      2. pg_connect("host=host_address port=5432 dbname=postgres user=webadmin password=password");
        • host - Postgres server address that you received by email (note that it must be without http://):
          postgres-{env_name}.{hoster_domain}
        • port - by default 5432.
        • dbname - name of your database.
        • user - by default is "webadmin"
        • password - the password that you received by email.
      3. Closing connection to postgresql database: pg_close().

      All Postgres functions you can see here.

    6. You need to write necessary functions in every *.php page, which should be connected to the database.

  3. Checking the connection
  4. You can check the connection using this code:

    <?php
    
    $dbconn = pg_connect("host=postgres-demo.jelastic.com port=5432 dbname=postgres-demo user=webadmin password=password");
    //connect to a database named "postgres" on the host "host" with a username and password
    
    if (!$dbconn){
    echo "<center><h1>Doesn't work =(</h1></center>";
    }else
     echo "<center><h1>Good connection</h1></center>";
    pg_close($dbconn);
    ?>
    

  5. Executing simple request
  6. Here is an example how to execute simple request and output it onto table:

    <?php
    
    $conn = pg_connect("host=postgres-demo.jelastic.com port=5432 dbname=postgres-demo user=webadmin password=password");
    if (!$conn) {
     echo "An error occured.\n";
     exit;
    }
    
    $result = pg_query($conn, "SELECT * FROM test_table");
    if (!$result) {
     echo "An error occured.\n";
     exit;
    }
    
    while ($row = pg_fetch_row($result)) {
     echo "value1: $row[0]  value2: $row[1]";
     echo "<br />\n";
    }
    
    ?>
    

    Now you can use connection to PostgreSQL database for your PHP application.