I have a page where I am dynamically generating a lot of rows of students (max around 50) from a DB. The page is to allow a teacher to enter grades for each student at once. The rows are generated using AJAX/jQuery and looks something like this:
$("#tbodystudents").append('<tr><td class="studentid" style="display:none">'+value[0]+'</td><td class="subjectid" style="display:none">'+value[1]+'</td><td><input class="inpmark" type="number"></td>/tr>');
I then send it to my PHP file like this:
$("#btnaddmarks").click(function(){
var marks= $("input.inpmark").map(function(){
return $(this).val();
}).get().map();
var studentids= $(".studentid").map(function() {
return $(this).text();
}).get().map();
var subjectids= $(".subjectid").map(function() {
return $(this).text();
}).get().join();
$.ajax({
type: "POST",
url: "modules/addmarks.php",
dataType: 'json',
data: {s:studentids,m:marks,subj:subjectids},
cache: false,
}) // etc..
});
and my PHP, addmarks.php:
<?php
$inputvalues = $_POST;
$errors = false;
$returnResult;
$result = false;
include_once '../../../includes/database.php';
$studentids = $inputvalues['s'];
$marks = $inputvalues['m'];
$subjectids= $inputvalues['subj'];
$studentid = explode(",",$studentids);
$mark= explode(",",$marks);
$subjectid= explode(",",$subjectids);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if( !$errors ) {
$sql = "INSERT INTO `marks` (`studentid`, `subjectid`,`mark`) VALUES (?,?,?)";
$stmts = $mysqli->prepare($sql);
$stmts->bind_param('iii',$studentid,$subjectid,$mark);
$result = $stmts->execute();
$returnResult = "Success";
}
mysqli_close($mysqli);
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
So my questions are,
How can I loop over the values and insert corresponding values into my DB?
Is this the best way to go about this problem? If not, what is?
How can I ensure that the correct values are entered, meaning that the first value in the studentids array and the first value in the marks array are connected and entered into the DB accordingly.
Is it safe to send this data using AJAX to the backend? I plan to use HTTPS later.