未捕获的异常PDOException:违反完整性约束错误

时间:2019-04-12 18:35:51

标签: php sql pdo

我有一个错误

  

致命错误:消息为'SQLSTATE [23000]的未捕获异常'PDOException':违反完整性约束:1452无法添加或更新子行:外键约束失败(gymdatabasenutrition,在G:\第五学期\电子商务\ xampp \ htdocs \ app中约束nutrition_ibfk_2外键(food_id引用foodfood_id)在更新级联上删除级联) \ models \ Nutrition_model.php:11堆栈跟踪:#0 G:\第5个学期\ Ecommerce \ xampp \ htdocs \ app \ models \ Nutrition_model.php(11):PDOStatement-> execute(Array)#1 G:\第5个学期\ Ecommerce \ xampp \ htdocs \ app \ controllers \ Nutrition.php(59):Nutrition_model-> insert()#2 [内部功能]:Nutrition-> create()#3 G:\第五学期\ Ecommerce \ xampp \ htdocs \ app \ core \ App.php(38):call_user_func_array(Array,Array)#4 G:\ 5th semester \ Ecommerce \ xampp \ htdocs \ index.php(5):App-> __ construct()#5 {main}在第11行的G:\第五学期\ Ecommerce \ xampp \ htdocs \ app \ models \ Nutrition_model.php中抛出

所以我的数据库中有2个表。 在food表中,有food_id,名称,描述,路径列。 营养表中有nutri_id,user_id,food_id列。 因此,在营养表中有一个外键是food_id 而且两个表中都没有任何数据。 我多次遇到此错误,但这主要是因为我的外键被限制删除,或者表中已经存在违反约束的数据,但这不是事实。

public function insert()//for event
    {
        $stmt = $this->_connection->prepare("INSERT INTO nutrition(user_id, food_id) VALUES(:user_id, :food_id)");
        $stmt->execute(['user_id'=>$this->user_id,'food_id'=>$this->food_id]);
        return $stmt->rowCount();
    }

public function create()
    {

        if(isset($_POST['nutrition_action']))
        {       

            $nutrition = $this->model('Nutrition_model');
            $user_id = $_SESSION['user_id'];
            $nutrition->user_id = $user_id;

            $gender = $_POST['gender'];
            $type = $_POST['type'];     
            $cheating = $_POST['cheating'];


            if($cheating == "Hell Yes")//CH
            {
                $food = 1;

            }
            else if($gender == "Male")
            {
                if($type == "Lose Weight") //ML
                {
                    $food = 4;

                }
                else if($type == "Maintain Weight") //MM
                {
                    $food = 7;
                }
                else//MG
                {
                    $food = 10;
                }
            }
            else
            {
                if($type == "Lose Weight")
                {
                    $food = 0;
                }
                else if($type == "Maintain Weight")
                {
                    $food = 0;
                }
                else
                {
                    $food = 0;
                }
            }
            $nutrition->food_id = $food;
            $nutrition->insert();

            //header('location:/Nutrition/automatic_index');//send somewhere
        }
        else
        {
            $this->view('nutrition/nutrition_create');
        }


    }

1 个答案:

答案 0 :(得分:1)

外键约束要求在外表中有用于INSERT的记录。

如果仍然从另一个表中引用并且具有FK约束,则无法删除该记录。

使用DE DELETE CASCADE,如果您删除食物记录,则所有带有food_id的营养素也会被删除。