Progress28.ru

IT Новости
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Php sqlsrv dll

Как подключиться к Microsoft SQL Server через PHP

В этой статье мы расскажем о всех тонкостях подключения к MS SQL серверу, для работы с ним через PHP .

Мы будем рассматривать SQL Server 2014 . На ранних версиях этот процесс может немного отличаться.

Давайте определим, что мы уже имеет установленный пакет SQL Server на каком то VPS или сервере с ОС Windows (Например, заказанного у ihc.ru), либо установленный на вашем локальном компьютере для тестов.

Так же соответственно на сервере стоит PHP версии 5.2+ или у вас установлен локальный сервер, вроде OpenServer .

Теперь нужно скачать и установить PHP driver для SQL Server — вот ссылка на официальный сайт.

На данный момент там есть четыре версии драйвера 2.0, 3.0, 3.1, 3.2. Далее приведена таблица с совместимостью с PHP :

Так же приведем таблицу поддержки разных версий MS SQL Server :

Microsoft Drivers for PHP for SQL Server VersionSupported PHP Versions

Windows Server 2008 R2 SP1

Windows Server 2008 SP2

Windows Server 2012

Windows Server 2012 R2

Windows Server 2008 R2 SP1

Windows Server 2008 SP2

Windows Server 2003 Service Pack 1

Windows Server 2008 R2

Windows Server 2008

Мы для проверки выбрали драйвер версии 3.2 для сервера 2014 года. После скачивания распакуйте полученные файлы в какую-нибудь временную папку. Получите примерно такой список файлов:

  • PHP Drivers License Terms.rtf
  • php_pdo_sqlsrv_54_nts.dll
  • php_pdo_sqlsrv_54_ts.dll
  • php_pdo_sqlsrv_55_nts.dll
  • php_pdo_sqlsrv_55_ts.dll
  • php_pdo_sqlsrv_56_nts.dll
  • php_pdo_sqlsrv_56_ts.dll
  • php_sqlsrv_54_nts.dll
  • php_sqlsrv_54_ts.dll
  • php_sqlsrv_55_nts.dll
  • php_sqlsrv_55_ts.dll
  • php_sqlsrv_56_nts.dll
  • php_sqlsrv_56_ts.dll
  • release.txt
  • SQLSRV_Readme.htm
  • SQLSRV_ThirdPartyNotices.rtf

Нас здесь интересуют только библиотеки с форматом dll . Библиотеки с приставкой php_pdo отметаем сразу. Остается список из файлов:

  • php_sqlsrv_54_nts.dll
  • php_sqlsrv_54_ts.dll
  • php_sqlsrv_55_nts.dll
  • php_sqlsrv_55_ts.dll
  • php_sqlsrv_56_nts.dll
  • php_sqlsrv_ 56_ts.dll

Здесь после приставки php_sqlsrv_ идут две цифры, это версия PHP , и следующие символы определяют Thread Safety , режим которого можно посмотреть в информации о вашем PHP , смотрится в phpinfo() . Если в графе стоит enabled , то выбираем версию с приставкой _ts и иначе — _nts .

После того как вы определились с файлом драйвера, который нужен вам, переходим к настройке php.ini . В первую очередь находим там строчку extension_dir = и удостоверяемся, что она не закомментирована, она указывает путь к расширениям, именно по этому пути открываем соответствующую директорию и закидываем туда библиотеку драйвера, в нашем случае это был php_sqlsrv_54_ts.dll , у вас может быть другая версия драйвера.

Теперь добавляем в php.ini строку с подключением драйвера extension=php_sqlsrv_54_ts.dll . Перезапускаем сервер и проверяем phpinfo() . Если всё произошло успешно вы должны обнаружить блок sqlsrv :

Теперь проверяем соединение с БД при помощи следующего шаблона:

Если получаем «Connection established.» — радуемся. Если «Connection could not be established.» и гору сообщений об ошибках, то перечитываем статью, после этого уже пишем в комментарии.

Мы пробовали всё на локальном компьютере — сервер OpenServer , версия PHP — 5.4.44, MS SQL Server 2014, имя БД — StudyBD .

Напоследок так же ссылка на на описание API драйвера.

Connecting PHP to MS SQL Server

php_sqlsrv.dll is PHP’s Database Driver for MS SQL Server, that has replaced php_mssql.dll (which no longer exists in PHP 5.3 and above).

While the php_sqlsrv API is not the same as the php_mssql API, php_sqlsrv can be used through php_pdo_sqlsrv, which provides the common PDO Database interface that can access MS SQL Server. php_sqlsrv can also be used directly (without the PDO abstraction).

There is 1 official build of php_sqlsrv.dll by Microsoft that is provided for PHP 5.3. And several unofficial builds of php_sqlsrv.dll for PHP 5.6, 5.5, 5.3 (32 bit and 64 bit).

PHP 5.5 Driver for MS SQL Server

In the OneDrive folder, right-click on file “sqlsrv_unofficial_3.0.2.2.zip” and select “Download”.

Inside of file sqlsrv_unofficial_3.0.2.2.zip, extract these files out:

Files:
php_pdo_sqlsrv_55_ts.dll
php_sqlsrv_55_ts.dll

Files:
php_pdo_sqlsrv_55_nts.dll
php_sqlsrv_55_nts.dll

* The above PHP paths are WampDeveloper Pro’s. If you are using another WAMP (such as Xampp or WampServer), just substitute in its own path.

Microsoft’s PHP 5.3 Driver for MS SQL Server

Download file:
SQLSRV30.EXE

This file is not really an EXE (it’s a compressed CAB file), and if you try to run it Windows will display error message: “sqlsrv30.exe is not a valid win32 application”.

You will need to open (not run) SQLSRV30.EXE with either of these un/compression programs: WinRar, or 7-Zip (I use 7-Zip myself, it’s free and open source).

Inside of file SQLSRV30.EXE, extract these files out:

Files:
php_pdo_sqlsrv_53_ts.dll
php_sqlsrv_53_ts.dll

Files:
php_pdo_sqlsrv_53_nts.dll
php_sqlsrv_53_nts.dll

* The above PHP versions are WampDeveloper Pro’s (v5.1.0.1) latest PHP 5.3 releases (regular PHP and FCGI-PHP).

Then via Components Tab, switch WampDeveloper from using Channel: Current (Apache 2.4 + PHP 5.5 + MySQL 5.6) to Stable (Apache 2.2 + PHP 5.3 + MySQL 5.5)…
http://www.devside.net/wamp-server/howto-switch-wampdevelopers-apache-php-mysql-branches

Load php_sqlsrv.dll

Rename the files under all PHP versions to:
php_pdo_sqlsrv.dll
php_sqlsrv.dll

Edit file php.ini, and insert the loading of “php_sqlsrv.dll”…

Save file. Restart Apache.

Links

“Microsoft Drivers for PHP for SQL Server” project
http://sqlsrvphp.codeplex.com/

“Update For PHP 5.5″ discussion
http://sqlsrvphp.codeplex.com/discussions/441706

“Data Developer Center SQL Server Driver for PHP” page
http://msdn.microsoft.com/en-us/data/ff657782.aspx

“Accessing SQL Server Databases from PHP”
http://social.technet.microsoft.com/wiki/contents/articles/1258.accessing-sql-server-databases-from-php.aspx

8 thoughts on “Connecting PHP to MS SQL Server”

Hello Sir,
I m using php version 5.5.12 and i did all the task which you mentioned in this page but still i m getting “Call to undefined function sqlsrv_connect() ” error

Check Apache’s and PHP’s error logs… Both the general and the website specific logs.

It is likely that PHP was unable to load file php_sqlsrv.dll because the build between PHP and php_sqlsrv.dll are not matching…

The php_sqlsrv.dll build has to be for:

1. The same PHP branch:
PHP 5.5

2. The same PHP bit version:
32 bit

3. The same PHP run-type:
TS (Thread Safe) or Regular – for PHP.
NTS (Not Thread Safe) or FCGI – for PHP-FCGI.

sir this code is not running undefined function mssql_connect() plz help me

mssql_connect() is a function from the php_mssql.dll PHP extension.

The php_mssql.dll PHP extension is only available under the older PHP 5.2 version.

A. Switch to the PHP 5.2 branch (if using a WAMP such as WampDeveloper) and load php_mssql.dll in php.ini.

B. Or you can try to locate all instances of mssql_ in your script, and update those lines to use the functions of the php_sqlsrv.dll driver (or to the database-neutral PDO interface).

I am getting this error in my error log.

‘php_sqlsrv_55_ts.dll’ – %1 is not a valid Win32 application

At first thank you for the awesome and useful page!

I am using latest WAMP 2.5 32bit version under Win 8.1.

Php version is 5.5.12. I am seeing that it has php5ts.dll in php folder. I did the regular install as per wamp website download.

I am using the ts version, but when I am trying to connect I am getting this:

Rob’s Area for PHP on Windows

Programming used to be fun. Thanks to PHP’s support for Windows builds, you can run very efficient web sites on Windows and have a good time making them. This blog is a small collection of the additional things I’ve needed to help me build a few sites.

Friday, 7 September 2012

How to install Microsoft’s SQL Server Driver for PHP

There are questions on Microsoft’s SQL Server driver for PHP forum from people that cannot work out how to install the PHP driver.

It’s still a bit complicated, so here are some explicit instructions which I hope can help new users of PHP. After a while all of this will become common sense.

Instruction notes:

  1. Microsoft’s PHP driver for SQL Server only runs with PHP 32-bit builds (as standard from http://windows.php.net/download).
  2. These instructions are only for PHP 5.2, 5.3 or 5.4. (5.5 and 5.6 supported with custom build.)
  3. I am pretending that PHP is installed into folder C:PHP . Replace the term C:PHP in the instructions with whatever folder your PHP is installed into.
  4. See orange text for PHP 5.5 and 5.6 support in 32 and 64 bits. If you do not know whether you have 64-bit PHP 5.5/5.6, start the instructions at step 5, note the orange comment in 5.3, then return to step 1 of the instructions below.

Instructions:

  1. Download Microsoft’s PHP drivers. Open page: http://www.microsoft.com/en-us/download/details.aspx? >If you have PHP 5.5/5.6, or you have Windows XP/2003 and you want to install driver 3.0.
    1. See this post: Unofficial php_sqlsrv 3.0 and download the archive
    2. Note the text in orange in step (2.) below — you don’t need to extract the ‘source code’ folder. Also.
      1. If you have 64-bit PHP, you need to extract only the files in sub-folder x64 of the zip file, and can ignore everything else.
      2. If you have 32-bit PHP, you should ignore the folder x64 in the zip file.
    3. Assume for step (6.) below that you downloaded SQLSRV30.EXE
    4. Remember that PHP 5.5+ does not work on Windows XP/2003 — for this OS you can only go up to PHP 5.4.
  • Extract the entire contents of the file downloaded in (1.) to your PHP extensions folder. This is usually a sub-folder of the location where php is installed, named ‘ext’, e.g. C:PHP ext.
    Note that you can use WinRAR to open the .exe file and extract the files, if you want.

    1. Open a command window (run cmd.exe)
    2. Using your PHP folder, run command: » C:PHP php.exe» -i | more
      ‘more’ loads the information page by page.
    3. The top line will show PHP Version => 5.x.x. Make a note of the version. It will start with 5.6, 5.5, 5.4, 5.3 or 5.2. The final (3rd) number is not important. PHP 5.5+ users can also tell if they have a 64-bit or 32-bit version of PHP by looking at the reported Architecture: x86 = 32-bit and x64 = 64-bit. For the next steps you may need to scroll to the 2nd information page in the console window, by pressing the space bar.
    4. For version 5.6, 5.5, 5.4 and 5.3, a little further down is setting PHP Extension Build => API. It will end with either . TS,VCn or . NTS,VCn. Make a note of whether it says TS or NTS. Also make a note of whether the final part is VC11, VC9 or VC6 (VC6 is still possible with PHP 5.3 and SQLSRV20.EXE).
    5. For PHP version 5.2 only: note the setting that says «Thread Safety enabled» or «Thread Safety disabled».
      «Thread Safety enabled» means TS,VC6
      «Thread Safety disabled» means NTS,VC6.
  • Edit your php configuration file, php.ini. Go to the end of the file and add these lines, depending on your earlier choices. You need to know your PHP version number (5.2, 5.3, 5.4, 5.5 or 5.6), and your TS/NTS setting, and whether you have a VC11, VC9 or VC6 build, all noted from step 5. above.

    You can calculate the files you need by looking at the file name and comparing to your PHP version, and remembering whether you downloaded SQLSRV20.exe or SQLSRV30.exe. Here are all of the combinations that are possible:

      For the custom drivers, PHP 5.6, NTS, VC11 add lines:

    Php sqlsrv dll

    Вопрос

    Still getting the same error

    php_sqlsrv_54_nts.dll’ — %1 is not a valid Win32 application.

    I have installed the latest version of IIS i guess it is 7.5 and using PHP Manager to enable the extension.

    The error log still shows the same error

    Can you please suggest some help

    • Разделено Jonathan Guerin 24 сентября 2012 г. 20:30 Off-topic

    Ответы

    • Изменено Robert Johnson 17 октября 2012 г. 12:31
    • Предложено в качестве ответа Jonathan Guerin 17 октября 2012 г. 23:46
    • Помечено в качестве ответа Jonathan Guerin 28 ноября 2012 г. 5:49

    Все ответы

    How did you install the PHP runtime? Is it 64-bit, or 32-bit?

    This posting is provided ‘AS IS’ with no warranties, and confers no rights.

    Follow these instructions to get PHP 5.4.7 vc9 nts on Windows Server 2008 R2 64-bit (current — September 24, 20120) installed on your computer:

    0. First in IIS make sure to install cgi role: In the SERVER MANAGER, Add Role Services, choose to add/install CGI. I believe this is needed for FastCGI to work in php.

    1. Next download the old version 5.3.17 here — http://windows.php.net/downloads/releases/php-5.3.17-nts-Win32-VC9-x86.msi , the reason is this old version comes as an installer and handles most of the setup like installing php as fastcgi and registry/file permissions etc.

    3. Extract the zip file to the exact same directory you installed php to. For instance if you installed PHP to c:program files (x86)php then extract to the same folder — DO NOT OVERWRITE the php.ini file — DO NOT OVERWRITE THE php.ini file!

    4. You may or may not need to do this — on the following directories change the permissions to READ and WRITE , right click on these folders, click PROPERTIES, then click SECURITY tab — then add the user IUSR to the folder permission, give only the READ and the WRITE permission

    — c:windowstemp

    — c:inetpubwwwroot

    This allows php to read and write to these folders, the first one allows you to write temp files and session cookies to the temp directory, the second is where your websites are located in IIS, this allows your php scripts to write and read files in those directories.

    5. In your php.ini file you may need to make these changes, depending on what you need for your php install:

    default_socket_timeout = 60
    upload_tmp_dir=»C:WindowsTemp»
    session.save_path=»C:WindowsTemp»
    log_errors=On
    error_log=»C:Windowstempphp-errors.log»
    cgi.force_redirect=0
    fastcgi.impersonate=1
    fastcgi.logging=0
    max_execution_time=300
    extension_dir=»C:Program Files (x86)PHPext»

    6. Restart IIS and test if PHP is working before preceeding to get MSSQL/SQL Azure extension working with php. If it doesn’t work then try again from step one. Uninstall php and reinstall, don’t upgrade to latest version — test if the installer version works and if it does backup the php.ini and then extract and test with updated version of php.

    7. Now for MSSQL/SQL Azure do the following:

    Extract the driver files anywhere temporarily then copy the single file php_sqlsrv_54_nts.dll to c:program files (x86)phpext or whichever directory you installed php in and set as the extension directory.

    — In your php.ini file add this near the bottom of the file:

    [PHP_MSSQLDRV]
    extension=php_sqlsrv_54_nts.dll

    8. Install the management tools and sql native client — I believe this is only really needed for SQL Azure databases and/or to programmatically access MSSQL/SQL Azure: http://www.microsoft.com/en-us/download/details.aspx? >

    This should now let you use MSSQL or SQL Azure with the current version of PHP.

    Читать еще:  Ошибка google play market
    Ссылка на основную публикацию
    Adblock
    detector
  • Microsoft Drivers for PHP for SQL Server VersionSupported Windows Server