microsoft sql connect php
Загрузка драйверов Майкрософт для PHP для SQL Server
Скачать драйвер PHP
Эта статья содержит инструкции по загрузке Драйверы 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
Чтобы загружать драйвер SQLSRV при запуске PHP, сначала поместите файл драйвера в свой каталог расширений. Затем выполните следующие действия:
Чтобы включить драйвер SQLSRV, добавьте в файле php.ini следующую строку в раздел расширения и измените имя файла соответствующим образом:
В Linux, если вы скачали предварительно созданные двоичные файлы для вашего дистрибутива, запустите следующий код:
Если вы выполнили компиляцию двоичного файла SQLSRV из источника или с помощью PECL, файл получит имя sqlsrv.so:
Чтобы включить драйвер PDO_SQLSRV, расширение PHP Data Objects (PDO) должно быть доступно либо как встроенное расширение, либо как динамически загружаемое.
В Linux, если вы установили PHP с помощью диспетчера пакетов системы, PDO, скорее всего, установится как динамически загруженное расширение с именем pdo.so. Расширение PDO нужно загрузить перед расширением PDO_SQLSRV, иначе загрузка завершится ошибкой. Расширения обычно загружаются с использованием отдельных INI-файлов, и эти файлы считываются после файла php.ini. Таким образом, если файл pdo.so загружается с использованием собственного INI-файла, то после PDO понадобится отдельный файл, загружающий драйвер PDO_SQLSRV.
Как и в случае с SQLSRV, если вы выполнили компиляцию двоичного файла PDO_SQLSRV из источника или с помощью PECL, файл получит имя pdo_sqlsrv.so:
Скопируйте этот файл в каталог, содержащий другие INI-файлы.
Если вы скомпилировали PHP из источника со встроенной поддержкой PDO, то отдельный INI-файл не требуется и можно добавить в файл php.ini соответствующую указанную выше строку.
Чтобы проверить, загружен ли драйвер, запустите сценарий, который вызывает phpinfo().
Дополнительные сведения о директивах php.ini см. в статье Описание встроенных директив php.ini.
См. также:
Getting Started with the Microsoft Drivers for PHP for SQL Server (Начало работы с драйверами Майкрософт для PHP для SQL Server)
Подключение MS SQL к PHP 5.3 и выше
Недавно передо мной встала задача: работать с MS SQL из PHP. Поиск в Google по ключевым словам «php mssql» и подобным дал уйму ссылок с примерно одинаковой инструкцией:
— раскомментировать в php.ini строчку extension=php_mssql.dll;
— перезапустить Апач/Денвер;
— наслаждаться.
Однако выяснилось, что начиная с версии 5.3 в состав дистрибутива PHP это расширение не входит и, более того, не поддерживается. Для работы с MS SQL рекомендуется драйвер SqlSrv от Microsoft. Пошаговой инструкции по работе с ним найти не смог, поэтому после ряда проб и ошибок написал свою, которую и предлагаю вашему вниманию.
Первое, с чем придётся столкнуться — это соответствие версий PHP, MS SQL, SqlSrv и Windows.
SqlSrv доступен двух версий: 2.0 и 3.0. Версия 2.0 работает только c MS SQL 2008, при этом поддерживает PHP версий 5.2 и 5.3; версия 3.0 работает только с MS SQL 2012, а PHP поддерживает версий 5.3 и 5.4. При этом необходимо помнить, что MS SQL 2012 работает только под Windows Vista и выше.
На моей машине стоит Windows XP, поэтому были взяты: MS SQL 2008, PHP 5.3.5 и SqlSrv 2.0.
Сначала нужно установить сам сервер MS SQL; неожиданностей в установке нет, обо всех проблемах установщик сообщает вовремя и даёт возможность исправить. Желательно также установить MS SQL Server Management Studio: средство управления базами данных. Установка похожа на установку сервера.
Установка связки Apache+PHP описывалась много и подробно, так что здесь не будем её касаться.
Если PHP только что установлен, нужно также не забыть раскомментировать строчку
PHP готов к работе. Осталось подготовить MS SQL; дело в том, что после установки у него отключены все клиентские протоколы, кроме «Общая память». Нужно их включить; делается это в приложении SQL Server Configuration Manager, идущая в комплекте с сервером.
Теперь все компоненты настроены, и можно проверять работу всей системы. Для этого подойдёт такой скрипт:
$serverName = «Имя сервера»; // Имя сервера задавалось при установке; его также можно увидеть при запуске Management Studio
Если всё правильно, то на экране будет строчка
И последнее: для работы с базой данных из PHP нужно использовать функции семейства sqlsrv_, а не mssql_.
sqlsrv_connect
Download PHP Driver
Creates a connection resource and opens a connection. By default, the connection is attempted using Windows Authentication.
Syntax
Parameters
$serverName: A string specifying the name of the server to which a connection is being established. An instance name (for example, «myServer\instanceName») or port number (for example, «myServer, 1521») can be included as part of this string. For a complete description of the options available for this parameter, see the Server keyword in the ODBC Driver Connection String Keywords section of Using Connection String Keywords with SQL Native Client.
Also beginning in version 3.0 of the Microsoft Drivers for PHP for SQL Server, you can specify a virtual network name, to connect to an AlwaysOn availability group. For more information about Microsoft Drivers for PHP for SQL Server support for AlwaysOn Availability Groups, see Support for High Availability, Disaster Recovery.
$connectionInfo [OPTIONAL]: An associative array that contains connection attributes (for example, array(«Database» => «AdventureWorks»)). See Connection Options for a list of the supported keys for the array.
Return Value
A PHP connection resource. If a connection cannot be successfully created and opened, false is returned.
Remarks
If values for the UID and PWD keys are not specified in the optional $connectionInfo parameter, the connection will be attempted using Windows Authentication. For more information about connecting to the server, see How to: Connect Using Windows Authentication and How to: Connect Using SQL Server Authentication.
Example
The following example creates and opens a connection using Windows Authentication. The example assumes that SQL Server and the AdventureWorks database are installed on the local computer. All output is written to the console when the example is run from the command line.
How to use PHP to connect to sql server
I want to use PHP to connect to sql server database.
I installed xampp 1.7.0(php 5.2) and SQLSRV20. I’ve added the extensions in php.ini and I get this error:
What does this error message mean and how do I connect to SQL Server?
14 Answers 14
enable mssql in php.ini
if your using sqlsrv_connect you have to download and install MS sql driver for your php. download it here http://www.microsoft.com/en-us/download/details.aspx?id=20098 extract it to your php folder or ext in xampp folder then add this on the end of the line in your php.ini file
im using xampp version 5.5 so its name php_pdo_sqlsrv_55_ts.dll & php_sqlsrv_55_ts.dll
if you are using xampp version 5.5 dll files is not included in the link. hope it helps
Use localhost instead of your IP address.
And also double check your mysql username and password.
for further investigation: print out the mssql error message:
It is also important to specify the port: On MS SQL Server 2000, separate it with a comma:
2)edit php.ini file add below line extension=php_pdo_sqlsrv_55_ts.dll extension=php_sqlsrv_55_ts.dll
MS SQL connect to php
After install you will get some files. Store it in your system temp folder
Add to php.ini file extension=php_sqlsrv_72_ts_x64 (php_sqlsrv_72_ts_x64.dll is your file which your copy in 4th step ) extension=php_pdo_sqlsrv_72_ts_x64 (php_pdo_sqlsrv_72_ts_x64.dll is your file which your copy in 4th step )
$serverName =»DESKTOP-me\MSSQLSERVER01″; (servername\instanceName)
How to: Connect Using Windows Authentication
Download PHP Driver
By default, the Microsoft Drivers for PHP for SQL Server use Windows Authentication to connect to SQL Server. It is important to note that in most scenarios, this means that the Web server’s process identity or thread identity (if the Web server is using impersonation) is used to connect to the server, not an end-user’s identity.
The following points must be considered when you use Windows Authentication to connect to SQL Server:
The credentials under which the Web server’s process (or thread) is running must map to a valid SQL Server login in order to establish a connection.
If SQL Server and the Web server are on different computers, SQL Server must be configured to enable remote connections.
Connection attributes such as Database and ConnectionPooling can be set when you establish a connection. For a complete list of supported connection attributes, see Connection Options.
Windows Authentication should be used to connect to SQL Server whenever possible for the following reasons:
No credentials are passed over the network during authentication; user names and passwords are not embedded in the database connection string. This means that malicious users or attackers cannot obtain the credentials by monitoring the network or by viewing connection strings inside configuration files.
Users are subject to centralized account management; security policies such as password expiration periods, minimum password lengths, and account lockout after multiple invalid logon requests are enforced.
If Windows Authentication is not a practical option, see How to: Connect Using SQL Server Authentication.
SQLSRV example
Using the SQLSRV driver of the Microsoft Drivers for PHP for SQL Server, the following example uses the Windows Authentication to connect to a local instance of SQL Server. After the connection has been established, the server is queried for the login of the user who is accessing the database.
The example assumes that SQL Server and the AdventureWorks database are installed on the local computer. All output is written to the browser when the example is run from the browser.
PDO_SQLSRV example
The following example uses the PDO_SQLSRV driver to accomplish the same task as the previous sample.