delete record that is foreign key in another table

0

I have a php project in the MVC framework. I need to confirm the deletion of records with records in another table. In Calls the user can record evolutions of this service. By excluding a precise call test if there is any evolution in it. Here is the code:

This javascript script receives the id of the record to be deleted:

function delChamado(id) {
  var resposta = confirm("Deseja remover esse registro mesmo?");
  if (resposta == true) {
     $.ajax({
          type: 'POST',
          url: 'controlador/delChamado',
          data: { id: id }
      });
     location.reload();
  }
}

Here the controller receives the id and sends it to the model:

public function delChamado(){
        $id = $_POST['id'];
        $c = new classe_chamado();
        $c->excluir_chamado($id);
    }

And here the model tests whether there are evolutions for the registry:

 public function excluir_chamado($id){ 
        $sql = "SELECT * FROM chamados_evolucao WHERE fk_chamado = '$id'";
        $sql = $this->db->query($sql);
        if ($sql->rowCount() > 0) {
            $sql = "DELETE FROM chamados_evolucao WHERE fk_chamado = '$id'"; 
            $sql = $this->db->query($sql);
            $sql = "DELETE FROM chamados WHERE pk_chamado = '$id'";
            $sql = $this->db->query($sql);
        } else {
            $sql = "DELETE FROM chamados WHERE pk_chamado = '$id'";
            $sql = $this->db->query($sql);
        }
    }

What I tried to do without success was to insert a javascript in the middle of the delete routine, but it did not work!

public function excluir_chamado($id){ 
        $sql = "SELECT * FROM chamados_evolucao WHERE fk_chamado = '$id'";
        $sql = $this->db->query($sql);
        if ($sql->rowCount() > 0) {
            ?>
             <script>
             var confirmar_deletar = confirm("Existem evoluções neste 
             chamado. Tem certeza que quer deletar?");
             if(confirmar_deletar == true){
              <?php
                $sql = "DELETE FROM chamados_evolucao WHERE fk_chamado = '$id'"; 
               $sql = $this->db->query($sql);
               $sql = "DELETE FROM chamados WHERE pk_chamado = '$id'";
               $sql = $this->db->query($sql);
              ?>
             } 
             </script>
            <?php 
        } else {
            $sql = "DELETE FROM chamados WHERE pk_chamado = '$id'";
            $sql = $this->db->query($sql);
        }
    }

Can anyone help me?

    
asked by anonymous 13.06.2018 / 15:34

0 answers