I need to insert two data items such that the data is inserted if and only if both data items are inserted. This is my current prepared query (based on https://codeigniter.com/user_guide/database/queries.html#prepared-queries)
$pQuery = $db->prepare(static function ($db) {
$sql = 'INSERT INTO transaction (uuid, img_link, datetime) VALUES (?, ?, ?)';
return (new Query($db))->setQuery($sql);
});
$pQuery->execute($uuid_one, $img_link_one, $datetime_one);
$pQuery = $db->prepare(static function ($db) {
$sql = 'INSERT INTO transaction (uuid, img_link, datetime) VALUES (?, ?, ?)';
return (new Query($db))->setQuery($sql);
});
$pQuery->execute($uuid_two, $img_link_two, $datetime_two);
The above does not use transaction, which means that there is a possibility where first data is inserted but the second is not (lost connection, database crash, etc.).
I tried to combine both query at once
$pQuery = $db->prepare(static function ($db) {
$sql = 'INSERT INTO transaction (uuid, img_link, datetime) VALUES (?, ?, ?); '.
'INSERT INTO transaction (uuid, img_link, datetime) VALUES (?, ?, ?); ';
return (new Query($db))->setQuery($sql);
});
$pQuery->execute($uuid_one, $img_link_one, $datetime_one, $uuid_two, $img_link_two, $datetime_two);
but it throws
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO transaction (uuid, img_link, datetime) VALUES (?, ?, ?)' at line 1.
This indicates that I can't use two queries at once. I thought that the solution is to use transaction, but I haven't found how to use transaction on prepared query on CodeIgniter 4. How can I use transactions?
The question Codeigniter how to use transactions does not answer my question because the transaction method described in the answer in the link only works on normal queries and not prepared queries.
To demonstrate what I mean, I tried running the following script
$db->transBegin();
$pQuery = $db->prepare(static function ($db) {
$sql = 'INSERT INTO transaction (uuid, img_link, datetime) VALUES (?, ?, ?)';
return (new Query($db))->setQuery($sql);
});
$pQuery->execute($uuid_one, $img_link_one, $datetime_one);
$pQuery = $db->prepare(static function ($db) {
$sql = 'INSERT INTO transaction (uuid, img_link, datetime) VALUES (?, ?, ?)';
return (new Query($db))->setQuery($sql);
});
$pQuery->execute($uuid_two, $img_link_two, $datetime_two);
db->transRollback();
transRollback() does not rollback the transaction, but the data is still inserted, which indicates that the transaction does not work for prepared query using the method above.
Notice that I didn't even run $db->transCommit() and the data is still inserted, which means the prepared query above is not affected by transaction at all.
And also the question in the link above is for CodeIgniter 3, I'm using CodeIgniter 4.
source https://stackoverflow.com/questions/77153529/how-to-use-transaction-on-prepared-query
No comments:
Post a Comment