How to treat error when deleting a BD record, which has a foreign key, PHP

Asked

Viewed 337 times

-1

Good morning guys, someone would tell me the best way to treat the following mistake: erro retornado

The following error occurs when, for example, I have a client in a BD table and in another table I have a budget referencing this client, when I try to exclude the client it presents this error, what is correct I really do not want to delete this client to maintain the integrity of the comic book.

What I want is for this error to be presented in a better way for the user, something in the form of a message explaining why it is not possible to delete the client.

I’m using PHP and codeigniter to make this small system.

Edit, codes used by:

Controller:

function deletar($pcod) {

        /* Executa a função deletar do modelo passando como parâmetro o id da pessoa */
        if ($this->model->deletar($pcod)) {
                $this->session->set_flashdata('mensagem', "<div class='alert alert-warning'> Produto deletado com sucesso</div>");
                redirect('produtos');
            } else {
                $this->session->set_flashdata('mensagem', "<div class='alert alert-danger'> Erro ao deletar Produto</div>");
            }
    }

Model:

function deletar($pcod) {
        $this->db->where('pcod', $pcod);
        return $this->db->delete('produtos');
    }

2 answers

2


It turns out that CI does not work very well with Try Catch, one way is to disable debug for queries, which returns this error on the screen and validate it with the tools themselves. A solution would be something with this:

<?php

function deletar($pcod) {
    $this->db->where('pcod', $pcod);    

    $db_debug = $this->db->db_debug; //salve a configuração
    $this->db->db_debug = FALSE; //desabilita o debug para consultas

    if ( !$this->db->delete('produtos') )
    {
        $error = $this->db->error();

        // Tratativa de erro aqui
        /*
         * Seu código...
         */
        $this->db->db_debug = $db_debug; //restaure a configuração de debug

        return $alguma_coisa_que_queira_retornar;
    }

    return $this->db->affected_rows();
}
  • just to confirm if I understood I would put this code in my modal ? my sql is as follows: function deletar($pcod) {&#xA; $this->db->where('pcod', $pcod);&#xA; return $this->db->delete('produtos');&#xA; }

  • Post the part of the code where you delete, I will insert in the correct point to perform the test.

  • Post Edited with the code

  • I changed the code, try the test and see if you’ll answer.

0

I believe the best way out is to use a Try catch block:

try {
    //coloque aqui sua query 
    //TO DO
}

catch (MySQLException $e) {
    // mysql exception - trate aqui a váriavel abaixo para exibir o erro como quiser
    $e->getMessage();
}

Browser other questions tagged

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