Connecting Microsoft SQL Server using PHP

Throwing Steps Right away without wasting much time :
3 things you need to have:
  • WAMP/XAMPP installed on your system to run PHP.
  • SQL Server for creating and connecting to Databases etc.
  • PHP Drivers : For bridging SQL Server and PHP.
Latest version of PHP Drivers can be download from this Download link which now supports PHP version 7.x.

Steps for installing PHP drivers:
  • The file that you will download is a nothing but a zip containing some dll files which are nothing but PHP extensions.
  • Find the PHP extension folder for the version you are using and place the files inside that folder.
  • Next open the Php.ini files for the version in use and add the initialization for the dll/plugins files that you just placed in extensions folder cos without initialization those files are good for nothing.
  • Restart the wamp services.
  • Goto Php extension from wamp menu and select the options which are having the same name as those files.
This completes the installation part and now we are all ready to test the connection.

For testing the connection please use the following code where I have added self explanatory comments about what is being done where ,paste it into notepad and save the file with some name and .php extension  in www /http directory of your wamp/xampp setup.

<html>
<head>  
<title>TestConnection</title>  
</head>  
<body>  
<h1 align='center'>TestConnection</h1>  
<h5 align='center'>
This is a demonstration of Microsoft SQLSRV driver for PHP & SQL Server.
</h5>
<br/>  
<?php  
$serverName = "YourSQLServerName";  
$connectionOptions = array("Database"=>"master");  
/* Connect using windows Authentication. */  
$conn = sqlsrv_connect( $serverName, $connectionOptions);  
if( $conn === false )  
die( FormatErrors( sqlsrv_errors() ) );  
else
echo "<h1 align='center'>Connection Established</h1>  ";
/*Give a little bit formatted error messages in case of failure in connection */
function FormatErrors( $errors )  
{  
    /* Display errors. */  
    echo "<b>Connection Failed, Error information: <br/><br/></b>";  
    foreach ( $errors as $error )  
    {  
        echo "<b>SQLSTATE:</b>".$error['SQLSTATE']."<br/>";  
        echo "<b>Code:</b>".$error['code']."<br/>";  
        echo "<b>Message:</b>".$error['message']."<br/>";  
    }  
}
/* Free the connection resources. */  
sqlsrv_close( $conn );  
?>
</body>
</html>

Now launch your browser and visit the URL http:\\localhost\YourFileName.php
This should flash the connection established message which means your playground is ready and now what game you play on it depends on you.
I hope this helps !

Comments

Popular posts from this blog

Adding Home Older Newer Post Buttons in new Blogger templates such as Contempo

Adding copy to clipboard button to every google code prettify pre blocks in blogger

Checklist: Before applying for adsense