Welcome Guest, Not a member yet? Register   Sign In
Codeigniter transactions with multiple functions
#1

I need to add a product in the "products" table, and I get the added product ID and then add the details of that product in the table "product details"

In the official page of Codeigniter they show how to do this but without using functions, eg:

PHP Code:
$this->db->trans_start(TRUE); // Query will be rolled back
$this->db->query('AN SQL QUERY...');
$this->db->trans_complete(); 

I need to use functions and still maintain integrity that if one of the two queries fails then the records are not added, I have prepared the following code and I want to know if in this way Codeigniter will be able to detect if the query fails or not to undo the records Or if there is another best practice or other way of doing it.


PHP Code:
// Instead of using the $this->db->query('AN SQL QUERY...'); I am using a function:
public function init_product()
{
 
   $this->db->trans_begin();
 
   $this->new_product();
 
   $this->new_product_details();

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


PHP Code:
// Adding the product and returning the aggregate product ID
public function new_product()
     
    $data 
= array(            
        
'name' => $this->input->post('name'),
 
       'details' => $this->input->post('details'),
 
       'price' => $this->input->post('price')
 
   );
 
   $this->db->insert('products'$data);
 
   if($this->db->affected_rows()) {            
        return $this
->db->insert_id();
 
   }
 
   return false;


PHP Code:
// Adding Product Details
public function new_product_details()
     
    $data 
= array(            
        
'product_id' => $this->new_product(),
 
       'user_id' => $this->session->id_user
    
);
 
   $this->db->insert('products'$data);
 
   if($this->db->affected_rows()) {            
        return true
;
 
   }
 
   return false;



As you specify, I need to know if this way is functional even though I do not follow the example as done in Codeigniter, and if using these functions Codeigniter can detect whether or not queries or insertions in the database fail, also if they can give me Some better example.

Thanks for your help
Reply


Messages In This Thread
Codeigniter transactions with multiple functions - by funcion - 06-21-2017, 06:31 AM



Theme © iAndrew 2016 - Forum software by © MyBB