How to treat exception released "Integrity Constraint Violation: Cannot delete or update a Parent Row: a Foreign key Constraint fails"?

Asked

Viewed 744 times

3

I use the class PDO for communication with the banco de dados and I don’t know a good way to capture this exceção.

I looked for a class that extends PDOException but I didn’t find.

I can do a query before deleting, it solves, but wanted to treat when the exception is cast, or this is not the best way?

  • Every "Integrity Constraint Violation" exception comes with an error message that starts with SQLSTATE[23000]. Have you tried treating your exception based on this?

  • Exactly that @Rodrigorigotti, Thanks, with that I found out that the object of the Pdoexception class has a method getCode() return the exact number, thanks @Rodrigorigotti

  • example: }catch(PDOException $e){ echo $e->getCode();}

1 answer

1


There are cases where the getCode() da Pdoexception does not return the correct code.

In this case I use:

try {
   ....
} catch (PDOException $e) {
   if (isset($e->errorInfo[1]) && $e->errorInfo[1] == '1451') {
      print 'mensagem';
   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.