Using php to connect to postgresql

PostgreSQL PHP: Connect to PostgreSQL Database Using PDO

Summary: in this tutorial, you will learn how to setup a simple project structure and connect to the PostgreSQL database using PHP PDO API.

Enable PDO_PGSQL driver

Most PHP distributions include the PostgreSQL extension PDO_PGSQL by default so you don’t need to do any further configuration in PHP.

However, if this is not the case, you can enable the extension by editing the php.ini file to uncomment the following line:

;extension=php_pdo_pgsql.dllCode language: Shell Session (shell)

To uncomment the line, you remove the semicolon (;) at the beginning of the line and restart the webserver.

extension=php_pdo_pgsql.dllCode language: SQL (Structured Query Language) (sql)

Create a PHP project structure with Composer

The Composer is a tool for managing dependency that allows you to declare the PHP library in a project and manage the update automatically.

We will use the Composer to set up the project structure of all the projects that we will be working on.

First, create the postgresqlphpconnect folder in the webroot folder to store the project files.

Next, create the app folder and a new composer.json file in the postgresqlphpconnect folder with the following content:

 < "autoload": < "psr-4": < "PostgreSQLTutorial\\": "app/" >> >Code language: SQL (Structured Query Language) (sql)

It means that every class that you create in the app folder will map to the PostgreSQLTutorial namespace.

Then, go to the window terminal, navigate to the postgresqlphpconnect folder, and type the following command:

This command instructs the Composer to download the declared libraries in the composer.json file and generate an autoload file.

The command will also place all third-party libraries in the newly created vendor folder. Because we didn’t declare any library in the composer.json file, it just generates the autoload file.

Loading composer repositories with package information Updating dependencies (including require-dev) Nothing to install or update Generating autoload filesCode language: JavaScript (javascript)

After that, create the index.php file in the postgresqlphpconnect folder.

Finally, create two more files in the app folder: Connection.php and database.ini .

The project structure will look like the following picture:

PostgreSQL PHP Connect

Connect to the PostgreSQL database

First, create a new database named stocks for the demonstration.

CREATE DATABASE stocks;Code language: SQL (Structured Query Language) (sql)

Next, use the database.ini file to store the PostgreSQL database parameters as follows:

host=localhost port=5432 database=stocks user=postgres password=postgresCode language: SQL (Structured Query Language) (sql)

Then, create a new class called Connection in the Connection.php file.

 namespace PostgreSQLTutorial; /** * Represent the Connection */ class Connection < /** * Connection * @var type */ private static $conn; /** * Connect to the database and return an instance of \PDO object * @return \PDO * @throws \Exception */ public function connect() < // read parameters in the ini configuration file $params = parse_ini_file('database.ini'); if ($params === false) < throw new \Exception("Error reading database configuration file"); > // connect to the postgresql database $conStr = sprintf("pgsql:host=%s;port=%d;dbname=%s;user=%s;password=%s", $params['host'], $params['port'], $params['database'], $params['user'], $params['password']); $pdo = new \PDO($conStr); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); return $pdo; > /** * return an instance of the Connection object * @return type */ public static function get() < if (null === static::$conn) < static::$conn = new static(); > return static::$conn; > protected function __construct()  < >private function __clone()  < >private function __wakeup()  < >>Code language: PHP (php)
  • The Connection class is a singleton class. It means that you can create only one instance for the class. If the instance already exists and you try to create a new one, the class will return the existing reference.
  • To connect to a PostgreSQL database, you need to create a new instance of the PDO class. In the connect() method, we read the database configuration parameters in the database.ini file, construct a connection string and pass it to the PDO constructor.

After that, place the following code in the index.php file.

 require 'vendor/autoload.php'; use PostgreSQLTutorial\Connection as Connection; try < Connection::get()->connect(); echo 'A connection to the PostgreSQL database sever has been established successfully.'; > catch (\PDOException $e) < echo $e->getMessage(); >Code language: PHP (php)

PHP throws a \PDOException if there is an exception occurs when connecting to the PostgreSQL database server, therefore, you need to place the code of creating a new PDO object inside the try. catch block to handle the exception.

Run the following composer command to update the autoload files:

>composer dump-autoload -o Generating optimized autoload filesCode language: SQL (Structured Query Language) (sql)

Finally, launch the index.php file from the web browser to test it.

A connection to the PostgreSQL database sever has been established successfully.

If you want to see the exception that may occur, you can change the parameters in the database.ini file to an invalid one and test it.

The following is the error message when the password is invalid.

SQLSTATE[08006] [7] FATAL: password authentication failed for user "postgres"Code language: CSS (css)

And the following is the error message when the database is invalid.

SQLSTATE[08006] [7] FATAL: database "stockss" does not existCode language: SQL (Structured Query Language) (sql)

In this tutorial, you have learned how to connect to the PostgreSQL database from a PHP application using the PDO API. We will reuse the Connection class in the subsequent tutorials.

Источник

Connecting to PostgreSQL

Summary: in this tutorial, you will learn how to connect to a PostgreSQL database server using PHP PDO.

Prerequisites

To make a connection to the PostgreSQL database server using PHP PDO, you need to have:

  • A PostgreSQL database server, a database, and an account with a username and password that can access the database.
  • PHP PDO PostgreSQL driver enabled in the php.ini file.

1) PostgreSQL database parameters

Suppose you have the following PostgreSQL database parameters:

  • A PostgreSQL database server on the localhost .
  • The dvdrental sample database.
  • The account with the user postgres and password postgres that can access the dvdrental database on the local database server

The following creates a new database configuration file named config.php that stores the PostgreSQL database parameters:

 $host= 'localhost'; $db = 'dvdrental'; $user = 'postgres'; $password = 'postgres'; // change to your passwordCode language: HTML, XML (xml)

To use these parameters, you include the config.php file in the script that connects to the PostgreSQL using the require construct.

2) Enable PostgreSQL driver

The PDO_PGSQL is a driver that implements the PDO interface. It allows you to access PostgreSQL databases from PHP.

To check if the PDO_PGSQL driver is enabled, you open the php.ini file. Typically, the php.ini file is located under the php directory. For example, if you use XAMPP on Windows, you can find the php.ini file under the C:\xampp\php directory.

in the php.ini file, you can find the following line:

;extension=php_pdo_pgsql.dll

If you see the comma( ; ) placed at the beginning of the line, it means that the line is commented and the database driver is not enabled.

To enable the driver, you need to uncomment the line by removing the comma ( ; ) like this:

extension=php_pdo_pgsql.dll

After that, you need to restart the web server to apply the change.

PostgreSQL data source name

The data source name or DSN holds database parameters that enable access to a database system. The data source name of the PostgreSQL consists of the following parameters:

  • pgsql: is the DNS prefix.
  • host: the host of the server where the PostgreSQL runs.
  • port: the port to which PostgreSQL listens. The default PostgreSQL’s port is 5432 .
  • dbname: the database name that you want to connect to.
  • And other parameters.

The following shows a DSN that connects to dvdrental database in the local PostgreSQL Server, port 5432:

pgsql:host=localhost;port=5432;dbname=dvdrental;

Connecting to PostgreSQL

The following illustrates how to connect to the dvdrental database in PostgreSQL database server:

 require_once 'config.php'; try < $dsn = "pgsql:host=$host;port=5432;dbname=$db;"; // make a database connection $pdo = new PDO($dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); if ($pdo) < echo "Connected to the $db database successfully!"; > > catch (PDOException $e) < die($e->getMessage()); > finally < if ($pdo) < $pdo = null; > > Code language: HTML, XML (xml)
  • First, make a new connection to the PostgreSQL database by creating a new instance of the PDO class.
  • Second, show a message if the database connection is established successfully; otherwise, show an error message.

The following option instruct PDO to set an error code and throw an exception if an error occurs:

[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]Code language: PHP (php)

PDO has three exception handling options:

  • PDO::ERROR_SILENT – PDO sets an error code for inspecting using the PDO::errorCode() and PDO::errorInfo() methods. The PDO::ERROR_SILENT is the default mode.
  • PDO::ERRMODE_WARNING – Besides setting the error code, PDO will issue an E_WARNING message.
  • PDO::ERRMODE_EXCEPTION – Besides setting the error code, PDO will raise a PDOException .

Note that PHP automatically closes the database connection when the script ends. If you want to close the database connection explicitly, you can set the PDO instance to null:

 $pdo = null;Code language: HTML, XML (xml)

The following connect.php script defines a connect() function that makes a connection to the PostgreSQL database and returns an instance of the PDO class:

 require_once 'config.php'; function connect(string $host, string $db, string $user, string $password): PDO < try < $dsn = "pgsql:host=$host;port=5432;dbname=$db;"; // make a database connection return new PDO( $dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] ); > catch (PDOException $e) < die($e->getMessage()); > > return connect($host, $db, $user, $password);Code language: HTML, XML (xml)

To use this connect.php in a script, you use the require construct as follows:

 $pdo = require 'connect.php'; // start working with the databaseCode language: HTML, XML (xml)

Summary

  • Enable PostgreSQL extension in php.ini file by removing the semicolon ( ; ) from the line extension=php_pdo_pgsql.dll
  • Create a new instance of PDO by passing the data source name (DSN) to its constructor to make a connection to the PostgreSQL database server.

Источник

Читайте также:  Php insert null date
Оцените статью