I need to add a product in the "products" table, once the product has been added, return the product ID, then I need to add the details of that product in the "details_product" table
In the official page of Codeigniter they show how to do it but without using functions, for example:
$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 maintain the 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 undo the records OR if there is another best practice or another way to do it.
Instead of using this $ this-> db- > query ('AN SQL QUERY ...'); I'm 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();
}
}
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;
}
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 specified above, I need to know if this way is functional even if I do not follow the example of the official Codeigniter website, if I use these functions Codeigniter can detect if the queries or insertions in the database fail, also if they can give me a better example.
I appreciate your help very much