D555
D555

Reputation: 1832

Codeigniter transaction not working

I have a function which inserts row into a table, something like below

function fn_insert_user() {
    $this->db->trans_begin();
    $this->db->query('INSERT INTO user VALUES(9,"john", "9865321245")');
    $this->db->query('INSERT INTO user VALUES(8,"martin", "8865321245")');
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE)
    {
        $this->db->trans_rollback();
        echo 'something bad happened';
    }
    else
    {
        $this->db->trans_commit();
        echo 'everything is fine';
    }

}

Now primary key 8 already exists and hence as expected it should not allow to insert second query (which is fine).

It successfully rolls back first query but the problem is that instead of printing 'something bad happened' it prints

A Database Error Occurred
Error Number: 1062
Duplicate entry '8' for key 'PRIMARY'
INSERT INTO user VALUES(8,"martin", "8865321245")
Filename: C:\wamp\www\landmark\system\database\DB_driver.php
Line Number: 330

Upvotes: 0

Views: 3177

Answers (2)

user3442019
user3442019

Reputation: 1

This is not a transation problem...

Try it:

function fn_insert_user() {

    $this->db->trans_begin();
    $this->db->query('INSERT INTO user VALUES("john", "9865321245")');
    $this->db->query('INSERT INTO user VALUES("martin", "8865321245")');
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE)
    {
        $this->db->trans_rollback();
        echo 'something bad happened';
    }
    else
    {
        $this->db->trans_commit();
        echo 'everything is fine';
    }

}

Upvotes: 0

AdrienXL
AdrienXL

Reputation: 3008

If you do

$this->db->trans_complete();

And

$this->db->trans_commit();

Then it will commit the transaction twice.

You have 2 solutions :

    $this->db->trans_start();
    $this->db->query('QUERY');
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE)
    {
        echo "fail";
    } 

OR

$this->db->trans_begin();
$this->db->query('QUERY...');


if ($this->db->trans_status() === FALSE)
{
    $this->db->trans_rollback();
}
else
{
    $this->db->trans_commit();
}

See documentation for further details ; http://www.codeigniter.com/user_guide/database/transactions.html

Upvotes: 3

Related Questions