PDO:完整性约束违规(更新表)

时间:2015-03-23 14:31:52

标签: php mysql sql pdo

第一张表:

CREATE TABLE Portfolio_Categories 
(
  cat_id int(11) NOT NULL,
  cat_title varchar(255) NOT NULL,
  cat_dir varchar(255) NOT NULL
) 
ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

第二张表:

CREATE TABLE Portfolio_Images 
(
  img_id int(11) NOT NULL,
  cat_id int(11) NOT NULL,
  img varchar(255) NOT NULL,
  img_title varchar(255) DEFAULT NULL
) 
ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=latin1 COMMENT='Table to store the Portfolio Images';

约束:

ALTER TABLE Portfolio_Categories
  ADD PRIMARY KEY (cat_id);

ALTER TABLE Portfolio_Images
  ADD PRIMARY KEY (img_id), ADD KEY cat_id (cat_id), ADD KEY img_id (img_id);

ALTER TABLE Portfolio_Images ADD CONSTRAINT cat_id FOREIGN KEY
    (cat_id) REFERENCES Portfolio_Categories (cat_id);

我的PHP代码:

$query =   "UPDATE
                Portfolio_Images
            SET
                Portfolio_Images.img = :new_img,
                Portfolio_Images.img_title = :new_tit,
                Portfolio_Images.cat_id =
                    (SELECT t_cat.cat_id FROM (SELECT * FROM Portfolio_Categories) AS t_cat WHERE t_cat.cat_title = :new_cat)
            WHERE
                Portfolio_Images.img = :old_img;";
$stmt = $_MySQLConn->prepare($query);

$stmt->bindParam(':new_img', $new_img);
$stmt->bindParam(':new_tit', $new_tit);
$stmt->bindParam(':new_cat', $new_cat);
$stmt->bindParam(':old_img', $old_img);

if($stmt->execute())
{
    $return_value = array('success'=>true,
                          'new_img:'=>$new_img,
                          'new_tit'=>$new_tit,
                          'new_cat'=>$new_cat,
                          'old_img'=>$old_img);
}
else
{
    $return_value = array('success'=>false,'error_code'=>'Could not execute query');
}

它应该做什么:

它应该在没有任何错误的情况下更新我的表(就像我直接运行语句一样)

它做了什么:

PHP向我显示了此错误消息:

  

SQLSTATE [23000]:完整性约束违规:1452无法添加或   更新子行:外键约束失败   (1_new.Portfolio_Images,CONSTRAINT cat_id FOREIGN KEY   (cat_id)REFERENCES Portfolio_Categories(cat_id))

1 个答案:

答案 0 :(得分:1)

这意味着您要在Portfolio_Images中插入一行Portfolio_Images.cat_idPortfolio_Categories.cat_id中不存在Portfolio_Categories.cat_id中的值。

换句话说,如果在Portfolio_Images.cat_id中您只有值1,2,4,则只能在{{1}}中插入值1,2或4。