Php pgsql driver install

How to Use PostgreSQL PDO Driver with PHP Part 1

This tutorial will explain how to connect PHP to PostgreSQL with the PDO driver and create the PHP project structure with Composer, a dependency-management tool in PHP. Compose allows for verifying the libraries a project requires and it will install and update the libraries as needed. Be sure all the prerequisites are properly in place before beginning the exercises in this tutorial.

Prerequisites to Connect PHP to PostgreSQL with the PDO Driver.

  • PHP must be properly installed and configured. Check for the current PHP installation version by executing the php -v command. The result should look something like the following in the Linux system:

PHP 7.3.7- 2 +ubuntu18.04.1+deb.sury.org+ 1 ( cli ) ( built: Jul 25 2019 11 : 44 : 59 ) ( NTS )
Copyright ( c ) 1997 — 2018 The PHP Group
Zend Engine v3.3.7, Copyright ( c ) 1998 — 2018 Zend Technologies
with Zend OPcache v7.3.7- 2 +ubuntu18.04.1+deb.sury.org+ 1 , Copyright ( c ) 1999 — 2018 , by Zend Technologies

The result should resemble the following in a Windows system:

PHP 7 . 3 . 5 ( cli ) ( built : May 1 2019 13 : 17 : 17 ) ( ZTS MSVC15 ( Visual C ++ 2017 ) x64 )
Copyright ( c ) 1997 — 2018 The PHP Group
Zend Engine v3 . 3 . 5 , Copyright ( c ) 1998 — 2018 Zend Technologies

Execute the following command to start the PostgreSQL server:

Now execute the following command to verify the service is running:

The result should resemble the following:

— postgresql.service — PostgreSQL RDBMS
Loaded: loaded ( / lib / systemd / system / postgresql.service; enabled; vendor prese
Active: active ( exited ) since Thu 2019 -08-01 14 : 51 : 20 PST; 36min ago
Process: 1230 ExecStart = / bin / true ( code =exited, status = 0 / SUCCESS )
Main PID: 1230 ( code =exited, status = 0 / SUCCESS )

Aug 01 14 : 51 : 20 user-UX330UAK systemd [ 1 ] : Starting PostgreSQL RDBMS.
Aug 01 14 : 51 : 20 user-UX330UAK systemd [ 1 ] : Started PostgreSQL RDBMS.
lines 1 — 8 / 8 ( END )

  • Composer must be properly installed and configured. Entering the composer –version command should return the following results:

PDO and PHP Data Objects

The PHP data objects, or PDO, defines a lightweight, unified interface for accessing the relational databases, or RDB, in PHP. Each database defines the driver specific to that database that implements the PDO interface. Each driver can also reveal the database-specific functions as a normal extension of the functions.

Читайте также:  Программирование javascript что нужно

NOTE: Most PHP distributions includes PostgreSQL extension PDO_PGSQL by default. However, the extension can be edited in the php.ini file. Just remove the prefixed semicolon (;) to uncomment the following line with ;extension=php_pdo_pgsql.dll .

How to Create the PHP Project Structure with Composer

This section will explain how to use Composer to create the project-directory structure.

  1. Create a folder and name it something meaningful, in this case the folder will be named for the project directory as “postgreSQL_php”.
  2. Create a sub-folder and name it “control.” Then create a json file named composer.json and put the following json script inside the control file:

The above script handles the mapping of every class that will be created and added to the PostgreSQL namespace.

NOTE: The PHP Standard Recommendations isPSR-4: Improved Autoloading for using FQCN in a file path.

  1. Navigate to the project directory via the terminal then execute the below command. Note that in this case the system project directory is located at “var/www/html/postgreSQL_php”.

The above Composer command will download the declared libraries within the composer.json file and will generate an autoload file. Composer will also create a folder named vendor and insert all of the third-party libraries in it. However, in this case no third-party library was specified so composer will only generate the autoload file. The results should resemble the following.

Loading composer repositories with package information
Updating dependencies ( including require-dev )
Nothing to install or update
Generating autoload files

  1. Create a PHP file named index.PHP in the root project directory using the following touch command:
  1. Create two additional files within the control folder named connection.php and config.ini and then repeat the same process used in the previous section in sequence.

To verify the following file was created, use the ls command. The results should resemble the following:

How to Create a PostgreSQL Database

Execute the following command in the terminal to create a database where the connection can be tested later:

Execute the following command, in sequence, to verify the database was successfully created:

The result should resemble the following:

List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
—————+———-+———-+————-+————-+————————
postgres | postgres | UTF8 | en_PH.UTF- 8 | en_PH.UTF- 8 |
template0 | postgres | UTF8 | en_PH.UTF- 8 | en_PH.UTF- 8 | =c / postgres +
| | | | | postgres =CTc / postgres
template1 | postgres | UTF8 | en_PH.UTF- 8 | en_PH.UTF- 8 | =c / postgres +
| | | | | postgres =CTc / postgres
testDatabase | postgres | UTF8 | en_PH.UTF- 8 | en_PH.UTF- 8 |
( 4 rows )

The above are the results for the database testDatabase .

How to Connect PHP to the PostgreSQL Database

With the project and the database properly set up, add functionalities to the files that were created in the previous section.

The Configuration for config.ini

Open the config.ini using the nano editor and add the following configuration by executing the following command:

Now add the following PostgreSQL database parameters:

Читайте также:  Компилятор javascript vs code

How to create the PHP code for the connection.php

Now create a PHP class named Connection inside the connection.php file with the same process used in the previous section. However, this time edit the connection.php file using nano with the following commands:

Now add the following PHP script in the connection.php:

/**
* Represents the Connection
*/
class Connection {

/**
* The Connection
* @var type
*/
private static $conn ;

/**
* Connect to the database and return an instance of PDO object
* @return PDO
* @throws Exception
*/
public function connect ( ) {

// The following script will parse the parameters in the config.ini configuration file
$params = parse_ini_file ( ‘config.ini’ ) ;
if ( $params === false ) {
throw new Exception ( «Error reading database configuration file» ) ;
}
// connect to the postgresql database from the config.file parameters
$conStr = sprintf ( «pgsql:host= %s ;dbname= %s ;user= %s ;password= %s » ,
$params [ ‘host’ ] ,
$params [ ‘database’ ] ,
$params [ ‘user’ ] ,
$params [ ‘password’ ] ) ;

$pdo = new PDO ( $conStr ) ;
$pdo -> setAttribute ( PDO :: ATTR_ERRMODE , PDO :: ERRMODE_EXCEPTION ) ;

/**
* return an instance of the Connection object
* @return type
*/
public static function get ( ) {
if ( null === static :: $conn ) {
static :: $conn = new static ( ) ;
}

The above code is a bit lengthy. Here is a breakdown:

  1. A singleton class Connection class was used. This will create only one instance and if an instance already exists while trying to create a new one, the class returns the reference to the old instance.
  2. Before connecting to a PostgreSQL database a new PDO instance class must be created.

The PHP code for the index.php

Below is the PHP script of the index.php file:

use PostgreSQLPHPConnection as Connection ;

try {
Connection :: get ( ) -> connect ( ) ;
echo ‘PostgreSQL Server : database connection has been established successfully.’ ;
} catch ( PDOException $e ) {
echo $e -> getMessage ( ) ;
}
?>

The above code will catch a PDOException , if one should occur when connecting to the PostgreSQL database server.

With the connection setup, now update the autoload files using the following command:

NOTE: Be sure to be in the project root directory when executing the above command.

The result should be: Generating optimized autoload files .

How to Test the PostgreSQL Connection with PHP

With the PHP scripts and configuration set up, test the new program using the built-in Webserver, however, this feature is only available in PHP versions 5.4 and above. Navigate to the project directory and run the following command:

The results should resemble the following:

Listening on http: // localhost: 9090
Document root is / var / www / html / postgreSQL_php
Press Ctrl-C to quit.

Navigate to the browser and type in localhost:9090 .

The results should resemble the following:

Conclusion

This tutorial covered how to connect PHP to PostgreSQL with the PDO driver. The article explained PDO and PHP data objects and how to create the PHP project structure with Composer. The tutorial also covered how to create a PostgreSQL database, how to connect PHP to the PostgreSQL database, how to create the PHP code, a breakdown of the code and how to test the PostgreSQL connection with PHP. Remember that testing the PostgreSQL connection using the built-in Webserver can only be done in PHP versions 5.4 and above.

Читайте также:  Console log typescript react

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Источник

Функции PostgreSQL (PDO_PGSQL)

PDO_PGSQL — это драйвер, реализующий интерфейс PHP Data Objects (PDO) для доступа к базам данных PostgreSQL.

Типы ресурсов

Этот модуль определяет потоковый ресурс, возвращаемый PDO::pgsqlLOBOpen() .

Установка

Для установки модуля PDO PostgreSQL используйте опцию —with-pdo-pgsql[=DIR], где [=DIR] — необязательное значение, указывающее на директорию установки базы PostgreSQL или путь до pg_config.

Предопределённые константы

Перечисленные ниже константы определены данным драйвером и будут доступны только в случае, если PHP был собран с поддержкой этого модуля, или данный модуль был динамически загружен во время выполнения. Вдобавок, эти зависимые от драйвера константы должны быть использованы только совместно с этим драйвером. Использование атрибутов, специфичных для некоторого драйвера с другим драйвером может вызвать неожиданное поведение. Если ваш код выполняется с несколькими драйверами, то можно использовать функцию PDO::getAttribute() для получения атрибута PDO::ATTR_DRIVER_NAME для проверки драйвера.

PDO::PGSQL_ATTR_DISABLE_PREPARES ( int )

Отправьте запрос и параметры на сервер вместе за один вызов, избегая необходимости отдельно создавать именованный подготовленный оператор. Если запрос будет выполняться только один раз, это может уменьшить задержку, избегая ненужного обхода сервера.

Общие замечания

Замечание:

Поля bytea возвращаются как потоки.

Источник

How to enable PostgreSQL driver for PDO for php 7?

How do you correctly install & enable the PDO drivers for PostGres for php 7?

5 Answers 5

You’ve been running php7.1 while you installed php7.0 pgsql module.

Try php -v to check your version and install php7.1-pgsql .

Also you need to uncomment these lines:

extension=php_pdo_pgsql.dll extension=php_pgsql.dll 

The following worked on Ubuntu 18.04 with php 7.1

sudo apt install php7.1-pgsql sudo phpenmod pdo_pgsql sudo apachectl restart 

In addition to what others said, try:

Please be specific. Which other commands should one use before the one you wrote? Otherwise the answer is not complete.

I have tried the following:

  1. Try php -v to check your version
  2. Install php7.1-pgsql
  3. Enable postgres PDO drivers using sudo phpenmod pdo_pgsql
  4. Restart postgres service.

You must log in to answer this question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.20.43540

Ubuntu and the circle of friends logo are trade marks of Canonical Limited and are used under licence.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью