Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the preferred way to connect to a postgresql database from PHP?

Tags:

php

postgresql

I've been using PHP & MySQL for ages and am about to start using PostgreSQL instead.

What's the preferred method?

Is it via the PDO objects or is there something better?

like image 834
Mark Biek Avatar asked Aug 14 '08 00:08

Mark Biek


People also ask

How can I connect PostgreSQL database using PHP?

Use the following PHP code to connect to PostgreSQL and select a database. Replace username with your username, password with your password, and dbname with the database name: <? php $db_connection = pg_connect("host=localhost dbname=dbname user=username password=password"); ?>

Which function is offered by PHP for connecting to a PostgreSQL?

pg_connect() opens a connection to a PostgreSQL database specified by the connection_string .

Is PHP compatible with PostgreSQL?

There are two ways we can connect to the PostgreSQL database: Using the PHP command line interface. Using PHP API.


2 Answers

PDO objects are the new hotness. I'd recommend that as long as you can ensure that your target platform will always be running PHP 5.2+.

There are many other database abstraction layers that support PostgreSQL that are compatible with older versions of PHP; I'd recommend ADODB.

You should really be using PDO or a different abstraction layer even for your MySQL work; that way you won't have this problem again!

like image 130
pix0r Avatar answered Sep 29 '22 12:09

pix0r


Using Zend Db:

require_once 'Zend/Db.php';
$DB_ADAPTER = 'Pdo_Pgsql';
$DB_CONFIG = array(
    'username' => 'app_db_user',
    'password' => 'xxxxxxxxx',
    'host'     => 'localhost',
    'port'     => 5432,
    'dbname'   => 'mydb'
);
$db = Zend_Db::factory($DB_ADAPTER, $DB_CONFIG);
like image 43
grom Avatar answered Sep 29 '22 12:09

grom