PostgreSQL with PHP and ODBC

First of all you need to get and install platform specific ODBC PostgreSQL drivers. I suppose you run Windows. Go to http://www.postgresql.org/ftp/odbc/versions/msi/ find the last version, pick up a mirror and download the zipped installer. The one I use I got from the Romanian mirror found here (direct link).

Unzip the file, run the installer psqlodbc.msi. It should look similar to this:

odbc install

After the installation completes, go to Control Panel > Administrative Tools > Data Sources (ODBC), select the Drivers tab and make sure the PostgreSQL Unicode driver is installed.

odbcdrivers

To use ODBC you need your PHP ODBC extension (php_pdo_odbc.dll) to be enabled (see php.ini)

This is an example PHP code connecting to a PostgreSQL server running on localhost, executing a simple query and printing the results.

<?php
/*
 * Connecting to PostgreSQL using ODBC
 * Version: 160408
 * Written by Piotr Polak
 */
 
 

/* Connection data */
$odbc_driver      = 'PostgreSQL Unicode';
$odbc_database    = 'your_database_name';
$odbc_host        = 'localhost';
$odbc_user        = 'your_username';
$odbc_password    = 'your_password';

/* ************************************************** */



/* Building DSN */
$dsn =  'DRIVER={'.$odbc_driver.'};'.
		'Server='.$odbc_host.';'.
		'Database='.$odbc_database.';'.
		'uid='.$odbc_user.'; pwd='.$odbc_password;

/* Connecting */
$connection = @odbc_connect($dsn, '', '') or die('Connection error: '.htmlspecialchars(odbc_errormsg()));

/* Prepares query */
$query = 'SELECT VERSION() AS ver';

/* Executes query */
$result = @odbc_exec($connection, $query) or die('Query error: '.htmlspecialchars(odbc_errormsg()));;

/* Fetches array */
$row = odbc_fetch_array($result);

/* Printing message */
echo '<h1>Success!</h1> <p>Server version is: '.$row['ver'].'</p>';
?>

Everything you need

Apache + PHP (I suggest WAMP)
PostgreSQL server (download)
PostgreSQL ODBC drivers for Windows (download)

References

http://www.php.net/odbc
http://en.wikipedia.org/wiki/Open_Database_Connectivity

Powered by PepisCMS