我是使用交易的新手。我之前的问题是关于多个插入,如果遇到错误应该中止,而忽略的事务解决它。我的新问题是我必须知道插入是否成功,如果不成功则应显示错误。
PROFILE table
+--+----+---------+
|ID|NAME|BAL_LIMIT|
+--+----+---------+
NUMBER table
+--+----------+------+
|ID|PROFILE_ID|NUMBER|
+--+----------+------+
- 交易声明 -
START TRANSACTION;
INSERT IGNORE INTO `PROFILE` (`ID`, `NAME`, `BAL_LIMIT`) VALUES(NULL, "Name", 0);
INSERT INTO `NUMBER` (`PROFILE_ID`, `NUMBER`) VALUES(LAST_INSERT_ID() , "09123456789");
COMMIT;
- 要处理的错误 -
#1062 - Duplicate entry '09123456789' for key 'NUMBER_UNIQUE'
- PHP文件包含 -
$vname = $_POST["iname"];
$vbalancelimit = $_POST["ibalancelimit"];
$vnumber = $_POST["inumber"];
$transaction = "START TRANSACTION;
INSERT IGNORE INTO `PROFILE` (`ID`, `NAME`, `BAL_LIMIT`) VALUES(NULL, \"$vname\", $vbalancelimit);
INSERT INTO `NUMBER` (`ID`, `PROFILE_ID`, `NUMBER`) VALUES(NULL, LAST_INSERT_ID(), \"$vnumber\");
COMMIT;";
$execute_transaction = mysqli_multi_query($con,$transaction) or die("Error: ".mysqli_error($connection));
if (!$execute_transaction) {
echo mysqli_error($connection);
} else { echo "success"; }
PHP文件总是显示成功,但有#1062错误并且插入被忽略。
答案 0 :(得分:0)
多查询交易声明问题已解决。
最终的PHP文件:
<?php
$vname = $_POST["iname"];
$vbalancelimit = $_POST["ibalancelimit"];
$vnumber = $_POST["inumber"];
$transaction = "
START TRANSACTION;
INSERT IGNORE INTO `PROFILE` (`ID`, `NAME`, `BAL_LIMIT`) VALUES(NULL, \"$vname\", $vbalancelimit);
INSERT INTO `NUMBER` (`ID`, `PROFILE_ID`, `NUMBER`) VALUES(NULL, LAST_INSERT_ID(), \"$vnumber\");
COMMIT;";
$aff_rows = 0;
if(mysqli_multi_query($con,$transaction)){
do{$aff_rows+=mysqli_affected_rows($con);
}while(mysqli_more_results($con) && mysqli_next_result($con));
}if($aff_rows==2){//SUCCESS
echo "<script>swal(\"$vname\", \"New number: $vnumber\", \"success\");</script>";
}if($aff_rows==1){//WRONG NUMBER CORRECT NAME
echo "<script>swal(\"Duplicate entry of $vnumber\", \"Failed to add for: $vname\", \"error\");</script>";
}if($aff_rows==0){//WRONG NAME CORRECT/WRONG NUMBER
echo "<script>swal(\"Duplicate entry of $vname\", \"Failed to add number: $vnumber\", \"error\");</script>";}
?>