Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I connect to a local SQL Server Express but not to a remote SQL Server from PHP?

This is the standard code when using windows authentication:

<?php
    try {
        $conn = new PDO("sqlsrv:Server=geoffrey-pc\SQLEXPRESS;Database=books", 
                         NULL, NULL);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo $e;
        die("Error connecting to SQL Server");
    }

    echo "Connected to SQL Server\n";
?>

The above works for connecting to the local server (SQL Server 2008 Express Edition), but not for connecting to a server on the network (SQL Server Standard Edition). The error message is:

exception 'PDOException' with message 'SQLSTATE[28000]: [Microsoft][SQL Server Native Client 10.0][SQL Server]Login failed for user 'myDomain\GEOFFREY-PC$'.' in C:\wamp\www\PhpProject1\index.php:10 Stack trace: #0 C:\wamp\www\PhpProject1\index.php(10): PDO->__construct('sqlsrv:Server=n...', NULL, NULL) #1 {main}

The connection string for the network server is the same as for the local server, except that the server name is similar to abc0120 and does not end with \SQLEXPRESS or anything else, and the database name is different. The database name I use with the network server does exist.

I am using Apache 2.2.11. The SQLServer 2005 MSDN page for How to: Connect Using Windows Authentication reads:

The credentials under which the Web server's process (or thread) is running must map to a valid SQL Server login in order to establish a connection.

Maybe that is the problem.

I can connect to the network server using SQL Server Management Studio also using windows authentication.

like image 377
Geoffrey Avatar asked Nov 05 '22 15:11

Geoffrey


1 Answers

From the PHP manual, you have this example :

<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

In your example, you omit the $user and $password arguments. I would try and specify a username and password instead of passing null; the user running your PHP script might not be the same as the logged user... omitting to provide a username and password, PHP tries to provide the user's credentials who's running the script (with perhaps even no password at all).

like image 152
Yanick Rochon Avatar answered Nov 10 '22 18:11

Yanick Rochon