所以我一直试图找到答案,但我不认为有一个是我想要做的。我将从我的代码示例开始
file.php
$q = "INSERT INTO ".PORTAL_DB.".resource_file (company__id, rf_category__id, title, file_name, description, path, upload_by, has_quiz)
SELECT ?, ?, ?, CONCAT(MAX(id)+1, '.', '$extension'), ?, ?, ?, ? FROM ".PORTAL_DB.".resource_file";
$stmt = $CONN->prepare($q);
$filename = 0;
$resource_file__id = 0;
if($stmt->execute(array($company__id, $rf_category__id, $title, $description, "assets/$uploadFolder/", USER, $has_quiz))){
$filename = $CONN->lastInsertId();
$resource_file__id = $filename;
}
if(!empty($quiz)){
$passing_score = $quiz->passing_score;
if(!is_numeric($passing_score) or ($passing_score < 0) or $passing_score > 100){
$CONN->rollback();
throw new Exception("Invalid passing score value for quiz, please fix");
}
$q = "INSERT INTO ".PORTAL_DB.".rf_quiz (resource_file__id, passing_score)
VALUES(?, ?)";
$stmt = $CONN->prepare($q);
$rf_quiz__id = 0;
$stmt->execute(array($resource_file__id, $passing_score));
print_r($CONN->lastInsertId);
exit;
$question_ids = array();
foreach($quiz as $qz){
$question = $qz->question;
//print_r($qz);
$q = "INSERT INTO ".PORTAL_DB.".rf_quiz_question (rf_quiz__id, question)
VALUES(?, ?)";
$stmt = $CONN->prepare($q);
if($stmt->execute(array($rf_quiz__id, $question))){
array_push($question_ids, $CONN->lastInsertId);
}
}
//print_r($question_ids);
exit; // using this for testing only
}
解释
在$CONN->beginTransaction()
之后调用上面的代码,以便我可以更轻松地管理错误。根据我的理解,您可以多次调用stamtement $CONN->lastInsertId()
而不会出现问题,但是当我们转到$resource_fild__id
变量时,我可以获得存储在变量$rf_quiz__id
下的第一个ID ,即使通话成功,我也什么也得不到,这会导致错误。我希望能够在一次交易中完成所有这些操作,以便于编码过程和组织。
我希望有人可以指出我正确的方向,或者至少能够告诉我我做错了什么,以便找到快速的解决方案!
提前感谢您的帮助。