【问题标题】:Integrity constraint violation PDO method (create query) php完整性约束违反PDO方法(创建查询)php
【发布时间】:2012-10-17 15:04:22
【问题描述】:

我有 3 个表,分别是 subcategory、product 和 prod_category。

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

警告:PDOStatement::execute() [pdostatement.execute]: SQLSTATE[23000]: 完整性约束违规:1452 无法添加或更新子行:外键约束失败 (yokotachi.prod_category, CONSTRAINT prod_category_ibfk_4 FOREIGN KEY (product_id) REFERENCES product (product_id) ON DELETE CASCADE ON UPDATE CASCADE) 在 C:\xampp\htdocs\yokotachi\models\Prod_category.php 第 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 个帖子是重新索引问题,并要求截断表格。但我不知道如何在我的情况下执行截断查询。

提前致谢。

【问题讨论】:

  • 数据库表是你建的还是别人的?
  • @N.B.:我会说其他人设置了表格。致 OP:阅读 FOREIGN KEY CONSTRAINTS 并且为了避免必须执行 3 个单独的查询:JOIN
  • 第 27 行是 if(!$stmt->execute()){throw new PDOException()}
  • @N.B 不,我正在自己布置桌子......

标签: php mysql pdo many-to-many


【解决方案1】:

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

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

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

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

【讨论】:

  • Oic,其实executed_product_id是执行$product>create($title,$model,$description,$feature,$specification)时返回的product_id;我在执行查询之前尝试回显,并且存在一个已经存在的值。即使在要执行的函数中,在准备语句之后和执行查询之前,我也尝试将其回显,它确实具有我想要的值。所以,我不知道,怎么会这样:(
  • 你试图回应什么? PHP变量?如果是这样,请查看实际表格。
  • 是的,看看实际的表怎么说?你什么意思?你的意思是在执行create时,product_id是存在还是已创建?
  • 我的意思是用mysql命令行工具或者phpMyAdmin之类的东西连接数据库,直接看表的内容。看看你期望的值是否真的存在。他们可能不是。
  • 嗯,oic...yupz,实际上我也尝试过.. 我确实尝试使用 phpMyadmin 插入预期的数据,它成功.. >.
猜你喜欢
  • 1970-01-01
  • 2015-05-26
  • 2020-01-14
  • 2013-07-04
  • 2015-01-20
  • 2017-03-01
  • 1970-01-01
  • 2021-12-13
相关资源
最近更新 更多