要连接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();
}
请注意将上述代码中的"服务器地址"、“数据库名”、“用户名”、“密码”、“表名”、"列"等替换为实际的值。