2016-01-05 47 views
-2

我是新的使用事務。我以前的問題是關於多個插入,如果遇到錯誤應該中止,而使用忽略的事務解決它。我的新問題是,我必須知道插入是否成功,如果不是,應顯示錯誤。xampp MySQL忽略 - 如何捕獲PHP文件中的錯誤

PROFILE table 
+--+----+---------+ 
|ID|NAME|BAL_LIMIT| 
+--+----+---------+ 

NUMBER table 
+--+----------+------+ 
|ID|PROFILE_ID|NUMBER| 
+--+----------+------+ 

--transaction STATEMENT--

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; 

--error是HANDLED--

#1062 - Duplicate entry '09123456789' for key 'NUMBER_UNIQUE' 

--PHP文件contains--

$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錯誤和插入被忽略。

+1

你是如何設置'$ transaction'變量? –

+0

顯示所有相關的代碼,或者你會得到的所有代碼都是猜測 – RiggsFolly

+0

你曾經將那個查詢發佈到數據庫執行的地方嗎?我不知道錯誤來自哪裏,但它不是從創建文本字符串! – RiggsFolly

回答

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>";} 
?>