How to treat exception that cannot delete as it is a Foreign key

Asked

Viewed 767 times

4

I am not able to treat an exception that happens when I delete an address that is being used in another table. I’m using the codeigniter

my code is:

public function delete_endereco($cod_clientes_endereco){
    try{
        $acao = $this->db->delete('clientes_enderecos', array('cod_clientes_endereco' => $cod_clientes_endereco));
    }
    catch (SqlException $ex) {
        SqlException::throwDeleteException($ex);
    }
    if($acao){
        $this->session->set_flashdata('success', 'Endereço deletado com sucesso!');
    }
    else{
        $this->session->set_flashdata('error', 'Este endereço não pode ser deletado, pois existe um pedido utilizando ele.');
    }
    redirect("pagina_cliente?page=enderecos");
}

The following error keeps appearing:

A Database Error Occurred

Error Number: 1451

Cannot delete or update a parent row: a foreign key constraint fails (`db`.`pedidos`, CONSTRAINT `fk_pedidos_clientes_enderecos1` FOREIGN KEY (`endereco_cobranca`) REFERENCES `clientes_enderecos` (`cod_clientes_endereco`) ON DELETE NO ACTION ON UPDATE NO ACTIO)

DELETE FROM `clientes_enderecos` WHERE `cod_clientes_endereco` = '5'

Filename: controllers/Pagina_cliente.php

Line Number: 160
  • Can’t mean what exactly?

  • @rray instead of capturing the exception so that I can handle by displaying an error msg, appears: Cannot delete or update a Parent Row: a Foreign key Constraint fails

  • Error and php Exception are two different things, in this case just remove the Try-catch, let the if solve this.

  • @rray already tried to remove the Try-catch, but keeps showing the same screen with the error.

  • This type error appear has no problem in approval environment, in the production environment they will be hidden, of course you should treat and log them.

2 answers

1

Hi. This is because codeigniter does not make an exception in this case.

What you can do is:

Open the database.php file, find the line $db['default']['db_debug'] and seven a to FALSE.

And in your code you can keep the following if:

if ($this->db->_error_number() == 1451)

if you need something special to happen in case the error is released by db. I believe this should work.

  • put as suggested, but now appears the following error: Call to Undefined method Ci_db_mysqli_driver::_error_number()

  • Can you check whether the $query_builder is enabled in your database.php?

  • yes is $query_builder = TRUE;

0

To solve this problem I created a column in my address table called "active", and then instead of doing the delete operation on the address, I just update the "active" column to zero.

and in the listing of all addresses for the user to see, I just list the addresses that have the "active" column equal to 1.

Thank you to everyone who tried to help me...

Browser other questions tagged

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