Web20 University

Can PHP Connect to MS SQL Server?

Yes, PHP can connect to SQL Server using various methods. You can use the SQLSRV extension provided by Microsoft, PDO (PHP Data Objects), or the older (and removed as of PHP 7.0.0) mssql functions. For this example, let’s use the SQLSRV extension.

You’ll first need to ensure that the SQLSRV extension is installed and enabled in your PHP environment.

Here’s a simple example of connecting to an SQL Server database, running a query, and printing the results:

<?php
$serverName = "localhost";
$connectionOptions = array(
    "Database" => "db_name", 
    "Uid" => "username", 
    "PWD" => "password"
);

//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);

//Select Query
$tsql= "SELECT column_name FROM table_name";
$getResults= sqlsrv_query($conn, $tsql);
if ($getResults == FALSE)
    die(FormatErrors(sqlsrv_errors()));
?>
<h1> Results : </h1>
<?php
while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {
    echo $row['column_name'].", ";
}
sqlsrv_free_stmt($getResults);
?>

Just replace “localhost” with your server’s name, “db_name” with your database’s name, “username” with your SQL Server username, and “password” with your password. You’ll also want to replace “column_name” and “table_name” with the actual column and table names from your database.

Please note:

  1. This is a very basic example and for the real application, you will need to use better error handling and security practices.

  2. This code assumes that you’re running it on a server that can reach the SQL Server instance, and that the SQL Server is configured to accept connections from the PHP server.

  3. PHP 7.0.0 removed the original MSSQL extension, and PHP 5.5 deprecated it. The above example uses the SQLSRV extension which is provided by Microsoft.