In PHP, how do you make the PDO not issue FATAL error so that it is possible to identify and handle the error that occurred?
Example: Table: tb_pedidos: id fk_products qtd 1 5 5 2 7 2 3 2 13
Table: tb_products id description 5 Manga 7 Grape 2 Peach
Being relationship between tb_pedidos.fk_products and tb_products.id .
If I try to exclude Manga (id = 5) from the tb_products table ...
$sql = "DELETE FROM tb_produtos where id = ?"; // query
$rs = $this->conn->prepare($sql); // prepara a query
$arParametros = array(5); // parametro(s) para a query
try {
$teste = $rs->execute($arParametros); // executa query
} catch (PDOException $err) {// DEVERIA TRATAR EXCEÇÕES PDO
echo "ERRO PDO.....<br/>";
var_dump($err->getMessage());
var_dump($this->conn->errorInfo());
echo '...fim erros PDO....';
} catch (Exception $err) {// DEVERIA TRATAR OUTRAS EXCEÇÕES (NÃO PDO)
echo "ERRO NÃO PDO.....<br/>";
var_dump($err);
echo "FIM ERRO NÃO PDO.....<br/>";
}
... However, it never enters CATCH
, generates the following error and executes the script:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE [23000]: Integrity constraint violation: 1451 Can not delete or update parent row: a foreign key constraint fails ....
How do I stop script execution? That is, to enter the CATCH and make possible the handling of the error?
Notes:
In the connection I use:
$this->conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->conn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
My Environment:
- PHP 5.6
- MySQL 5.5