I’m working on a product inventory management system using CodeIgniter. I have created a form that collects product information such as brand name, generic name, category, and pricing details. My problem is that while the form validation is successful, the data doesn’t seem to be getting inserted into the database.
Controller InventoryController.php
Here is my addProduct()
function that handles the form submission, validation, and passing of data to the model:
public function addProduct() {
$this->load->model('Inventory_model');
$data = $this->input->post();
$this->load->library('form_validation');
$this->form_validation->set_rules('brand_name', 'Brand Name', 'required');
$this->form_validation->set_rules('generic_name', 'Generic Name', 'required');
$this->form_validation->set_rules('category', 'Category', 'required');
if ($this->form_validation->run() == FALSE) {
// validation failed
$error = array(
"success" => false,
"message" => "Validation failed"
);
echo json_encode($error);
} else {
// validation passed
$data = array(
'brand_name' => $this->security->xss_clean($this->input->post('brand_name')),
'generic_name' => $this->security->xss_clean($this->input->post('generic_name')),
'category' => $this->security->xss_clean($this->input->post('category'))
);
$result = $this->Inventory_model->insertProduct($data);
echo json_encode($result);
}
}
Model InventoryModel.php
This is my insertProduct()
function in the model, which should be inserting the data into the products table:
public function insertProduct($data) {
$this->db->trans_start();
$this->db->insert('products', array(
'brand_name' => $this->security->xss_clean($data['brand_name']),
'generic_name' => $this->security->xss_clean($data['generic_name']),
'category' => $this->security->xss_clean($data['category'])
));
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
$error = array(
"success" => false,
"message" => "Error adding product"
);
return $error;
} else {
try {
$query = "SELECT *, selling_price * quantity as total FROM products ORDER BY product_id DESC";
$result = $this->db->query($query, $product_id);
$row = $result->row_array();
$total = $row['total'];
$badge_class = $row['qty_sold'] < 10 ? 'badge-danger' : 'badge-success';
$response = array(
"success" => true,
"data" => array(
"brand_name" => $row['brand_name'],
"generic_name" => $row['generic_name'],
"category" => $row['category']
)
);
return $response;
} catch (Exception $e) {
$error = array(
"success" => false,
"message" => "Error retrieving product data"
);
return $error;
}
}
}