加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

如何在Php中处理MySQL的外键错误?

发布时间:2020-12-11 23:46:03 所属栏目:MySql教程 来源:网络整理
导读:我在MySQL中测试外键.目标是防止将id输入table2,这在table1中不存在.我希望使用外键只会导致一行没有插入,但它似乎抛出了这个巨大的错误.我如何在PHP中处理这个?有没有办法让MySQL根本不插入行并返回没有返回的行? Fatal error: Uncaught exception PDOExc

我在MySQL中测试外键.目标是防止将id输入table2,这在table1中不存在.我希望使用外键只会导致一行没有插入,但它似乎抛出了这个巨大的错误.我如何在PHP中处理这个?有没有办法让MySQL根本不插入行并返回没有返回的行?

Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (wp-db.borrowed,CONSTRAINT borrowed_ibfk_1 FOREIGN KEY (employeeid) REFERENCES employee (id) ON DELETE CASCADE ON UPDATE CASCADE)’ in C:webapachehtdocsdevforeign.php:10

Stack trace:

#0 C:webapachehtdocsdevforeign.php(10): PDOStatement->execute()

#1 {main} thrown in C:webapachehtdocsdevforeign.php on line 10

最佳答案 用try catch

try { 
    $pdo->exec ("QUERY WITH SYNTAX ERROR"); 
} catch (PDOException $e) { 
    if ($e->getCode() == '23000') 
        echo "Syntax Error: ".$e->getMessage(); 
}

阅读PDOStatement::errorCode

取自Return Code list

The SQL-92 standard defines a set of SQLSTATE return codes. SQLSTATE
is defined as a five-character string,where the leftmost two
characters define the error class,and the remaining three characters
define the error subclass. Some database vendors may extend these
return codes; classes beginning with the numbers 5 through 9 and
letters I through Z are reserved for such implementation-specific
extensions. The SQLSTATE code for a particular JDBC action can be
retrieved via the getSQLState() method of SQLException

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读