在PHP中使用MySQL進行事務處理,您需要遵循以下步驟:
使用MySQLi擴展:
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
使用PDO擴展:
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 設置 PDO 錯誤模式為異常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "連接失敗: " . $e->getMessage();
}
beginTransaction()
方法。使用MySQLi擴展:
$conn->begin_transaction();
使用PDO擴展:
$conn->beginTransaction();
使用MySQLi擴展:
$sql1 = "INSERT INTO table1 (column1, column2) VALUES ('value1', 'value2')";
$sql2 = "UPDATE table2 SET column1 = 'value3' WHERE column2 = 'value4'";
if ($conn->query($sql1) === TRUE && $conn->query($sql2) === TRUE) {
$conn->commit();
} else {
$conn->rollback();
echo "Error: " . $sql1 . "<br>" . $conn->error;
}
使用PDO擴展:
$sql1 = "INSERT INTO table1 (column1, column2) VALUES (:value1, :value2)";
$sql2 = "UPDATE table2 SET column1 = :value3 WHERE column2 = :value4";
try {
$stmt1 = $conn->prepare($sql1);
$stmt1->bindParam(':value1', $value1);
$stmt1->bindParam(':value2', $value2);
$stmt1->execute();
$stmt2 = $conn->prepare($sql2);
$stmt2->bindParam(':value3', $value3);
$stmt2->bindParam(':value4', $value4);
$stmt2->execute();
$conn->commit();
} catch(PDOException $e) {
$conn->rollback();
echo "Error: " . $e->getMessage();
}
使用MySQLi擴展:
$conn->close();
使用PDO擴展:
$conn = null;
這就是在PHP中使用MySQL進行事務處理的基本方法。請根據您的具體需求進行調整。