Connecting to PostgreSQL with PHP
Let’s look at how we can use PostgreSQL with PHP.
I will not talk about why you should use PostgreSQL over Mysql, and this article is not about how you can install PostgreSQL on your system.
Installing PDO Driver
On Ubuntu you can install with one line command.
sudo pecl install pdo_pgsql
This will install PDO pgsql driver.
On Windows you just need to edit php.ini
find this line and remove “;”.
If you are using WAMP server, after enabling the POD PostgreSQL driver, it is still not working and you got the following error message:
could not find driver
You can put the following line:
At the end of the
httpd.conf file in the
Connection to PostgreSQL
Once the driver is installed, you can connect as following;
$pdo = new PDO("pgsql:host=localhost;dbname=yourdbname", "root", "yourpassword");
if that does not work try that way;
$pdo = new PDO("pgsql:host=localhost;dbname=yourdbname;user=root;password=yourpassword");
Connect to Docker PostgreSQL Container
Unless you use Docker you can skip this section.
All you have to do is put your docker name instead of localhost
For example, this is my docker file;
and this is how i connect to PostgreSQL;
$pdo = new PDO("pgsql:host=ordm-postgres;dbname=docker", "root", "my password");
When you use PostgreSQL instead of Mysql and you are a beginner of Pgsql you might have issue with LIMIT statement.
You probably used LIMIT statements like below when using Mysql.
but PostgreSQL does not support this statement; You have to use like that;
LIMIT 10 OFFSET 0
you better use this way always because this is a ANSI statement which is supported almost every sql server.