0

I am new to CI and PHP too.

I have a form that which add a company and its contacts to the server including file upload .

i need all things on one button click.

so

function create_company()
{

 $insert = $this->database->insert();

 return $insert["insertID"]; //returns the inserted ID

}

function file_upload()
{

//upload files if there are some file input selected

return $array_of_uploaded_files;
}

function insert_contacts($company_id,$contacts_array)
{
//return true if everything success

}

My problems are

  1. First Company insertion is success,but failed to add its contacts,then i need to delete the current inserted item
  2. If insert_contact failed i need to delete the uploaded files

So is there any way to roll back actions if one or more of its dependency failed ?

I know transactions in Codeignitor ,but how can i use it [with multiple function scope] ?

What about file upload ?

Please note that i am asking this question because i am new to php , what i can do is that create so many functions and call it on appropriate situations.

I just want to know that how can i improve or simplify my codes...

Thank you.

Colin Brock
  • 21,267
  • 9
  • 46
  • 61
Red
  • 6,230
  • 12
  • 65
  • 112

1 Answers1

1

Why not use transactions?

http://ellislab.com/codeigniter/user-guide/database/transactions.html

So something like:

$this->db->trans_start();
// your database queries
$this->db->trans_end();

Check if there's any error with the transaction by:

$this->db->trans_status();    
prashant thakre
  • 5,061
  • 3
  • 26
  • 39
Steven Lu
  • 2,150
  • 1
  • 24
  • 33
  • Thanks ... i want transaction happened in one function and checking in another function is this possible ?currenty i have records for successful/failed operations ... and what about file uploads ? any clue ... :) – Red Jul 05 '12 at 16:28
  • Sure, $this->db is singular and can be used across all your models and controllers. So start your db->transaction() in your controller and if you encounter an error in your models, just don't call trans_end(). – Steven Lu Jul 05 '12 at 16:30