Connect SQL Server with PHP Pages

Connect remote SQL Server 2008 R2 with PHP:

Today i came to know that SQL server can be connected in 2 ways for windows…one is thru mssql_connect(Microsoft is not supporting this one as it is very old procedure) & sqlsrv_connect( this drivers are launched in 2012)

Inorder to work with sql server 2008 R2, first i need to install  SQL Server 2012 Native Client driver along with SQLSRV30.EXE .

Copy all the required dll files(php_pdo_sqlsrv_53_ts_vc9.dll” and “php_sqlsrv_53_ts_vc9.dll” along with vc6.dll files) to ext directory of servers & add these extensions in php.ini file too.Then after activate all the extensions in server.

Restart xampp/wamp server.

Paste this code in php file:

$serverName = “serverName/instanceName”; //serverName\instanceName

$connectionInfo = array(
‘Database’ => ‘Database_name’,
‘UID’ => ‘userid’,
‘PWD’ => ‘password’); // this will work for only sql server authentication not for windows authentication
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
echo “Connection established.<br />”;
}else{
echo “Connection could not be established.<br />”;
die( print_r( sqlsrv_errors(), true));
}

I successfully established connection to my remote server with this procedure. 🙂

For inserting data:

$sql = “INSERT INTO table_name(UId, Pwd) VALUES (?, ?)”;
$params = array(1, “some data”);

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

To Fetch the data:

$sql = “select * from table_name”;
$params = array(5);
$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
else{
while ($result = sqlsrv_fetch_array($stmt))
{
echo $result[UId].” “.$result[Pwd].”<br/>”;
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s