2013-08-30 55 views
5

Tôi đã thử nghiệm các khóa ngoại trong MySQL. Mục tiêu là để ngăn chặn việc nhập một số id vào table2, không tồn tại trong table1. Tôi đã hy vọng rằng bằng cách sử dụng foreign keys sẽ chỉ đơn giản là kết quả trong một hàng không được chèn vào, nhưng có vẻ như để ném lên lỗi này rất lớn. Làm thế nào để xử lý điều này trong PHP? Có cách nào để làm cho MySQL chỉ đơn giản là không chèn hàng và trả về không có hàng trả lại?Làm thế nào để xử lý lỗi ngoại khóa của MySQL trong Php?

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:\web\apache\htdocs\dev\foreign.php:10

Stack trace:

#0 C:\web\apache\htdocs\dev\foreign.php(10): PDOStatement->execute()

#1 {main} thrown in C:\web\apache\htdocs\dev\foreign.php on line 10

Trả lời

4

sử dụng cố gắng nắm bắt

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

đọc PDOStatement::errorCode

lấy từ 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