Codeigniter Transactions

Codeigniter Transactions

Using transactions means support databases to insert data safely. So in Codeigniter we write every database related functions in the Model not in Controller.. And in your second code(which is not working)you have pointed model on there.(utils). So simple I'm sure this will not work. Because its not a insert data with model and Controller parallel. Transaction should be coded in the Model(I will write in Model in my answer).


Load this stuffs as well

  1. Database Library
  2. Model Class
  3. URL helper
  4. Session

Assumptions

In your code you have used $data and $test as array. So i assume there is two array for inserting and updating data.


Your data sets

$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
);

$id = 007;
$test = array(
'title' => $title,
'name' => $name,
'date' => $date
);

Your Code

$this->db->trans_start(); # Starting Transaction
$this->db->trans_strict(FALSE); # See Note 01. If you wish can remove as well

$this->db->insert('table_name', $data); # Inserting data

# Updating data
$this->db->where('id', $id);
$this->db->update('table_name', $test);

$this->db->trans_complete(); # Completing transaction

/*Optional*/

if ($this->db->trans_status() === FALSE) {
# Something went wrong.
$this->db->trans_rollback();
return FALSE;
}
else {
# Everything is Perfect.
# Committing data to the database.
$this->db->trans_commit();
return TRUE;
}

Notes

  1. By default Codeigniter runs all transactions in Strict Mode. When
    strict mode is enabled, if you are running multiple groups of transactions, if one group fails all groups will be rolled back. If
    strict mode is disabled
    , each group is treated
    independently
    , meaning a failure of one group will not affect
    any others
    .

CodeIgniter Transactions - trans_status and trans_complete return true but nothing being committed

I found my problem. I want to say Thank-you to everyone that tried to help however, this one was my fault.

Earlier in the Controller method that calls this function I called another function that starts a transaction. That transaction was never closed and therefore continued on into this new transaction.

Because the transaction just wasn’t committed and there were no errors, I was not able to find any errors or any history of a rollback. However as soon as I closed the previous transaction everything worked.

There was no evidence of any problems in the mySQL query log, mySQL error log, or the CodeIgniter error logs. I was only able to find this problem by slowly reading through the entire mySQL query log.

For anyone who comes across this problem: Check your other transactions and make sure that they are all closed.

Codeigniter how to use transactions

The reason for transactions is to perform multiple db query operations and if any operations fail undo any that have already taken place.

You are only performing one operation within your transaction block so transactions are pointless. Other than that, you've got the idea.

In your case where you are only using db->insert() you can easily check the results and respond accordingly. db->insert() returns either true or false. If the return is false, get the error and set it into flashdata. Otherwise, go on with your work.

As @Topjka say, transactions should be in the model code.

Here's a sample model

class Some_model extends CI_Model
{
public function save_stuff($data)
{
//let's assume $data has values for two different tables
$newInfo = $data['newStuff'];
$updateInfo = $data['oldStuff'];
$this->db->trans_start();
$this->db->insert('other_table', $newInfo);
$this->db->update('one_table', $updateInfo);
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$this->set_flash_error();
return FALSE;
}
return TRUE; //everything worked
}

public function set_flash_error()
{
$error = $this->db->error();
$this->session->set_flashdata('Error', $error["message"]);
}

}

Transactions are justified above because we do two db ops and if the either fails we don't want any changes to the db made.

Using the model/method in the controller

if($this->some_model->save_stuff($the_stuff) === FALSE)
{
redirect('/wherever');
}
//All OK, proceed
//do other controller things

Using CodeIgniter transactions?

Question: Is there any difference between using

Answer: No. Both do the same sort of job.


Explanation

If You need to get know about CI Transaction Read this answer on another question.

But By only using $this->db->query() you can't archive transaction part comletly.

I Recommend this personally Read this Documentaion


Question: When do you explicitly write out that you want to begin a transaction in a query and when do you just invoke a built-in method from the framework or whatever language you are using?

Answer: (based on PHP/CI)It's based on what kind a system you do.

Explanation

For example, if you have simple product add and its have many child tables. (assume 1 master and 4 child tables). so once one of the child table throws an error, data remain at the upper-level table. So to prevent that we should use Transaction on here.

Assume Child Table 2 occurred an error and this what happens (for Inserted Data).

| Table Name    | Normal Insert     if          |
/update | Transaction |
| ------ | ------ | ------ |
| Master Table | Remain | Roalbacked |
| Child Table 1 | Remain | Roalbacked |
| Child Table 2 | Error | Roalbacked |
| Child Table 3 | Empty | Nothing to do |
| Child Table 4 | Empty | Nothing to do |

Useful Links

  1. Transactions - codeigniter.com
  2. My Answer on another question
  3. php-mysql transaction - mysqltutorial.org

CodeIgniter transactions with multiple functions

Why do you want to do this? Won't work. I saw you use the same table so why don't you do this in the initial function and return the insert ID if you need it, something like this:

public function init_product()
{
$this->db->trans_begin();

$data = array(
'name' => $this->input->post('name'),
'details' => $this->input->post('details'),
'price' => $this->input->post('price'),
'user_id' => $this->session->id_user
);

$this->db->insert('products', $data);

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

return $this->db->insert_id();
}


Related Topics



Leave a reply



Submit