Search code examples
phpsql-serversql-server-2014

Connection failed to MSSQL in php


I'm using SQL Server 2014 and I have this code to connect to my sql server :

<?php 

$serverName = "DESKTOP-P87SVPI\MSSQLSERVER";

$connectionInfo = array("Database"=>"map2");

$conn = sqlsrv_connect($serverName,$connectionInfo);

if ($conn){
echo "finally";
}
else {
print_r( sqlsrv_errors());

}
?>

I got this error :

Array ( [0] => Array ( [0] => 08001 [SQLSTATE] => 08001 1 => 87 [code] => 87 2 => [Microsoft][ODBC Driver 11 for SQL Server]SQL Server Network Interfaces: Connection string is not valid [87]. [message] => [Microsoft][ODBC Driver 11 for SQL Server]SQL Server Network Interfaces: Connection string is not valid [87]. ) 1 => Array ( [0] => HYT00 [SQLSTATE] => HYT00 1 => 0 [code] => 0 2 => [Microsoft][ODBC Driver 11 for SQL Server]Login timeout expired [message] => [Microsoft][ODBC Driver 11 for SQL Server]Login timeout expired ) 2 => Array ( [0] => 08001 [SQLSTATE] => 08001 1 => 87 [code] => 87 2 => [Microsoft][ODBC Driver 11 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. [message] => [Microsoft][ODBC Driver 11 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. ) )

I checked this in MSSQL:

select @@servername + '\' + @@servicename

And it's the same :

DESKTOP-P87SVPI\MSSQLSERVER

And These are the drivers I have in phpInfo(): enter image description here

Also I checked the remote connection in MSSQL and it's allowed.

How to fix this ?


Solution

  • I used this code to connect but also having problem so I added ConnectionPooling=0 in the connection then it worked !

     try {
    
    
    $conn = new PDO("sqlsrv:server=serverName\serverInstance,1433;Database=db;ConnectionPooling=0", "user", "pass");
    
    } catch (PDOException $e) {
    
        echo $e->getMessage();
    }