2015-10-14 92 views
0

我是一名Web開發人員,對PHP + SQL數據庫連接和顯示結果有疑問。PHP + SQL數據庫Azure錯誤

<?php 

    ini_set('display_errors',1); 
    ini_set('display_startup_errors',1); 
    error_reporting(-1); 

    function OpenConnection() 
    { 
     try 
     { 
      $serverName = "tcp:***,1433"; 
      $connectionOptions = array("Database"=>"flan", 
       "Uid"=>"***", "PWD"=>"***"); 
      $conn = sqlsrv_connect($serverName, $connectionOptions); 
      if($conn == false) 
       die(FormatErrors(sqlsrv_errors())); 
     } 
     catch(Exception $e) 
     { 
      echo("Error!"); 
     } 
    } 

    function ReadData() 
    { 
     try 
     { 
      $conn = OpenConnection(); 
      $tsql = "SELECT * FROM tour_id"; 
      $getProducts = sqlsrv_query($conn, $tsql); 
      if ($getProducts == FALSE) 
       die(FormatErrors(sqlsrv_errors())); 
      $productCount = 0; 
      while($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC)) 
      { 
       echo($row['tour_title']); 
       echo("<br/>"); 
       $productCount++; 
      } 
      sqlsrv_free_stmt($getProducts); 
      sqlsrv_close($conn); 
     } 
     catch(Exception $e) 
     { 
      echo("Error!"); 
     } 
    } 

    echo ReadData(); 
?> 

結果:

Warning: sqlsrv_query() expects parameter 1 to be resource, null given in D:\home\site\wwwroot\test.php on line 29 Fatal error: Call to undefined function FormatErrors() in D:\home\site\wwwroot\test.php on line 31

enter image description here

回答

2

Openconnection()功能不返回任何東西,所以$conn永遠是null

在你的函數添加回線,像這樣返回的連接:

function OpenConnection() 
{ 
    try 
    { 
     $serverName = "***"; 
     $connectionOptions = array("Database"=>"***", "Uid"=>"***", "PWD"=>"***"); 
     $conn = sqlsrv_connect($serverName, $connectionOptions); 
     if($conn == false) 
      die(FormatErrors(sqlsrv_errors())); 

     return $conn; // <--- Here 
    } 
    catch(Exception $e) 
    { 
     echo("Error!"); 
    } 
} 
0

不必返回從OpenConnection函數的連接。

//... 
$conn = sqlsrv_connect($serverName, $connectionOptions); 
if($conn == false) 
    die(FormatErrors(sqlsrv_errors())); 
return $conn; 
//... 

此外:你不應該在網上發佈你的憑證。

+0

非常感謝你,我不會再犯這個錯誤。 –