Apache php and postgresql on windows

Настройка PHP и PostgreSQL в Windows

Я устанавливаю PHP, Apache и PostgreSQL вручную

PHP и Apache теперь подключены, но PostgreSQL не связан с PHP.

я тестирую с помощью phpinfo ();

Я также настраиваю php.ini следующим образом:

Но почему это не работает.

Этот урок работал для меня:

Расширение PHP будет искать libpq.dll который найден в вашей установке PostgreSQL. Простое исправление заключается в том, чтобы добавить путь, который содержит этот файл в вашу среду PATH.

1) Установка PostgreSQL для Windows

2) добавьте в свою переменную среды «PATH» папку bin установки PostgreSQL: C: \ Program Files \ PostgreSQL \ 9.2 \ bin; (например)

Предполагая, что вы установили PostgreSQL и ваша установка WAMP находится на c: \ wamp, вам нужно скопировать c: \ wamp \ bin \ php \ php5.3.9 \ libpq.dll в c: \ wamp \ bin \ apache \ Apache2.2.11 \ Bin

Убедитесь, что у вас также есть следующие файлы C: \ wamp \ bin \ php \ php5.3.9 \ ext \ php_pdo_pgsql.dll и C: \ wamp \ bin \ php \ php5.3.9 \ ext \ php_pgsql.dll

Кроме того, убедитесь, что вы включили вышеуказанные 2 файла в качестве расширений либо через меню WAMP (щелкните значок WAMP на панели задач, PHP, PHPExtensions, найдите вышеприведенные 2 и «проверьте» их)

Обратите внимание, что php5.3.9 и Apache2.2.11 относятся к моим конкретным версиям PHP и Apache. Откорректируйте те, которые подходят для вашей установки.

У меня была такая же проблема с PHP7 и Apache 2.4 в Windows 10. Для меня было решение добавить следующую строку в httpd.conf ;

Это также означает, что не требуется устанавливать PostgreSQL, если вы просто хотите подключить базу данных PostgreSQL, которая не работает на вашем компьютере.

PHP 5.4.39 в связке с PostgreSQL – настройка подключения и описание основных функций

В материале мы рассмотрим возможность взаимодействия языка программирования PHP версии 5.4.39 с СУБД PostgreSQL 9.1.13, мы научимся связывать PHP и PostgreSQL, узнаем, какие есть функции PHP для работы с PostgreSQL, а также разберем несколько примеров использования этих функций.

Для тех, кто увлекается web-программированием и в частности программированием на PHP не секрет что самой распространенной связкой языка и СУБД является связка PHP и MySQL, но иногда возникает необходимость взаимодействовать и с другими базами, например с PostgreSQL. Кстати, PHP поддерживает работу не только с MySQL и PostgreSQL, но еще и со многими другими СУБД, об этом мы говорили в материале PHP и базы данных. А сегодня мы подробней остановимся именно на работе с PostgreSQL, и начнем мы, конечно же, с вопроса как настроить взаимодействие PHP и PostgreSQL.

Читайте также:  Universal windows installer download

Примечание! В качестве операционной системы у нас будет выступать Windows 7, в качестве web-сервера Apache 2.2.2, версия PHP 5.4.39, версия PostgreSQL 9.1.13.

Настройка подключения PHP и PostgreSQL

Первое что нужно сделать, это убедиться, что в каталоге с PHP присутствует библиотека libpq.dll. Затем в файле php.ini найди строку, отвечающую за подключение модуля PostgreSQL и раскомментировать ее, а именно

Перезапускаем Apache и запускаем phpinfo(), и если Вы найдете блок pgsql, то все, библиотеку PostgreSQL Вы подключили.

Если у Вас нет данного раздела, то попробуйте скопировать libpq.dll из каталога PostgreSQL (по умолчанию C:\Program Files\PostgreSQL и так далее) в каталог с PHP с заменой старого, и перезапустите Apache еще раз.

Основные функции PHP для работы с PostgreSQL

pg_connect – открывает соединение с базой данных, возвращает указатель соединения.

pg_query – выполняет запрос к базе данных, возвращает результат запроса.

pg_fetch_assoc – преобразовывает результат запроса в ассоциативный массив.

pg_close – закрывает соединение с базой данных.

Пример работы перечисленных функций

В данном случае мы подключаемся к серверу, который расположен локально, по порту 5432, к базе testbase под пользователем admin с паролем 12345 и выполняем запрос (просто статические данные) к базе данных, затем мы преобразовываем результат в ассоциативный массив, выводим на экран и закрываем соединение.

pg_num_rows – возвращает количество строк в наборе данных, который вернул нам запрос.

pg_num_fields — возвращает количество полей в наборе данных, который вернул нам запрос.

pg_fetch_result – возвращает одно значение из результата запроса.

pg_fetch_row — преобразовывает результат запроса в массив.

pg_fetch_object – преобразовывает результат запроса в объект.

pg_field_name – возвращает название поля по его номеру.

pg_field_num – возвращает номер поля по его названию.

pg_version – возвращает сведения о протоколе взаимодействия, версии клиента и версии сервера в виде массива.

pg_escape_string – экранирует спецсимволы в строке.

pg_dbname – возвращает название базы данных.

pg_affected_rows – возвращает количество затронутых строк при update, insert и delete.

На этом я предлагаю заканчивать, так как для основ этого достаточно, описание всех функций Вы можете найти на сайте PHP вот здесь, ну все, пока!

Установка и настройка

Содержание

User Contributed Notes 5 notes

This happened to me also with PHP 5.4.1
Copying the offending DLL everywhere didn’t worket, and I don’t have Postgres installed in the server, but also planned to use PHP against different Postgres versions, so the only solution I found that worked was to put in httpd.conf a line like this:

Читайте также:  Код ошибки 0хс00000е9 windows

LoadFile «C:/Program Files/PostgreSQL/8.4/bin/libpq.dll»

but refering to the libpq.dll that comes bundled with PHP, like this:

After that it worked fine to me.

If you get a message like this:
«Php Startup: Unable to load dynamic library ‘C:\php\ext\php_pgsql.dll»

1. In the Configuration File alter the order of the libraries «php_exif.dll» and «php_mbstring.dll», in such a way that is called first the library «php_mbstring.dll»

2. Copy all the libraries in the folder «bin» of your installation of PostgreSQL and paste them into the root folder of Windows

3. Uncomment the line «extension=php_pgsql.dll»
4. Now you should see on the page generated by «phpinfo()» section of PostgreSQL

Unable to load dynamic library ‘C:\\php\\ext\\php_pgsql.dll’ — The specified module could not be found.

copy libpq.dll/all files from zip (if you have php from installer)

add to httpd.conf:

#BEGIN PHP INSTALLER EDITS — REMOVE ONLY ON UNINSTALL
PHPIniDir «c:/PHP/»
Loadfile «C:\php\php5ts.dll»
Loadfile «C:\php\libpq.dll»
LoadModule php5_module «c:/PHP/php5apache2_2.dll»
#END PHP INSTALLER EDITS — REMOVE ONLY ON UNINSTALL
AddHandler application/x-httpd-php .php
AddHandler application/x-httpd-php-source .phps

(in php.ini default: extension_dir =»c:\PHP\ext» )

if it doesn’t work add c:\php (php path) to your windows path (and restart)

tested on php5.2.8 + apache2.2.3

If you get this error on Windows:

Unable to load dynamic library ‘C:/php/ext\\php_pgsql.dll’ — The specified module could not be found.

Try downloading the PostgreSQL binaries-no-install archive from http://www.postgresql.org/ftp/binary/v8.3.5/win32/ (replace 8.3.5 with the latest stable version) and copy these DLLs to C:/WINDOWS/system32/ :

Another windows xp solution for «Unable to load dynamic library ‘php_pgsql.dll’ — The specified module could not be found.»

Add the path of the postgres binaries to the system search-path:

Right click on «My Computer», select «properties», «advanced»-tab, «Environment variables»-button, «System variables»-section, select «path» and click «Edit» and add the path to the postgres binaries at the end, in my case it was «C:\Program Files\PostgreSQL\8.4\bin» and then restart the computer (or at least restart the apache/php processes)

Please note that the system-path can have several values, each separated by a semicolon «;».

Configure PHP and PostgreSQL on Windows

I’m installing PHP, Apache and PostgreSQL Manually

PHP and Apache now is connected, but PostgreSQL is not connected to PHP.

i test by using phpinfo();

i also configure in php.ini like this :

But why it’s not work.

Читайте также:  Настройка rclone для windows

5 Answers 5

The PHP extension will look for libpq.dll which is found of your PostgreSQL installation. The simple fix is to add the path than contains that file to your environment PATH.

I had the same issue with PHP7 and Apache 2.4 on Windows 10. For me the solution was to add the following line to httpd.conf ;

This also means that it’s not required to have PostgreSQL installed if you just want to connect a PostgreSQL database that’s not running on your machine.

1) Installing PostgreSQL for Windows

2) add to your enviroment variable «PATH» the bin folder of PostgreSQL installation: C:\Program Files\PostgreSQL\9.2\bin; (for example)

Assuming you have installed PostgreSQL and your WAMP installation is on c:\wamp, you will need to copy c:\wamp\bin\php\php5.3.9\libpq.dll to c:\wamp\bin\apache\Apache2.2.11\bin

Make sure you also have the following files C:\wamp\bin\php\php5.3.9\ext\php_pdo_pgsql.dll and C:\wamp\bin\php\php5.3.9\ext\php_pgsql.dll

Also, make sure you have enabled the above 2 files as extensions, either via the WAMP menu (click on WAMP icon on taskbar, PHP, PHPExtensions, find the above 2 and ‘check’ them)

Please note that php5.3.9 and Apache2.2.11 refer to my specific PHP and Apache versions. Adjust those to suit your installation.

How do I enable php to work with postgresql?

I get the error message «Could Not Load Driver»

11 Answers 11

Uncomment the following in php.ini by removing the «;»

Use the following code to connect to a postgresql database server:

You need to install the pgsql module for php. In debian/ubuntu is something like this:

Or if the package is installed, you need to enable de module in php.ini

For debian/ubuntu install

I have to add in httpd.conf this line (Windows):

  • SO: Windows/Linux
  • HTTP Web Server: Apache
  • Programming language: PHP

Enable PHP to work with PostgreSQL in Apache

In Apache I edit the following configuration file: C:\xampp\php.ini

I make sure to have the following lines uncommented:

Finally restart Apache before attempting a new connection to the database engine.

Also, I leave my code that ensures that the connection is unique:

just install the database driver:

apt-get install php5-pgsql php5-mysql php5-sqlite . and so on .

I installed PHP on windows IIS using Windows Platform Installer (WPΙ). WPΙ creates a «PHP Manager» tool in «Internet Information Services (IIS) Manager» console. I am configuring PHP using this tool.

PDO and all the major drivers ship with PHP as shared extensions, and simply need to be activated by editing the php.ini file: extension=php_pdo.dll

so i activated the extension using PHP Manager and now PDO works fine

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