每次我将图像插入数据库时都会出现此错误
错误号码:1452
无法添加或更新子行:外键约束失败 (
herbalcebu
。product
,CONSTRAINTproduct_ibfk_1
FOREIGN KEY (categorie_id
)参考categorie
(categorie_id
))INSERT INTO
product
(product_image
)VALUES(' q3.jpg')文件名:C:/xampp/htdocs/HerbalCebu/system/database/DB_driver.php
行号:691
这是我的控制器代码
public function insert_product()
{
$this->form_validation->set_rules('product_name','Productname','required');
$this->form_validation->set_rules('product_price','Amount','required');
$this->form_validation->set_rules('product_stock','Stock','required');
$this->form_validation->set_rules('categorie_id','categorie_id','required');
$this->form_validation->set_rules('product_description','Description','required');
$config = array
(
'upload_path' => './assets/img',
'allowed_types' => 'jpg|png|jpeg|bmp',
'max_size'=> 0,
'filename' => $_FILES['product_image']['name']
);
$this->load->library('upload',$config);
if($this->upload->do_upload('product_image'))
{
$uploaddata = $this->upload->data();
$product_image=$uploaddata['file_name'];
$this->db->insert('product',array('product_image'=>$this->upload->file_name));
}
if ($this->form_validation->run())
{
$data = $this->input->post();
unset($data['submit']);
$this->load->model('queries_product');
if($this->queries_product->insert_product($data))
{
$this->session->set_flashdata('msg','Successfully Inserted');
}
else
{
$this->session->set_flashdata('msg','Failed to Insert');
}
return redirect('inventory');
}
else
{
echo validation_errors ();
}
}
我的模型代码
public function insert_product($data)
{
return $this->db->insert('product',$data);
}
答案 0 :(得分:1)
如果上传图片,您的代码正在进行图片插入,如果表单已经过验证,则会执行整个数据插入。
您的产品表具有categorie_id
字段约束,不能为空&应存在于类别表中,因此您得到上述错误。
您应该将product_image
数据与整个产品数据合并,方法是添加条件(如果已上传)添加其他上传的图片数据:
public function insert_product()
{
$this->form_validation->set_rules('product_name','Productname','required');
$this->form_validation->set_rules('product_price','Amount','required');
$this->form_validation->set_rules('product_stock','Stock','required');
$this->form_validation->set_rules('categorie_id','categorie_id','required');
$this->form_validation->set_rules('product_description','Description','required');
if ($this->form_validation->run())
{
$data = $this->input->post();
$config = array
(
'upload_path' => './assets/img',
'allowed_types' => 'jpg|png|jpeg|bmp',
'max_size'=> 0,
'filename' => $_FILES['product_image']['name']
);
$this->load->library('upload',$config);
if($this->upload->do_upload('product_image'))
{
$uploaddata = $this->upload->data();
$product_image=$uploaddata['file_name'];
$data['product_image'] = $product_image;
}
unset($data['submit']);
$this->load->model('queries_product');
if($this->queries_product->insert_product($data))
{
$this->session->set_flashdata('msg','Successfully Inserted');
}
else
{
$this->session->set_flashdata('msg','Failed to Insert');
}
return redirect('inventory');
}
else
{
echo validation_errors ();
}
}
答案 1 :(得分:0)
您的categoryID与类别
不匹配