Php pdo sqlsrv install

Загрузка драйверов Майкрософт для PHP для SQL Server

Эта статья содержит инструкции по загрузке Драйверы Microsoft SQL Server для PHP в пространство процессов PHP.

Предварительно созданные драйверы для платформы можно загрузить на странице драйверов Майкрософт для PHP в SQL Server на сайте GitHub. Каждый пакет установки содержит файлы драйверов SQLSRV и PDO_SQLSRV в потоковых и отдельных вариантах. В Windows они также доступны в 32-разрядных и 64-разрядных версиях. Список файлов драйверов, содержащихся в каждом пакете, см. в статье System Requirements for the Microsoft Drivers for PHP for SQL Server (Системные требования драйверов Майкрософт для PHP для SQL Server). Файл драйвера должен соответствовать версии PHP, архитектуре и потоковости среды PHP.

В Linux и macOS драйверы можно также установить с помощью PECL, как описано в учебнике по установке.

Вы также можете создать драйверы из источника при разработке PHP или с помощью phpize . Если вы решили создать драйверы из источника, можно создать их статически в PHP, а не в качестве общих расширений, добавив —enable-sqlsrv=static —with-pdo_sqlsrv=static (в Linux и macOS) или —enable-sqlsrv=static —with-pdo-sqlsrv=static (в Windows) в команду ./configure при компиляции PHP. Дополнительные сведения о системе сборки PHP и phpize см. в документации по PHP.

Перемещение файла драйвера в каталог расширения

Файл драйвера должен размещаться в каталоге, где среда выполнения PHP сможет его найти. Проще всего разместить файл драйвера в каталоге расширений PHP по умолчанию. Чтобы найти каталог по умолчанию, запустите php -i | sls extension_dir в Windows или php -i | grep extension_dir в Linux/macOS. Если вы не используете каталог расширений по умолчанию, укажите каталог в файле конфигурации PHP (php.ini) с помощью параметра extension_dir. Например, в Windows, если вы поместили файл драйвера в каталог c:\php\ext , добавьте следующую строку в файл php.ini:

Загрузка драйвера при запуске PHP

Чтобы загружать драйвер SQLSRV при запуске PHP, сначала поместите файл драйвера в свой каталог расширений. Затем выполните следующие действия:

    Чтобы включить драйвер SQLSRV, добавьте в файле php.ini следующую строку в раздел расширения и измените имя файла соответствующим образом: В Windows:

extension=php_sqlsrv_82_ts.dll 

В Linux, если вы скачали предварительно созданные двоичные файлы для вашего дистрибутива, запустите следующий код:

extension=php_sqlsrv_82_nts.so 

Если вы выполнили компиляцию двоичного файла SQLSRV из источника или с помощью PECL, файл получит имя sqlsrv.so:

В Linux, если вы установили PHP с помощью диспетчера пакетов системы, PDO, скорее всего, установится как динамически загруженное расширение с именем pdo.so. Расширение PDO нужно загрузить перед расширением PDO_SQLSRV, иначе загрузка завершится ошибкой. Расширения обычно загружаются с использованием отдельных INI-файлов, и эти файлы считываются после файла php.ini. Таким образом, если файл pdo.so загружается с использованием собственного INI-файла, то после PDO понадобится отдельный файл, загружающий драйвер PDO_SQLSRV. Чтобы узнать, в каком каталоге находятся INI-файлы, относящиеся к расширению, запустите php —ini и обратите внимание на каталог, указанный в разделе Scan for additional .ini files in: . Найдите файл, загружающий pdo.so. Возможно, он имеет числовой префикс, например 10-pdo.ini. Числовой префикс указывает порядок загрузки INI-файлов. Файлы, не имеющие числового префикса, загружаются в алфавитном порядке. Создайте файл для загрузки файла драйвера PDO_SQLSRV с именем 30-pdo_sqlsrv.ini (подойдет любое число, большее, чем pdo.ini) или pdo_sqlsrv.ini (если у pdo.ini нет числового префикса) и добавьте в него следующую строку, изменив имя файла на подходящее.

extension=php_pdo_sqlsrv_82_nts.so 

Как и в случае с SQLSRV, если вы выполнили компиляцию двоичного файла PDO_SQLSRV из источника или с помощью PECL, файл получит имя pdo_sqlsrv.so:

Читайте также:  Кнопка включить выключить javascript

Чтобы проверить, загружен ли драйвер, запустите сценарий, который вызывает phpinfo().

Дополнительные сведения о директивах php.ini см. в статье Описание встроенных директив php.ini.

См. также:

Getting Started with the Microsoft Drivers for PHP for SQL Server (Начало работы с драйверами Майкрософт для PHP для SQL Server)

Источник

Microsoft SQL Server Functions (PDO_SQLSRV)

PDO_SQLSRV is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MS SQL Server (starting with SQL Server 2005) and SQL Azure databases.

Installation

The most recent version of the driver is available for download here: » SQLSRV download. The driver sources are hosted in a » public repository.

For more information about system requirements, see » SQLSRV System Requirements.

On Windows the PDO_SQLSRV extension is enabled by downloading and adding appropriate DLL files to your PHP extension directory and the corresponding entry to the php.ini file.

On Linux and macOS, the PDO_SQLSRV extension can be installed using » PECL. See the » installation tutorial for details.

Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the PDO::ATTR_DRIVER_NAME attribute to check the driver, if your code can run against multiple drivers.

PDO::SQLSRV_TXN_READ_UNCOMMITTED ( int ) This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Read Uncommitted. PDO::SQLSRV_TXN_READ_COMMITTED ( int ) This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Read Committed. PDO::SQLSRV_TXN_REPEATABLE_READ ( int ) This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Repeateable Read. PDO::SQLSRV_TXN_SNAPSHOT ( int ) This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Snapshot. PDO::SQLSRV_TXN_SERIALIZABLE ( int ) This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Serializable. PDO::SQLSRV_ENCODING_BINARY ( int ) Specifies that data is sent/retrieved as a raw byte stream to/from the server without performing encoding or translation. This constant can be passed to PDOStatement::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam. PDO::SQLSRV_ENCODING_SYSTEM ( int ) Specifies that data is sent/retrieved to/from the server as 8-bit characters as specified in the code page of the Windows locale that is set on the system. Any multi-byte characters or characters that do not map into this code page are substituted with a single byte question mark (?) character. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam. PDO::SQLSRV_ENCODING_UTF8 ( int ) Specifies that data is sent/retrieved to/from the server in UTF-8 encoding. This is the default encoding. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam. PDO::SQLSRV_ENCODING_DEFAULT ( int ) Specifies that data is sent/retrieved to/from the server according to PDO::SQLSRV_ENCODING_SYSTEM if specified during connection. The connection’s encoding is used if specified in a prepare statement. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam. PDO::SQLSRV_ATTR_QUERY_TIMEOUT ( int ) A non-negative integer representing the timeout period, in seconds. Zero (0) is the default and means no timeout. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, and PDO::prepare. PDO::SQLSRV_ATTR_DIRECT_QUERY ( int ) Indicates that a query should be executed directly, without being prepared. This constant can be passed to PDO::setAttribute, and PDO::prepare. For more information, see » Direct and Prepared Statement Execution.

Читайте также:  Путь для include php

Table of Contents

Источник

How to Install the PHP SQLSRV Extension

To install a PECL extension for multiple PHP versions, repeat the PECL extension installation for each PHP version.

The SQLSRV extension provides functions for accessing Microsoft SQL Server databases.

In late 2016, after more than four years of this extension not being updated, Microsoft began releasing updates to greatly improve this extension and add support for PHP 7. As of early 2017, this extension is now considered stable again.

This extension only supports PHP 7.0, 7.1, and 7.2. PHP 7.3 is not yet supported.

Additionally, this extension only supports Ubuntu 16.04 and 18.04. You will not be able to use this extension on Ubuntu 12.04 or 14.04.

You can follow Microsoft’s work on this extension through the PHP SQL Server Team blog.

Installing the SQLSRV Extension on PHP 7.X

To install the PHP SQLSRV extension, SSH in to your server as root and run the following commands to install prerequisites:

curl -s https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - sudo bash -c "curl -s https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /etc/apt/sources.list.d/mssql-release.list" sudo apt-get update sudo ACCEPT_EULA=Y apt-get -y install msodbcsql17 mssql-tools sudo apt-get -y install unixodbc-dev
curl -s https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - sudo bash -c "curl -s https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list" sudo apt-get update sudo ACCEPT_EULA=Y apt-get -y install msodbcsql17 mssql-tools sudo apt-get -y install unixodbc-dev

Next, run the following commands to install the extension:

sudo apt-get -y install gcc g++ make autoconf libc-dev pkg-config sudo pecl7.X-sp install sqlsrv sudo pecl7.X-sp install pdo_sqlsrv

Once installed, create configuration files for the extension and restart PHP by running the following commands as root:

sudo bash -c "echo extension=sqlsrv.so > /etc/php7.X-sp/conf.d/sqlsrv.ini" sudo bash -c "echo extension=pdo_sqlsrv.so > /etc/php7.X-sp/conf.d/pdo_sqlsrv.ini" sudo service php7.X-fpm-sp restart

Possible Errors

If you get the following error while installing prerequisites using the instructions above:

Installation Failed, ODBC Driver 13 for SQL Server Detected!

this may be caused by a previous installation of Microsoft’s msodbcsql package while the new SQLSRV driver was still in development and not yet released. In this case, the solution is to start over with a clean Ubuntu 16.04 server, connect it to ServerPilot, and follow the PHP SQLSRV extension installation steps again on the new server.

Читайте также:  Sqlite java intellij idea

Installing the SQLSRV Extension on PHP 5.X

This extension no longer supports PHP 5.X.

Verifying the Installation

You can verify the SQLSRV extension is installed with the command:

If SQLSRV is installed correctly, you will see the following:

/etc/php7.1-sp/conf.d/pdo_sqlsrv.ini, /etc/php7.1-sp/conf.d/sqlsrv.ini, Registered PHP Streams => https, ftps, compress.zlib, compress.bzip2, php, file, glob, data, http, ftp, zip, phar, sqlsrv PDO drivers => dblib, mysql, odbc, pgsql, sqlite, sqlsrv pdo_sqlsrv pdo_sqlsrv support => enabled pdo_sqlsrv.client_buffer_max_kb_size => 10240 => 10240 pdo_sqlsrv.log_severity => 0 => 0 sqlsrv sqlsrv support => enabled sqlsrv.ClientBufferMaxKBSize => 10240 => 10240 sqlsrv.LogSeverity => 0 => 0 sqlsrv.LogSubsystems => 0 => 0 sqlsrv.WarningsReturnAsErrors => On => On

Uninstalling the SQLSRV Extension

To uninstall this extension, as root run the commands:

sudo rm /etc/phpX.Y-sp/conf.d/sqlsrv.ini sudo rm /etc/phpX.Y-sp/conf.d/pdo_sqlsrv.ini sudo peclX.Y-sp uninstall sqlsrv sudo peclX.Y-sp uninstall pdo_sqlsrv

Next, restart PHP-FPM with the command:

sudo service phpX.Y-fpm-sp restart

Using the PHP SQLSRV Extension

Note that the MSDN Online Documentation for this extension has not yet been updated for PHP 7.

Источник

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