如何使用PHP检查删除限制上的外键约束

时间:2013-10-30 15:15:57

标签: php mysql sql database

我有两个表产品购买。 我在on delete restrict列中设置product.purchase_id FK,其中purchase.purchase_id列。然后,如果我尝试用FK删除product.product_id,它会显示错误,就像

一样
A Database Error Occurred

Error Number: 1451

Cannot delete or update a parent row: a foreign key constraint fails (`another_bata`.`product_purchase_item`, CONSTRAINT `FK_product_purchase_item_1` FOREIGN KEY (`product_id`) REFERENCES `product` (`product_id`) ON UPDATE CASCADE)

delete from product where product_id='158'

Filename: C:\xampp\htdocs\rima_shoe\system\database\DB_driver.php

Line Number: 330

  

但我需要一个用户友好的错误,假设您无法删除此产品   列表,因为您已经存储了此产品

所以我需要在php中检查这个FK,我该怎么做?

我的第二个问题..在某些特殊情况下,是否可以删除已存在on delete restrict FK的'product.product_id'?假设

DELETE p,q FROM product AS p INNER JOIN purchase AS q
WHERE p.purchase_id=q.purchase_id AND q.purchase_quan=0

2 个答案:

答案 0 :(得分:4)

使用例外:

try {
    $db->query(...);
} catch (Exception $e) {
    echo "an error occured during query";
}

您还可以制作自己的例外以专门针对FK错误:

class ForeignKeyException extends Exception {
    public function __construct($msg = 0, $code = 0) {
        parent::__construct($msg, $code);
    }
}

当发生FK错误时,您执行throw new ForeignKeyException('FK failed');

try {
    $db->query(...);
} catch (ForeignKeyException $e) {
    echo "FK error";
} catch (Exception $e) {
    echo "general error";
}

<强>更新

mysqli已经有例外:

} catch (mysqli_sql_exception $e) {
    if ($e->getCode() == 'CODE FOR FK') {
        //...
    }
}

PHP mysqli例外:http://php.net/manual/en/class.mysqli-sql-exception.php

请参阅MYSQLI错误代码:http://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html

另一个有用的问题:Handling foreign key exceptions in PHP

第二个问题的更新:

通过

禁用外键
SET foreign_key_checks = 0;
<your delete query here>
SET foreign_key_checks = 1;

答案 1 :(得分:2)

关于你的第二个问题,我猜你可以用php检查条件,如果是,则运行此查询:

START TRANSACTION
SET FOREIGN_KEY_CHECKS=0;
DELETE WHAT YOU WANT;
SET FOREIGN_KEY_CHECKS=1;
COMMIT

但外键是有原因的,任意玩它们可能会迟早给你留下惊喜