2013-10-14 63 views
2

我開始學習使用MS SQL Server的PDO。 與此代碼連接:編碼PHP PDO MS SQL服務器

$userDB = 'userBD'; 
$passwordDB = 'passwordDB'; 

try { 
    $DBH = new PDO('mssql:dbname=spr_bank;host=hostname', $userDB, $passwordDB); 
    $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

} 
catch(PDOException $e) { 
    echo "<h1 style='font-weight:bold; color:red;'>Error. Can not connect to Database</h1>"; 
    file_put_contents('PDOErrors.log', date("Y-m-d H:i:s")." - ".$e->getMessage()."\n", FILE_APPEND); 
    exit(); 
} 

,現在,我從表中選擇數據:

 //simple query and binding with results 
     $query = $DBH->prepare("SELECT name FROM spr_sotrudnik WHERE login = :login AND password = :password"); 

     $login = (isset($_POST['login']) === true) ? $_POST['login'] : '' ; // ? : shorthand for if else 
     $password = (isset($_POST['password']) === true) ? md5($_POST['password']) : '' ; // ? : shorthand for if else 

     // bind parameters - avoids SQL injection 
     $query->bindValue(':login', $login); 
     $query->bindValue(':password', $password); 

     //try... if not catch exception 
     try { 
      // run the query 
      $query->execute(); 

      while($rows = $query->fetch()){ 
      echo $rows["name"]; 
      } 
     } 
     catch(PDOException $e){ 
      echo $e->getMessage(), $e->getFile(), $e->getLine(); 
     } 

當我去到瀏覽器中,我得到這個錯誤:

SQLSTATE[HY000]: General error: 10007 Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier. [10007] (severity 5) [(null)]D:\www\sklad_new\inc\auth.php19

當我寫這個查詢 $query = $DBH->prepare(" SELECT CONVERT(VARCHAR(MAX),name) AS s FROM spr_sotrudnik WHERE login = :login AND password = :password");

我沒有e恐怖,但我看到「?????

我怎樣才能改變這種

+0

你正在使用什麼[驅動程序](http://es1.php.net/manual/en/pdo.drivers.php)? PDO_DBLIB,PDO_ODBC或PDO_SQLSRV? –

+0

我認爲這[驅動程序](http://es1.php.net/manual/en/ref.pdo-dblib.php),但我不確定。我如何檢查它? – Abdukhafiz

+0

對不起,我真的不需要問,因爲你已經顯示了DNS:'mssql:...'。您正在使用[PDO_DBLIB](http://es1.php.net/manual/en/ref.pdo-dblib.connection.php)。 –

回答

2

你省略charset參數在DSN string

$DBH = new PDO('mssql:dbname=spr_bank;host=hostname', $userDB, $passwordDB); 

...所以你可能會使用默認的編碼沿整個工具鏈。

在任何情況下,駕駛員PDO_DBLIB顯然tagged as experimental並且包括以下聲明:

On Windows, you should use SqlSrv, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx .

If it is not possible to use SqlSrv, you can use the PDO_ODBC driver to connect to Microsoft SQL Server and Sybase databases, as the native Windows DB-LIB is ancient, thread un-safe and no longer supported by Microsoft.

以我的經驗,這意味着你可以獲得各種不可預測的副作用。

+0

對於使用php和MS SQL Server,您有什麼建議? – Abdukhafiz

+1

@ Mr.AbduJan - PHP手冊的建議。我已經編輯了答案,以包括完整的引用。但我建議你找出你的應用和你的數據庫使用了什麼編碼;無論司機如何,你都需要這些信息。 –