要連接SQL Server并實現增刪改查操作,可以使用PHP提供的PDO(PHP Data Objects)和SQL Server驅動程序。以下是一個簡單的示例:
$dsn = 'sqlsrv:Server=服務器地址;Database=數據庫名';
$username = '用戶名';
$password = '密碼';
try {
$conn = new PDO($dsn, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo '連接失敗: ' . $e->getMessage();
}
try {
$sql = "INSERT INTO 表名 (列1, 列2, 列3) VALUES (:value1, :value2, :value3)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);
$stmt->bindParam(':value3', $value3);
$value1 = '值1';
$value2 = '值2';
$value3 = '值3';
$stmt->execute();
echo '插入成功';
} catch (PDOException $e) {
echo '插入失敗: ' . $e->getMessage();
}
try {
$sql = "SELECT * FROM 表名";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
echo $row['列1'] . ' ' . $row['列2'] . ' ' . $row['列3'] . '<br>';
}
} catch (PDOException $e) {
echo '查詢失敗: ' . $e->getMessage();
}
try {
$sql = "UPDATE 表名 SET 列1 = :value1 WHERE 列2 = :value2";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);
$value1 = '新值';
$value2 = '匹配條件';
$stmt->execute();
echo '更新成功';
} catch (PDOException $e) {
echo '更新失敗: ' . $e->getMessage();
}
try {
$sql = "DELETE FROM 表名 WHERE 列 = :value";
$stmt = $conn->prepare($sql);
$value = '匹配條件';
$stmt->bindParam(':value', $value);
$stmt->execute();
echo '刪除成功';
} catch (PDOException $e) {
echo '刪除失敗: ' . $e->getMessage();
}
請注意將上述代碼中的"服務器地址"、“數據庫名”、“用戶名”、“密碼”、“表名”、"列"等替換為實際的值。