PHP代碼若是想要用以上的方式兼容linux服務器和windows服務器,那麼大概的示例代碼是這樣的。php
<?php
header("Content-type: text/html; charset=utf-8"); if(PATH_SEPARATOR==':') echo '本機操做系統是:Linux<br>'; else echo '本機操做系統是:Windows<br>'; try { //服務器 $host = "127.0.0.1"; $port = '1433'; $dbname = "databasename"; $username = "sa"; $pw = "xxxwtxxx"; $dbh = null; if(PATH_SEPARATOR==':'){ $dbh = new PDO ("dblib:host=$host:$port;dbname=$dbname","$username","$pw"); }else{ $dbh = new PDO("sqlsrv:Server=$host,$port;Database=$dbname",$username,$pw); } } catch (PDOException $e) { echo "Failed to get DB handle: " . $e->getMessage() . "\n"; exit; } $stmt = $dbh->prepare("SELECT top 1 * FROM tablename"); $stmt->execute(); while ($row = $stmt->fetch()) { var_dump($row); } unset($dbh); unset($stmt);