I am using PDO in PHP and a MySQL database. What I want to do is whenever an insert fails (such as duplicate entry in unique field), have it throw an exception error message and roll back the changes (not to auto increment in my case).
This is what I’ve done, but it doesn’t work:
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();
}
Where did I go wrong?
Here is the edit version of it (for whole part of inserting) , is that correct? thanks
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;
}
Is that all the code? You have to start a transaction in order to commit/rollback: