I want to perform an insert into the database so that the database table Individual Answer contains the following data:
Individual_Answer Table:
AnswerId AnswerMarks
295 2
296 1
297 1
298 3
299 3
Problem is that it is not inserting into database. Is it the php/mysqli code which is causing the problem or is it the ajax that is not accessing the php page which is doing the insert (insertmarks.php)?
Below in my code in php/mysqli:
<?php
// connect to the database
include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
var_dump($_POST);
$answersql = "INSERT INTO Individual_Answer (AnswerId, AnswerMarks)
VALUES (?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
//make sure both prepared statements succeeded before proceeding
if($insertanswer)
{
$c = count($_POST['answerId']);
for($i = 0; $i < $c; $i++ )
{
$insertanswer->bind_param('ii', $_POST['answersId'][$i], $_POST['answerMarks'][$i]);
}
//close your statements at the end
$insertanswer->close();
}
?>
Below is the var_dump($_POST) outputting:
array(7) {
["q1_ans_org"]=> string(1) "4"
["q1_ans"]=> string(1) "0"
["answerMarks"]=> array(5)
{
[0]=> string(1) "2"
[1]=> string(1) "1"
[2]=> string(1) "1"
[3]=> string(1) "3"
[4]=> string(1) "3" }
["q2_ans_org"]=> string(1) "6"
["q2_ans"]=> string(1) "0"
["num_groups"]=> string(1) "2"
["submitMarks"]=> string(12) "Submit Marks"
}
Below is the html and jquery/ajax code which is suppose to access insertmarks.php:
<form id="Marks" action="penalty.php" method="post">
...
<p>
<input type='hidden' id='num_groups' name='num_groups' value='<?php echo$questionId?>'>
<input id="submitBtn" name="submitMarks" type="submit" value="Submit Marks" />
</p>
</form>
...
<script type="text/javascript">
myClickHandler = function(e) {
var ng = $('#num_groups').val();
for (var group = 1; group <= ng; group++) {
if (!validation(group)) return false;
}
if (confirm("Make sure that your marks are correct, once you proceed after this stage you would not be able to go back and change any of your marks for this Assessment." + "\n" + "\n" + "Are you sure you want to Proceed?" + "\n")) {
$.ajax({
url: "insertmarks.php",
data: $("#Marks").serialize(),
async: false,
type: "POST"
});
return true;
} else {
return false;
}
};
$('#Marks').submit(myClickHandler);
});
</script>
You didn’t execute the query,