0

I have a PHP script and some constraint rules in Mysql to prevent the user from deleting a category that contains products. But when the user try to delete the prohibited category he will face a fatal error instead of the website page

Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails...

I need to show an error like below instead of Fatal error:

You can not delete this category while it has products related.

Edit : note that the try/catch will not work for fatal errors

Amin Gholibeigian
  • 1,325
  • 2
  • 9
  • 11

1 Answers1

-1

You can either put your query in a try and catch statement and try to catch all errors that occur during the query:

try{
//query
}
catch(Error $error){
//do something
}

Or put a error handler for your whole document:

function myCustomErrorHandler(int $errNo, string $errMsg, string $file, int $line) {
//do something
}

set_error_handler('myCustomErrorHandler'); 

I've got the idea originally from this website: https://netgen.io/blog/modern-error-handling-in-php

Timinator
  • 52
  • 6
  • 1
    It can be difficult with a global error handler to provide some meaningful error. – Nigel Ren Jan 16 '21 at 19:33
  • true, but useful if you just want to relay the user to a specific site, if an error occurs. In this case, if he wants to display an error message, it wouldn't really be viable. – Timinator Jan 16 '21 at 19:39
  • 1
    I used try catch but i faced the fatal error again – Amin Gholibeigian Jan 16 '21 at 19:46
  • 1
    then please use the `error_handler`, I just read that the `try catch` method can not handle fatal errors ([link](https://stackoverflow.com/questions/12928487/php-try-catch-and-fatal-error?rq=1)), sorry for the confusion – Timinator Jan 16 '21 at 19:51
  • He literally pasted the error and it says `fatal error`. The code isn't buggy at all – Timinator Jan 17 '21 at 10:42