This article describes two methods for connecting to a PostgreSQL database using PHP:
PHP provides many functions for working directly with PostgreSQL databases.
To connect to PostgreSQL using native functions, follow these steps:
<?php $db_connection = pg_connect("host=localhost dbname=dbname user=username password=password"); ?>
After the code connects to PostgreSQL and selects the database, you can run SQL queries and perform other operations. For example, the following PHP code runs a SQL query that extracts the last names from the employees table, and stores the result in the $result variable:
<?php $result = pg_query($db_connection, "SELECT lastname FROM employees"); ?>
The PostgreSQL functions in the previous procedure can only be used with PostgreSQL databases. PDO abstracts database access, and enables you to use code that can handle different types of databases.
To connect to PostgreSQL using PDO, follow these steps:
<?php $myPDO = new PDO('pgsql:host=localhost;dbname=dbname', 'username', 'password'); ?>
After the code connects to PostgreSQL and selects the database, you can run SQL queries and perform other operations. For example, the following PHP code runs a SQL query that extracts the last names from the employees table, and stores the result in the $result variable:
<?php $result = $myPDO->query("SELECT lastname FROM employees"); ?>
Subscribe to receive weekly cutting edge tips, strategies, and news you need to grow your web business.
No charge. Unsubscribe anytime.
Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.
We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.