2014-06-21 34 views
0

我已經通過了this,據我所知它有效。 (phpinfo()顯示在附加擴展名列表中)SQLSERV和PHP不能正常工作...不能創建到數據庫的連接

我有從MSDN獲得的這段代碼。我對它做了一些修改,以便它可以與我的SQL Server和數據庫一起工作。數據庫在那裏,它正在運行。

這裏是我的代碼:

<?php 
    ini_set('display_startup_errors', 1); 
    ini_set('display_errors', 1); 
    error_reporting(-1); 
?> 

^^在<head>塊。 沒有錯誤報告。

<?php 
    $serverName = "(local)"; 
    $database = "{db}"; 

    // Get UID and PWD from application-specific files. 
    $uid = "{user}"; 
    $pwd = "{pass}"; 

    try { 
     $conn = new PDO("sqlsrv:server=$serverName;Database = $database", $uid, $pwd); 
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    } 

    catch(PDOException $e) { 
     die("Error connecting to SQL Server"); 
    } 

    echo "Connected to SQL Server\n"; 

    $query = 'select * from {table}'; 
    $stmt = $conn->query($query); 
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ 
     print_r($row); 
    } 

    // Free statement and connection resources. 
    $stmt = null; 
    $conn = null; 
?> 

這裏是在catch塊$evar_dump()

PDOException Object ([message:protected] => SQLSTATE[28000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'sa'. [string:Exception:private] => [code:protected] => 28000 [file:protected] => C:\inetpub\wwwroot\sandbox\sfactor\sandbox.php [line:protected] => 20 [trace:Exception:private] => Array ([0] => Array ([file] => C:\inetpub\wwwroot\sandbox\sfactor\sandbox.php [line] => 20 [function] => __construct [class] => PDO [type] => -> [args] => Array ([0] => sqlsrv:server=;Database=SFactor [1] => sa [2] => 7536SqL))) [previous:Exception:private] => [errorInfo] => Array ([0] => 28000 [1] => 18456 [2] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'sa'.)) Connected to SQL Server Notice: Undefined variable: conn in C:\inetpub\wwwroot\sandbox\sfactor\sandbox.php on line 31 Fatal error: Call to a member function query() on a non-object in C:\inetpub\wwwroot\sandbox\sfactor\sandbox.php on line 31 
+0

你正在嘗試使用'sqlsrv'還是'PDO'?你的標題建議前者,但示例建議後者 – Machavity

+0

嘗試轉儲實際的錯誤代碼和消息,而不是隻是'死(「錯誤連接到SQL Server」);' – RiggsFolly

+0

你嘗試過'$ dbh = new PDO('mysql: host = localhost; dbname = test',$ user,$ pass);'這個,取自http://www.php.net//manual/en/pdo.connections.php的例子取代你的憑證。 –

回答

0

所以它的固定.. 問題是$serverName = "(local)";正在給他的問題。

我所要做的就是,$serverName = "localhost\MSSQL2014";

感謝大家。

+0

感謝您的更新。很高興它正在工作。 –