How to Connect to a PostgreSQL Database Using PHP Data Objects (PDO) 


               


How to Connect to a PostgreSQL Database Using PHP Data Objects (PDO)

PHP



In this article, we show how to connect to a PostgreSQL database using PHP Data Objects (PDO).

PHP supports all the major relational databases used by large companies, including Oracle, IBM's DB2, and Microsoft's SQL server. It also serves open source databases, such as SQLite, PostgreSQL, and MySQL.

In this code, we specifically focus on how to connect to a PostgreSQL database with PHP, specifically using a PHP Data Object (PDO).

PDO, PHP Data Objects extension, is a data-access abstraction layer. With PDO, you no longer need to use functions for specific databases. PDO is a consistent interface for multiple databases. With PDO, you no longer have to use the mysql_ functions or sqlite_ functions. Instead, you can simply use the PDO interface to work with all relational databases with the same code (with the same functxions). If you change databases, you'll only have to change the Data Source Name (DSN) of the PDO for the code to work.

So to access a PostgreSQL database using a PDO, the code is shown below.



By running this code, you should be able to connect to a serve that hosts a PostgreSQL database.

If you wanted to connect to another database, such as MysQL or SQLite, then you would just need to change the data source name. Note that for MySQL databases, only the DSN, the username and the password (separately) are needed to connect to the database. For SQLite databases, like PostgreSQL databases, only the DSN is needed to connect to the database.

For the DSN for PDO, there are 3 basic parts: the PDO driver name (such as mysql, sqlite, or pgsqul), a colon, and the driver-specific syntax. For PostgreSQL, the host name and the database name are needed to connect to the database.


Related Resources

How to Connect to a MySQL Database Using PHP Data Objects



HTML Comment Box is loading comments...