I am trying to send a variable as string in SQL statement to my DB function, which should then use that string as variable and do the processing.
Its multiple insert script (as array) needing the last insert ID, here's a shorten code:
$insertID = "$"."insertID";
$sql = array("first INSERT Script", "INSERT into blah(`ID`, `Name`)
VALUE ('$insertID', '$name')", "Third script");
$result = dbInsert($sql);
if ($result){
// do something
}
Here's the insert function, I am experimenting if this way would work:
function dbInsert($sql){
$con = dbConnect();
try {
// begin a transaction
mysqli_begin_transaction($con);
foreach ($sql as $value) {
if ($con-> query($value)) {
$insertID = $con-> insert_id;
} else {
trigger_error(mysqli_error($con));
}
}
// if no error, commit.
mysqli_commit($con);
} catch (Exception $e) {
// if any error, catch the exception and rollback
mysqli_rollback($con);
}
/* close connection and return the result */
$con->close();
return $insertID;
}
Please note the first script doesn't require any last insert Id, but subsequent ones do. I know I can do individual inserts and skip this whole way, but it would be good if I just send one array of SQLs and function does the insert and sends back the last insert ID (to verify).
When I echo (& die) the SQL statement in Function dbInsert has "$result" (value of $insertID), but its reading it as string and not as the variable, which holds the last insert ID. I have tried few combination but to no avail.
Current:
INSERT INTO `tblstudent` (`userid`, `scholarnumber`, `firstname`, `middlename`, `lastname`, `datecreated`)
VALUES ($result, '35566', 'Joe', '', 'Blog', CURRENT_TIMESTAMP);
Should be:
INSERT INTO `tblstudent` (`userid`, `scholarnumber`, `firstname`, `middlename`, `lastname`, `datecreated`)
VALUES ('418', '35566', 'Joe', '', 'Blog', CURRENT_TIMESTAMP);
I hope I am making sense and someone would be able to point me in the right direction. Much appreciate your time and help, thank you!
It turns out, I was going about it the wrong way. All I needed to do was pass on "LAST_INSERT_ID()" instead of passing variable etc. Thank you for all the help! Someone might benefit from this, hence updating the post.