Wednesday, April 5, 2017

Connect MS SQL Server in PHP using Wamp Server

Wamp Server is mostly used server application for PHP development in Window which is combination of Apache, MySql and PHP. So whenever you use Wamp than must work with MySql database. Sometimes you want to connect Microsoft SQL database in PHP using Wamp server than PHP connection function `mysql_connect` not working for connecting MS SQL database.
For connecting MS SQL server PHP provide `sqlsrv_connect` function as below.



$server = "connect.myserver.name";
$username = "Username";
$password = "Password";
$dbname = "MYDATABASE_NAME";
$connectionInfo = array("Database"=>$dbname, "UID" => $username, "PWD" => $password);
$conn = sqlsrv_connect($server, $connectionInfo);
if( $conn === false )
{
    echo "failed connection";
}

When you try to run below function in Wamp it's given error for `sqlsrv_connect` function because of `sqlsrv` service not installed in Wamp server.
So here follow below steps to run `sqlsrv_connect` function on your Wamp server.
  1. Download Microsoft Drivers for PHP for SQL Server from Microsoft site.
  2. When you click on Download button there are different versions display for download.Download version according to your PHP version
    • SQLSRV40.EXE for PHP 7.0+ on Windows and Linux
    • SQLSRV32.EXE for PHP 5.6, 5.5, and 5.4 on Windows
    • SQLSRV31.EXE for PHP 5.5 and 5.4 on Windows
    • SQLSRV30.EXE for PHP 5.4 on Windows
  3. Extact that files on local.
  4. Copy `php_sqlsrv_54_ts.dll` and `php_pdo_sqlsrv_54_ts.dll` to C:\wamp\bin\php\PHP_VERSION0\ext\ folder
  5. Now Open php.ini file from C:\wamp\bin\apache\APACHE_VERSION\bin\ or from WAMP icon.
  6. Add extension for the two drivers by adding these lines below all extensions list in `php.ini` file.
    
    extension=php_sqlsrv_54_ts.dll //for PHP 5.4
    extension=php_pdo_sqlsrv_54_ts.dll //for PHP 5.4
    
    
    and comment out the existing lines below if not commented
    ;extension=php_pdo_mssql.dll 
    ;extension=php_mssql.dll
  7. Now restart Wamp services.
Now you can connect MS SQL Server in Wamp server using `sqlsrv_connect` function.You can use other sqlsrv function according to mysql function.See list of all PHP:SQLSRV functions.