I'm coding using PHP PDO and MySQL.
In that context, can I write a single transaction that would run a first query (or series of queries), and then use the result of this query as an input into another query?
For example, I would like to (1) create a new record in table A and get the autoincremented ID in return, (2) create a new record in table B and get the autoincremented ID in return, (3) enter the IDs generated above from table A and B in two fields of a table C which represents the relation between A and B.
Can I do the above in a single transaction? Also, can I add some programming between each queries?
Short answer: Yes .
Long answer:
Absolutely, that's what transactions are designed for.
As far as your SQL vendor supports transaction (mysql does on InnoDB tables) you can use them to execute a serie of query.
Also, can I add some programming between each queries?
Yes, you can, however, make sure that if you're updating some third party, to rollback the change yourself.
Example:
try {
$db->beginTransaction();
$db->exec('INSERT INTO tableA (id, column) VALUES (NULL, NOW())');
$db->exec('SELECT id FROM tableB ORDER BY id DESC LIMIT 1');
// ...
$httpClient->post(sprintf('/notify/foo/%d?value=ok', $id));
$db->commit();
} catch (\PDOException $e) {
$db->rollback();
$httpClient->post(sprintf('/notify/foo/%d?value=cancel', $id));
}
Note that you can aslo nest transaction and use SAVEPOINT
on InnoDB tables.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.