$answersql = "INSERT INTO Penalty_Marks (PenaltyAnswer, PenaltyMarks, QuestionId)
VALUES (?, ?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
}
$c = count($_POST['incorrect']);
for($i = 0; $i < $c; $i++)
{
$incorrect = $_POST['incorrect'][$i];
$answerMarks = $_POST['answerMarks'][$i];
$numQuestion = $_POST['numQuestion'][$i];
$insertanswer->bind_param('sii', $incorrect, $answerMarks, $numQuestion);
$insertanswer->execute();
}
上述插入操作並未將所有不正確的答案都插入到表中,而是每個問題只插入一個不正確的答案。我究竟做錯了什麼?通過循環時數據未被正確調整
下面是當期的db表的樣子:
PenaltyAnswerId PenaltyAnswer PenaltyMarks QuestionId
1 A 4 12
2 D 1 13
下面是它應該的一直喜歡:
PenaltyAnswerId PenaltyAnswer PenaltyMarks QuestionId
1 A 4 12
2 B 3 12
3 D 0 12
4 D 1 13
5 E 1 13
下面表格:
<form id="PenaltyMarks" action="insertpenaltymarks.php" method="post">
<table id='penaltytbl'>
<?php
foreach($ques_ans as $questionId => $inc_ans)
{
$q_row_span = count($inc_ans);
$row_count = 0;
$inc_ans = array_values($inc_ans);
?>
<tr class="questiontd">
<td>
<input type="hidden" name="numQuestion[]" value="<?php echo$questionId?>" />
</td>
<td>
<input type="hidden" class="hiddenincorrect" name="incorrect[]" value="<?php echo$inc_ans[$row_count];?>">
</td>
<td>
<input name="answerMarks[]" type="text" data-type="qmark" value='0' />
</td>
</tr>
<?php
//remaining incorrect answers in separate row (if any) follows here
if($row_count < $q_row_span - 1)
{
for($i=($row_count + 1); $i<$q_row_span; $i++) { ?>
<tr>
<td>
<input type="hidden" class="hiddenincorrect" name="incorrect[]" value="<?php echo$inc_ans[$i];?>">
</td>
<td class="answermarkstd">
<input name="answerMarks[]" type="text" data-type="qmark" value='0' />
</td>
</tr>
<?php
}
}
}
?>
</table>
<input id="submitBtn" name="submitPenalty" type="submit" value="Submit Marks" />
</form>
下面是jQuery的處理提交:
myClickHandler = function(e) {
if (confirm("Are you sure you want to Proceed?" + "\n")) {
$.ajax({
url: "insertpenaltymarks.php",
data: $("#PenaltyMarks").serialize(),
async: false,
type: "POST"
});
return true;
} else {
return false;
}
};
$('#PenaltyMarks').submit(myClickHandler);
});
UPDATE:
Question Table:
QuestionId (PK auto) (int 10)
QuestionNo (int 4)
QuestionContent (varchar 5000)
Penalty_Marks Table;
PenaltyAnswerId (PK auto) (int 10)
PenaltyAnswer (Varchar 5)
PenaltyMarks (int 3)
QuestionId (FK) (int 10) Reference to QuestionId in Question Table
你能粘貼表的結構(主鍵,索引...) – m4t1t0
@ m4t1t0包括結構更新 – user1964964
如何給你sumbit的形式?我可以看到不提交按鈕。你提交的JavaScript? – hek2mgl