Search code examples
phpsql-serverwindows-authentication

PHP: How do I establish a connection to my SQL Server?


I usually use my SQL Server with SQL Server Management Studio. When logging in there I use Windows Authentication and do not specify a Username/Password. So the username/password I'm using at the moment is the same I use logging onto my computer. I'm attempting to establish a connection to the server through PHP; however, I get the an error. Anyone know what I am doing wrong?

Code

    $serverName = "MYPCNAME"; 

    $connectionInfo = array( "Database"=>"College", "UID"=>"MYUSERNAME", "PWD"=>"MYPASSWORD");

    $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));
    }

Error

Connection could not be established.
Array ( [0] => Array ( [0] => 28000 [SQLSTATE] => 28000 [1] => 18456 [code] => 18456 [2] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'MYUSERNAME'. [message] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'MYUSERNAME'. ) [1] => Array ( [0] => 28000 [SQLSTATE] => 28000 [1] => 18456 [code] => 18456 [2] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'MYUSERNAME'. [message] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'MYUSERNAME'. ) )

Solution

  • I think the problem is in your SQL Server configuration. You should have a user with SQL Server Authentication instead of Windows Authentication. Here is how https://support.gearhost.com/KB/a453/adding-users-to-mssql-using-sql-server-management-studio.aspx

    And you may also want to check if your SQL Server TCP/IP configuration is accessible remotely : http://blogs.msdn.com/b/walzenbach/archive/2010/04/14/how-to-enable-remote-connections-in-sql-server-2008.aspx