Welcome Guest, Not a member yet? Register   Sign In
models and db transactions
#4

Your example makes little sent. By default all databases autocommitting transactions. So they are doing exactly what you showed: they start transation, execute your query, and upon success immidiately commit and close transaction. So yoiu do not need to explicitly utilize them every time.

When you do need transaction is to ensure that several queries (affecting one or more tables in DB) are either succesfully executed all together, or not executed at all, to prevent partial execution.


See this example: you are building a marketplace that processes payments and earns some commission from each payment. When user purchases goods, you should do a lot of stuff: reserve items in stock, get confirmation that user paid the bill from payment gateway, pay taxes, etc. Imagine that if user does not pay  

PHP Code:
$this->db->transBegin();

//Step 1: reserve stock
//Some business logic here that might throw exceptions
$this->db->query("UPDATE stock...");

//Step 2: settle money
//Here we might wait till payment processor confirms payment
$this->db->query("INSERT INTO payments...");
$this->db->query("INSERT INTO taxes...");
$this->db->query("INSERT INTO commissions...");

//Step 3: Create invoice
//Again some business logic that might go wrong
$this->db->query("INSERT INTO invoices...");

if (
$this->db->transStatus() AND OTHER RELEVANT CHECKS) { $this->db->transCommit(); } else { $this->db->transRollback(); } 
Reply


Messages In This Thread
models and db transactions - by kyle - 03-11-2020, 10:48 AM
RE: models and db transactions - by zahhar - 03-11-2020, 02:29 PM
RE: models and db transactions - by kyle - 03-11-2020, 03:13 PM
RE: models and db transactions - by zahhar - 03-12-2020, 01:00 AM



Theme © iAndrew 2016 - Forum software by © MyBB