php + sqlserver如何使用事务

举个例子:

 "myDatabase", "UID" => "admin", "PWD" => "123"); // 数据库名称、服务器用户名、服务器密码
$conn = sqlsrv_connect($serverName, $connInfo); // 连接数据库

if ($conn === false) {
    die(print_r(sqlsrv_errors(), true));
}

// 启动事务
if (sqlsrv_begin_transaction($conn) === false) {
    die(print_r(sqlsrv_errors(), true));
}

$UserName = "admin";
$PassWord = "1";
$SEX = "";


$sql1 = "INSERT INTO userInfo (UserName, PassWord) VALUES (?,?)";
$sql2 = "INSERT INTO userInfoDetail (USERNAME, PASSWORD, SEX) VALUES (?,?,?)";

$param1 = array($UserName, $PassWord);
$param2 = array($UserName, $PassWord, $SEX);

$stmt1 = sqlsrv_query($conn, $sql1, $param1);
$stmt2 = sqlsrv_query($conn, $sql2, $param2);

if ($stmt1 && $stmt2) {
    sqlsrv_commit($conn); // 事务提交
    echo "提交成功!";
} else {
    sqlsrv_rollback($conn); // 事务回滚
    echo "提交失败!事务回滚";
}

 

你可能感兴趣的:(php,sql,server,php,sqlserver,事务)