gpt4 book ai didi

php - 数据库错误 1452

转载 作者:行者123 更新时间:2023-11-29 11:02:04 27 4
gpt4 key购买 nike

我正在开发这个项目,该项目在两个表上都有外键。通过使用表单,我尝试将新记录插入数据库。数据库中还有一个图像路径,我通过表单插入图像路径。我正在使用 codeigniter 文件上传库。当我提交表单时,数据库表的其他字段甚至外键字段都会更新。但图像路径没有更新。当我提交表单时,它显示此错误。

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');
}

型号

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;
}

最佳答案

您应该使用“更新”查询来代替 add_product_images() 中的插入。因为“插入”将添加产品的新记录,并且没有任何类别 id(外键),这就是显示此错误的原因。所以尝试更新图像。

关于php - 数据库错误 1452,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42061912/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com