php - 完整性约束违反PDO方法(创建查询)php

标签 php mysql pdo many-to-many

我有 3 个表,分别是子类别、产品和产品类别。

当我创建我的产品时,如果成功,它将返回成功的 product_id,之后它将捕获表单子(monad)类别列,以执行下一个查询,将 product_id 和 subcategory_id 插入到 prod_category 表中。我在单个 php 文件中进行了测试,以测试该功能是否正常工作。它可以插入,但是当我适应我的情况时,它给了我这个错误。

Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (yokotachi.prod_category, CONSTRAINT prod_category_ibfk_4 FOREIGN KEY (product_id) REFERENCES product (product_id) ON DELETE CASCADE ON UPDATE CASCADE) in C:\xampp\htdocs\yokotachi\models\Prod_category.php on line 27

我确认,2个参数被传递给函数,但我不知道为什么它不能执行查询。

if($_POST){ 
$title = mysql_real_escape_string($_POST['title']);
$model = mysql_real_escape_string($_POST['model']);
$description = stripslashes($_POST['description']);
$feature = stripslashes($_POST['feature']);
$specification = stripslashes($_POST['specification']); 

$subcategory_name = mysql_real_escape_string($_POST['product_subcategory']);

$sub_obj = $subcategory->find_by_sub_category_name($subcategory_name);

$subcategory_id = $sub_obj->sub_category_id;
echo $subcategory_id;
$executed_product_id=
    $product->create($title,$model,$description,$feature,$specification);
echo "im here".$subcategory_id;
echo $executed_product_id;
$responde = $prod_category->create($executed_product_id,$subcategory_id);
if($responde){
    echo "<script>";
    echo "alert(".$executed_product_id.");";
    echo "</script>";
    header("location: ../../../views/admin/product/product_index.php");
}}

我确实看到 1 个帖子是 reindex 问题,并要求截断表。但我不知道如何在我的情况下执行截断查询。

提前致谢。

最佳答案

错误消息似乎是在告诉您您尝试在表“prod_category”中使用的产品 ID 号在表“product”中不存在。

您需要找出执行此行后 $executed_product_id 的值。

$executed_product_id=
    $product->create($title,$model,$description,$feature,$specification);

如果它的值不在表“product”中,那是你的问题。外键引用要求产品 ID 存在于“product”中,然后才能在“prod_category”中使用它。

关于php - 完整性约束违反PDO方法(创建查询)php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12937377/

相关文章:

mysql - Phalcon:MySQL 触发器无法与 Phalcon 框架一起使用

php - Laravel 5.1 Mailer 试图获取非对象的属性

php - 调用非对象的成员函数,但对象是 $this 即它本身?

sql - 为每个类别选择 N 条记录并按 X 排序

mysql - 不允许通过 IISExpress 连接到 Mysql 服务器

php - 在 PHP 中从 MySQL 结果创建一个没有重复项的数组

MySQL 和 PDO : about efficiency

php - 在 RHEL 6 上编译 `mysql_pdo` 驱动程序(无法访问互联网,没有 `yum install` )

PHP 数组 : Extract from CSV

php - 从被关注的用户中选择帖子