The Blog

Connecting to MS SQL 2008 and older from PHP and Apache Posted on

There is a new way of doing it since PHP 3.2 after php_mssql.dll got discontinued.
Start by downloading this Microsoft driver for PHP http://sqlsrvphp.codeplex.com. Read readme to determine which file(s) will match your PHP. Next copy those file to your extension folder of your PHP install, and adjust your php.ini by adding or uncommenting those two lines:
extension=php_sqlsrv_53_ts_vc6.dll
extension=php_pdo_sqlsrv_53_ts_vc6.dll
Those two files were in my case, your might be different.

At the time of writing this document MS driver was 32 bit only, so make sure your php is 32 bit as well.

Restart apache and you should be olmost good to go, you should now see that extension under your phpinfo();

Last step before you connect is to download Microsoft® SQL Server® 2008 R2 Native Client Here you have a choice of two, 32 and 64bit, you need to use one that matches the OS on which you will run the Apache on, and not the PHP architecture, which need to be 32bit anyway for this to work, that’s my experience at least.

If you run MS SQL on the same box as the Apache and PHP then you can skip last step since MS SQL will load the native client most likely.

PHP test example:

$sql_server = "servername";
$sql_user = "username";
$sql_pass = "password";
$sql_db_name = "database";

$connectionInfo = array( "Database"=>$sql_db_name,"UID"=>$sql_user,"PWD"=>$sql_pass);
$conn = sqlsrv_connect($sql_server,$connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = 'SELECT * FROM some_table';
$params = array(1, "some data");

$result = sqlsrv_query( $conn, $sql, $params);
if( $result === false ) {
     die( print_r( sqlsrv_errors(), true));
}

while($row = sqlsrv_fetch_array($result))
{
	print_r($row);
}
This entry was posted in MySQL. Bookmark the permalink.

Please Post Your Comments & Reviews

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



CAPTCHA
Change the CAPTCHA codeSpeak the CAPTCHA code