My situation:
I have to do an e-learning system, where the lecturers(user) will upload an assignment. User will enter assignment details (name, description, etc) and also upload file(s). I have tried to do multiple file upload with transaction to insert the data into two tables, one containing the detail of the assignment and the other is for the file(s) uploaded in one assignment.
I have 2 related tables:
1) assignment - where all the assignment details will be stored
2) assignmentfile - where all the filepath will be stored
I have referred to several posts like this:
Inserting multiple tables with transaction in mysql
PHP & mySQL: Simple code to implement Transaction - Commit & Rollback
I tried to code like that, but somehow my data could not be inserted into the database.
Here is my connection code:
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "test";
// Create connection
$con = new mysqli($host, $dbusername, $dbpassword, $dbname);
// Check connection
if (mysqli_connect_error()){
die('Connect Error ('. mysqli_connect_errno() .') '
. mysqli_connect_error());
}
and here is my transaction code:
for ($i = 0; $i < count($_FILES['filename']['name']); $i++) {
$filename = $_FILES['filename']['name'][$i];
$target = "upload/";
$filetarget = $target.$filename;
$tempfilename = $_FILES["filename"]["tmp_name"][$i];
$result = move_uploaded_file($tempfilename,$filetarget);
if($result) {
// disable autocommit
mysqli_autocommit($con, FALSE);
$con->begin_transaction();
$con-> query("INSERT INTO assignment (assignid, topicid,classid,a_name,description,startdate,duedate,cutoffdate)VALUES ((SELECT topicid FROM topic WHERE topicid = '$topicid'),(SELECT classid FROM class WHERE classid = '$classid'),'$a_name','$description','$startdate','$duedate','$cutoffdate')");
// last inserted id for assignid
$assignid = mysqli_insert_id($con);
$con->query("INSERT INTO assignmentfile (fileid, assignid, filename, filetarget) VALUES ((SELECT assignid FROM assignment where assignid = '$assignid'), '$filename','$filetarget')");
$con->commit();
} // end of result
else {
$con->rollback();
}
} // end of for loop
}
What did I do wrong? There is no error displayed but the data is not inserted into the database. Is there a better way to do this?