Kasun Kasun - 4 years ago 201
MySQL Question

Database error 1452

I'm working on this project that have foreign keys on two tables. By using a form I'm trying to insert a new record to the database. And there's also an image path in the db and I'm inserting the image path via the form. I'm using codeigniter file upload library. Other fields of the database table get updated when i submit the form even the foreign key field. But the image path is not updating. When I submit the form it shows this error.

A Database Error Occurred

Error Number: 1452

Cannot add or update a child row: a foreign key constraint fails (`bfh`.`products`, CONSTRAINT `category_fk` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`))

INSERT INTO `products` (`img`) VALUES ('assets/img//sakya.PNG')

Filename: C:/xampp/htdocs/CI-skeleton/system/database/DB_driver.php

Line Number: 691


Controller

public function add_product()
{
$result = 0;
$cat_id = $this->input->post("category_id");
$type_id = $this->input->post("type_id");
$pname = $this->input->post("p_name");
$images = $this->input->post("images");
$images = $_FILES['images']['name'];
$price = $this->input->post("price");

$this->load->model("Products_Model");
$product_id = $this->Products_Model->add_product( $cat_id, $type_id, $pname, $price);

if ($product_id != 0) {
$result = $this->Products_Model->add_product_images($images);
}


if ($result && $_FILES['images']['name'][0] != "") {
$this->load->model('Image_Upload');
$result = $this->Image_Upload->upload("assets/img");
}

$this->session->set_flashdata('result', $result);
redirect('Products');
}


Model

public function add_product( $cat_id, $type_id, $pname, $price)
{
$result = $this->db->get_where("products", array('name' => $pname));
if ($result->num_rows() != 0) {
return 0; // record already exists
} else {
$data = array(
'category_id' => $cat_id,
'type_id' => $type_id,
'name' => $pname,
'price' => $price
);

if( !$this->db->insert('products', $data)) {
return -1; // error
}else{
return $this->db->insert_id();
}

return 1; // success
}
}

public function add_product_images($images)
{
$path = "assets/img/";

foreach ($images as $image) {
// if no images were given for the item
if ($image == "") {
return 1;
}

$data = array(
'img' => $path."/".$image
);

if ( ! $this->db->insert('products', $data)) {
return 0; // if something goes wrong
}
}

return 1;
}

Answer Source

You should use "update" query on the behalf of insert in add_product_images(). Because "insert" will add a new record of the product and there is no any category id(Foreign Key) with this that's why shows this error. So try to update image.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download