PHP & PostgreSQL: PDO connection example

This is a simple example how to connect to PostgreSQL from PHP using PDO object.

Preconditions:
1. php.ini configured to support PostgreSQL
2. Postgresql setuped on local machine ( Win 7)


<?php

$CFG = new stdClass();

$CFG->postgre     = new stdClass();
$CFG->postgre->host         = 'localhost';
$CFG->postgre->port         = '5432';
$CFG->postgre->user         = 'postgres';
$CFG->postgre->password     = 'mysuperpassword';
$CFG->postgre->dbname         = 'mysuperdb';

//==============================
//DB Connection - Postgresql
//==============================


  
    $pgdb = null;
    $statement = null;
       
    try{

        $pgdb = new PDO( 'pgsql:dbname=' . $CFG->postgre->dbname . ';host=' . $CFG->postgre->host . ';user=' . $CFG->postgre->user . ';password=' . $CFG->postgre->password );

    }catch(Exception $e){
        echo 'Database connection error.';
        die;
    }

 $query = $pgdb->prepare("SELECT * FROM mytable");
    $query->execute();

    $rows = $query->fetch();
    var_dump($rows);

   unset($statement);
    unset($pgdb);

?>

No comments:

Post a Comment