logo

How to connect to MS SQL Server using PHP

php to ms-sql-server connection

Today we will read how to connect to MS SQL Server using PHP. Normally PHP is bundled in an package having MySql as database all required dlls, extensions and libraries to connect to MySql Database with PHP. When we want to make connection with MS-Sql server we need few extra things like some extensions and a bit different code to connect.

Things required to connect to MS SQL SERVER

  1. Download required dlls
  2. Enable extensions
  3. (Optional) Install MS Sql Server CLI if SQL Server is installed on different PC.
  4. Restart WAMP
  5. Test PHP code to connect to MS Sql

1- Download required dlls to connect to MS SQL Server using PHP

For windows operating systems you can download required dlls from the following link
https://www.microsoft.com/en-us/download/details.aspx?id=20098

for PHP 7.4 use the following Dlls

https://github.com/microsoft/msphpsql/releases/download/v5.8.0/Windows-7.4.zip

for PHP 5.2 > download sqlsrv40.exe from above link.
Run this exe it will ask for folder location to extract dll file.
after completing goto that folder and copy required dlls to php extension folder.

Copy required dlls to PHP extension folder

if you are using php 5.3 copy 4 dll files ending with 54dll
if you are using php 5.6 copy 4 dll files ending with 56dll
and paste in PHP ext folder for me it is C:\wamp64\bin\php\php5.6.35\ext
I have copied the following files

  1. php_pdo_sqlsrv_56_nts.dll
  2. php_pdo_sqlsrv_56_ts.dll
  3. php_sqlsrv_56_nts.dll
  4. php_sqlsrv_56_ts.dll

2- Enable extensions

Goto php.ini file and add the following lines Better to add after other extension entries

3- Install MS Sql Server CLI

If MS Sql Server is installed on the same PC where PHP is installed than this is not required, but if the PC where PHP is installed has no MS SQL server than it will need MS-SQL-SERVER-CLI to operate sql server related commands. for windows operating systems you can download it from the following link, and its installation is easy just few clicks.
https://download.microsoft.com/download/B/E/D/BED73AAC-3C8A-43F5-AF4F-EB4FEA6C8F3A/ENU/x64/sqlncli.msi

4- Restart WAMP

Restart WAMP server, (All Services). it will be better to exit wamp and restart again. For me it was not working with simple restating all services
After restarting we are all done.

5- Test PHP code to connect to MS Sql

TO connect to MS SQL Server create a PHP file and pate the following code, and replace ip, DatabaseName, UserName and YourPassword

Here I will put code snippet for cakephp to MSSql-Server connection also

this is all done, hope this was helpful, write you experience in comments below.

Comments

    Write a Reply or Comment

    Your email address will not be published. Required fields are marked *