如何处理PHP中的MySQL外键错误? [英] How to handle MySQL's Foreign Key Error in Php?
问题描述
我正在测试MySQL中的外键.目的是防止id
进入table1
中不存在的table2
.我希望使用foreign keys
只会导致未插入行,但似乎引发了这个巨大的错误.如何在PHP中处理此问题?有没有一种方法可以使MySQL简单地不插入行并且不返回任何返回的行?
I was testing foreign keys in MySQL. The objective is to prevent the entry of an id
into table2
, that does not exist in table1
. I was hoping that using foreign keys
would simply result in a row not being inserted, but it seems to throw up this huge error. How do I handle this in PHP? Is there a way to make MySQL simply not insert the row and return no rows returned?
致命错误:消息为'SQLSTATE [23000]的未捕获异常'PDOException':违反完整性约束:1452无法添加或更新子行:外键约束失败(
wp-db
.borrowed
,CONSTRAINTborrowed_ibfk_1
C:\ web \ apache \ htdocs \ dev \ foreign.php:10
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
, CONSTRAINTborrowed_ibfk_1
FOREIGN KEY (employeeid
) REFERENCESemployee
(id
) ON DELETE CASCADE ON UPDATE CASCADE)' in C:\web\apache\htdocs\dev\foreign.php:10
堆栈跟踪:
#0 C:\ web \ apache \ htdocs \ dev \ foreign.php(10):PDOStatement-> execute()
#0 C:\web\apache\htdocs\dev\foreign.php(10): PDOStatement->execute()
在第10行的C:\ web \ apache \ htdocs \ dev \ foreign.php中抛出#1 {main}
#1 {main} thrown in C:\web\apache\htdocs\dev\foreign.php on line 10
推荐答案
使用try catch
use try catch
try {
$pdo->exec ("QUERY WITH SYNTAX ERROR");
} catch (PDOException $e) {
if ($e->getCode() == '23000')
echo "Syntax Error: ".$e->getMessage();
}
摘自返回代码列表
SQL-92标准定义了一组SQLSTATE返回代码. SQLSTATE 定义为五个字符的字符串,其中最左边的两个 字符定义错误类别,其余三个字符 定义错误子类.一些数据库供应商可能会扩展这些 返回码;以数字5到9开头的课程,以及 字母I到Z保留用于此类实现特定的 扩展名.特定JDBC操作的SQLSTATE代码可以是 通过
SQLException
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 ofSQLException
这篇关于如何处理PHP中的MySQL外键错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!