且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-04 14:53:34

使用例外:

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

您也可以创建自己的例外来专门处理FK错误:

You can also make your own Exceptions to speciallize for FK errors:

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

发生FK错误时,您抛出新的ForeignKeyException('FK failed');

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

更新:

mysqli已经有例外:

mysqli has exceptions already:

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

PHP mysqli异常: http://php.net/manual/en/class.mysqli-sql-exception.php

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

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

See MYSQLI error codes: http://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html

另一个有用的问题:在PHP中处理外键异常

第二个问题的更新:

通过

SET foreign_key_checks = 0;
<your delete query here>
SET foreign_key_checks = 1;