【環境】
作業系統:Windows 7 Ultimate 64位
Web伺服器:IIS7
PHP版本:5.3.28
具體開發環境的搭建請參閱:https://zh.arslanbar.net/post.php?t=23515
【程序代碼】
<?php
define('DB_PWD', '*******************');
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>SQL Server Connection Test</title>
</head>
<body>
<?php
if (function_exists('sqlsrv_connect')) {
$serverName = '(local)';
$connectionInfo = array('Database' => 'test', 'UID' => 'sa', 'PWD' => DB_PWD);
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn) {
echo 'Connection established.<br>';
$sql = 'SELECT * FROM Users';
$stmt = sqlsrv_query($conn, $sql, array(), array('Scrollable' => SQLSRV_CURSOR_KEYSET)); // the 4th param ensures that sqlsrv_num_rows is able to work
if ($stmt === false) {
echo 'Query failed.<br>';
} else {
if (sqlsrv_has_rows($stmt)) {
$count = sqlsrv_num_rows($stmt);
if ($count === false) {
echo '<b style="color:red">Error in retrieveing row count.</b><br>';
} elseif ($count == 1) {
echo 'There\'s only one row.<br>';
} else {
echo "There are $count rows.<br>";
}
while ($row = sqlsrv_fetch_array($stmt)) {
echo '<p><b>User ID: </b>' . $row['UserID'] . '<br>';
echo '<b>User Name: </b>' . $row['UserName'] . '<br>';
$time = $row['TimeRegistered']; // instance of DateTime
$timeStr = $time->Format('Y-n-j H:i:s');
echo "<b>Time Registered: </b>$timeStr<br></p>";
}
} else {
echo 'There\'s no row.<br>';
}
}
sqlsrv_close($conn);
} else {
echo 'Connection couldn\'t be established.<br>';
print_r(sqlsrv_errors());
}
} else {
echo 'Library sqlsrv isn\'t successfully installed.';
}
?>
</body>
</html>
【運行結果】