PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 3, 2022

[FIXED] transaction doesn't work on truncate

 March 03, 2022     laravel, laravel-5.2, transactions     No comments   

Issue

I'm trying Laravel transaction for the first time... I do most of my queries with Eloquent and since there no transaction there I have to do a mixture of Eloquent and query builder.

Here is my code:

DB::beginTransaction();

try{
    Setting::truncate();
    Setting::insert($data);
    DB::commit();
    jok('all ok');

}
catch (\Exception $e)
{
    DB::rollback();
    jerror('some error accorded! ');
}

So I've tied to add some invalid data to Settings and i got the some error accorded error as expected but the query before INSERT Setting::truncate(); was executed anyway and I ended up with a empty table.

So either I'm doing something wrong or transaction doesn't work on truncate.


Solution

TRUNCATE TABLE in a database transaction will cause a implicit COMMIT action. DELETE does not have that same behavior, so you can safely run

DELETE FROM tblname

This will clear your table and still keep the desired rollback feature of a transaction.

See the MySQL documentation on TRUNCATE. The bullet points explain this functionality http://dev.mysql.com/doc/refman/5.7/en/truncate-table.html



Answered By - Rob Fonseca
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing