PHP SQLSRV例子 - 實(shí)現(xiàn)數(shù)據(jù)庫(kù)操作
在PHP中使用SQL Server數(shù)據(jù)庫(kù),可以通過(guò)SQLSRV擴(kuò)展實(shí)現(xiàn)。以下是一些簡(jiǎn)單的PHP SQLSRV例子,用于展示如何在PHP中連接、查詢、插入、更新和刪除SQL Server數(shù)據(jù)庫(kù)。
1. 連接SQL Server數(shù)據(jù)庫(kù)
<?php $serverName = "serverName"; $connectionOptions = array( "Database" => "dbName", "Uid" => "userName", "PWD" => "password" ); $conn = sqlsrv_connect($serverName, $connectionOptions); if($conn === false){ die(print_r(sqlsrv_errors(), true)); } echo "Connected successfully"; ?>
2. 查詢數(shù)據(jù)
<?php $tsql = "SELECT TOP 10 * FROM Persons"; $stmt = sqlsrv_query($conn, $tsql); if($stmt === false){ die(print_r(sqlsrv_errors(), true)); } echo "<table>"; while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){ echo "<tr><td>".$row["FirstName"]."</td>"; echo "<td>".$row["LastName"]."</td></tr>"; } echo "</table>"; sqlsrv_free_stmt($stmt); sqlsrv_close($conn); ?>
3. 插入數(shù)據(jù)
<?php $tsql = "INSERT INTO Persons (FirstName, LastName, Age) VALUES (?, ?, ?)"; $params = array("John", "Doe", 25); $stmt = sqlsrv_query($conn, $tsql, $params); if($stmt === false){ die(print_r(sqlsrv_errors(), true)); } echo sqlsrv_rows_affected($stmt)." rows inserted"; sqlsrv_free_stmt($stmt); sqlsrv_close($conn); ?>
4. 更新數(shù)據(jù)
<?php $tsql = "UPDATE Persons SET Age = ? WHERE FirstName = ? AND LastName = ?"; $params = array(30, "John", "Doe"); $stmt = sqlsrv_query($conn, $tsql, $params); if($stmt === false){ die(print_r(sqlsrv_errors(), true)); } echo sqlsrv_rows_affected($stmt)." rows updated"; sqlsrv_free_stmt($stmt); sqlsrv_close($conn); ?>
5. 刪除數(shù)據(jù)
<?php $tsql = "DELETE FROM Persons WHERE FirstName = ? AND LastName = ?"; $params = array("John", "Doe"); $stmt = sqlsrv_query($conn, $tsql, $params); if($stmt === false){ die(print_r(sqlsrv_errors(), true)); } echo sqlsrv_rows_affected($stmt)." rows deleted"; sqlsrv_free_stmt($stmt); sqlsrv_close($conn); ?>
總結(jié)
這些簡(jiǎn)單的PHP SQLSRV例子展示了如何在PHP中連接、查詢、插入、更新和刪除SQL Server數(shù)據(jù)庫(kù)。通過(guò)SQLSRV擴(kuò)展,可以輕松地實(shí)現(xiàn)與SQL Server數(shù)據(jù)庫(kù)的交互。