php - Codeigniter php 上的数据库错误

标签 php mysql codeigniter

Cannot add or update a child row: a foreign key constraint fails (warehouse_inventory_system.inventory_products, CONSTRAINT fk_category FOREIGN KEY (Category_Id) REFERENCES category (Category_Id)) INSERT INTO inventory_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_productscategory_id等于 0 并且因为 inventory_productscategorycategory中没有记录如果表的category_id = 0,它会抛出外键约束失败错误。

检查您的<input><select>并确保他们的name属性与您在 PHP 代码中读到的属性相匹配。例如:必须有<select>标签名称 Category_Id .

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

相关文章:

php - 如何将选择表值存储为 php 以在 sql 查询中使用

PHP 表单,检查 2 个日期是否相隔不远

php - 缓慢的 MySQL 全文搜索

javascript中基于mysql查询的php循环

MySQL - 返回每个数据组的最后一条记录

php - 从URL Codeigniter获得值(value)

php - MySQL SELECT JOIN WHERE ORDER BY 性能

mysql - 将缩写字符串格式的日期转换为mysql中的日期格式

php - codeigniter 如何加载 View 文件并传递变量?

php - Codeigniter 优化/加载模型的最佳位置是?