简体   繁体   中英

Connecting to MSSQL Server from PHP

I've followed the guides at https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15 and https://docs.microsoft.com/en-us/sql/connect/php/installation-tutorial-linux-mac?view=sql-server-ver15 and PHP is finding the drivers / server but now I'm getting an authentication error.

Verified the server is configured for "SQL Server and Windows Authentication mode" and allows remote connections to the server.

In order to get this error, I believe that means the code is at least connecting and attempting to authenticate with the server (changing the server to some nonsense server name/location produces a timeout error) - fairly certain that eliminates any problems that would come before the authentication step.

Still, I'm getting an error as follows...

PDOException: SQLSTATE[28000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'username'. in /var/www/html/connect.php:10 Stack trace: #0 /var/www/html/connect.php(10): PDO->__construct('sqlsrv:Server=S...', 'username', 'password') #1 {main}root@containerIdGoesHere:/var/www/html

<?php

$user = 'username';
$pass = 'password';

try {
     $pdo = new PDO("sqlsrv:Server=SomeServer,1433;Database=SomeDb", $user, $pass);
     $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e) {
    echo 'See error log';
    $elog = fopen('errorlog.txt', 'w') or die("Couldn't open file");
    fwrite($elog, $e);
    fclose($elog);
}

Note: I've removed any sensitive info from my code... so the username and pw I'm using are not 'username' and 'password' & not related to the issue.

I've got this working on my production environment:

    $db = "DatabaseName";
    $password = "Password";
    $server = "TheSQLServer";
    $user = "username";
    $link = new PDO(
        "sqlsrv:Server=" . $server . 
        ";Database=" . $db, 
        $user, 
        $password
    );  

    return $link;

I also had to manually get into the DB and allow the previously created user to have the proper rights into it (DB->Security->Users), you can check that out aswell. Let me know how it goes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM