Cannot add or update a child row: a foreign key constraint fails (
warehouse_inventory_system
.inventory_products
, CONSTRAINTfk_category
FOREIGN KEY (Category_Id
) REFERENCEScategory
(Category_Id
)) INSERT INTOinventory_products
(Product_Name
,Category_Id
,Brand_Name
,Unit_Price
,Date_of_Entry
,Quantity
) VALUES (0, 0, '1', '120', '2016-03-31', '12')
运行的代码是
<?php
$query = $this->db->query('SELECT * FROM category');
foreach ($query->result() as $row) {
echo '<option value="'. $row->Category_Id. '">'. $row->Category_Name. '</option>';
}
?>
Insert code is:
function create(){
$this->form_validation->set_rules('Unit_Price','Unit_Price','trim|xss_clean|numeric|is_natural_no_zero|min_length[2]');
$this->form_validation->set_rules('Quantity','Quantity','trim|xss_clean|numeric|is_natural_no_zero');
if ($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
$data = array(
'Product_Name' => $this->input->post('Product_Name'),
'Category_Id' => $this->input->post('Category_Id'),
'Brand_Name' => $this->input->post('Brand_Name'),
'Unit_Price' => $this->input->post('Unit_Price'),
'Date_of_Entry' => $this->input->post('Date_of_Entry'),
'Quantity' => $this->input->post('Quantity')
);
$this->Admin_model->add_items($data);
$this->index();
}
}
Admin_model
function add_items($data){
$this->db->insert('inventory_products', $data);
return;
}
最佳答案
您正在尝试将新记录插入 inventory_products
表 category_id
等于 0 并且因为 inventory_products
指category
表category
中没有记录如果表的category_id = 0,它会抛出外键约束失败错误。
检查您的<input>
和<select>
并确保他们的name
属性与您在 PHP 代码中读到的属性相匹配。例如:必须有<select>
标签名称 Category_Id
.
关于php - Codeigniter php 上的数据库错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36110711/