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

-1

Good morning, someone would know how to handle the following error:

Thefollowingerroroccurswhen,forexample,IhaveaclientinaDBtableandinanothertableIhaveabudgetreferencingthisclient,whenItrytodeletetheclientitpresentsthiserror,whichiscorrect,IreallydonotwanttodeletethisclienttomaintaintheintegrityofDB.

WhatIwantisthatthiserrorbepresentedinabetterwayfortheuser,somethingintheformofamessageexplainingwhytheclientcannotbedeleted.

I'musingPHPandcodeignitertomakethislittlesystem.

Edit,codesused:

Controller:

functiondeletar($pcod){/*Executaafunçãodeletardomodelopassandocomoparâmetrooiddapessoa*/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');
    }
    
asked by anonymous 05.06.2017 / 13:08

2 answers

2

It turns out that CI does not work very well with Try Catch, one way is to disable debugging for queries, which causes this error to be returned to the screen and validated with its own tools. One solution would be something like 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();
}
    
05.06.2017 / 14:07
0

I think 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();
}
    
05.06.2017 / 14:05