我正在使用PHP中的PDO和MySQL数据库。我想要做的是,每当插入失败时(例如在唯一字段中重复输入),都会抛出异常错误消息并回滚更改(在我的情况下不自动增加)。
这是我所做的,但它不起作用:
这是我所做的,但它不起作用:
try {
$email = $_POST['Email'];
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$query="INSERT INTO subscriber (Email,FirstName,LastName,CreateDate) VALUES (?,?,?,CURDATE())";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $email , PDO::PARAM_STR);
$stmt->bindParam(2, $FirstName, PDO::PARAM_STR);
$stmt->bindParam(3, $LastName, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e) {
die ($e->getMessage().'<a href="addSub.php"> Back</a>');
$conn->rollBack();
}
我哪里做错了?
这是编辑版本(插入整个部分),是否正确?谢谢。
if($_SERVER['REQUEST_METHOD'] == "POST"){
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beingTransaction();
try {
$email = $_POST['Email'];
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$query="INSERT INTO subscriber (Email,FirstName,LastName,CreateDate) VALUES (?,?,?,CURDATE())";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $email , PDO::PARAM_STR);
$stmt->bindParam(2, $FirstName, PDO::PARAM_STR);
$stmt->bindParam(3, $LastName, PDO::PARAM_STR);
$conn->commit();
}
catch(PDOException $e)
{
die ($e->getMessage().'<a href="addSub.php"> Back</a>');
$conn->rollBack();
}
try {
$userID = $_SESSION['username'];
$query="INSERT INTO list_sub (SubID,ListID) VALUES ('',$_SESSION[ListID])";
$stmt = $conn->prepare($query);
$conn->commit();
}
catch(PDOException $e)
{
$conn->rollBack();
die ($e->getMessage().'<a href="addSub.php"> Back</a>');
}
$conn = null;
}
die()
相当自描述 :) - Tim Post