Delete button with modal mysql/php

Asked

Viewed 2,600 times

0

I am a beginner and I have a problem with a button (delete with modal). When clicking the button, the system should display the modal and if I click "yes", should delete the record.

I’m keeping my codes on one page only: "detailsTarefas.php".

Button code:

<form method="post" action="">
    <div class="direita" style="padding-right:30px;">
    <a href="#excluir" data-uk-modal >
    <div class="btn_all2" type="submit" id='btnApagar' style="margin-left:15px; background-color:#ff0000;">
                EXCLUIR </div> </a>
</form>

Modal code:

<div id="excluir" class="uk-modal" >
<div class="uk-modal-dialog">
    <div class="uk-modal-header">Excluir</div>
    Deseja mesmo excluir a tarefa?
    <div class="uk-modal-footer uk-text-right">
        <a class="uk-button" href="">Não</a>
        <a class="uk-button uk-button-primary" type="submit" name="botaoConfirma" value="true" href="painel_constru.php?constru=tarefas">Sim</a>
    </div>
</div>

Condition triggered by the button:

$codigo=$_GET["id"];
if (isset($_POST["btnApagar"])) {

    if (isset($_POST["botaoConfirmar"])) {
        $comandoExcluir = "DELETE FROM tbTarefa WHERE idTarefa =" .$codigo; 
        $resultado = $c ->criarConsulta($comandoExcluir);

        if ($resultado) {
            echo "Removido com sucesso";
        } else{
            echo "Não foi removido";
        }
    }
}

By clicking the button the record is not deleted. I was seeing that this can be done in ajax, but I don’t have much practice yet and I would also like to know if it is possible to make it work that way. Thanks in advance.

Method of creating the query:

public function criarConsulta ($sql)
{
     $this->conectarBd();
     $this->comandoSql = $sql; 
     // $result= mysqli_query($con,$comandoSql);
     if ($this->result =mysqli_query($this->con,$this->comandoSql)) {
         $this->desconectarBd();
         return $this->result;
     } else {
       echo "Nao foi possivel realizar comando sql";
       die();
       $this->desconectarBd();
     }
} 
  • Post the create codeConsult()

  • <code>public Function createConsult($sql) { $this->conectarBd(); $this->commandSql=$sql; // $result= mysqli_query($con,$commandSql); if($this->result =mysqli_query($this->con,$this->commandSql)) { $this->disconnectBd(); Return $this->result; } Else { echo "Unable to perform sql command"; die(); $this->disconnectBd(); } } </code>

  • Note: In addition to the problem presented, there is also risk of SQL Injection in your code. To avoid risk, treat data entry.

1 answer

2


Using the modal, you should think about front-end first, the back-end part should be thought about later:

HTML:

<div id="status" class="alert"></div>
<table class="table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Título</th>
            <th>Detalhes</th>
            <th>Status</th>
            <th>Ação</th>
        </tr>
    </thead>
    <!-- start: Table Body -->
    <tbody>
        <tr class="btnDelete" data-id="1">
            <td>1</td>
            <td><a href="#">Título x</a></td>
            <td>Blá blá blá</td>
            <td>Ativo</td>
            <td>
                <button class="btn btn-danger btnDelete" href="">Apagar</button>
            </td>
        </tr>
        <tr class="btnDelete" data-id="2">
            <td>2</td>
            <td><a href="#">Título y</a></td>
            <td>Blá blá blá</td>
            <td>Ativo</td>
            <td>
                <button class="btn btn-danger btnDelete" href="">Apagar</button>
            </td>
        </tr>
    </tbody>
</table>
<!--/table-collapse -->
<!-- start: Delete Coupon Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                 <h3 class="modal-title" id="myModalLabel">Exclusão de registro</h3>

            </div>
            <div class="modal-body">
                 <h4> Você gostaria de deletar este item?</h4>

            </div>
            <!--/modal-body-collapse -->
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" id="btnDelteYes" href="#">Sim</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Não</button>
            </div>
            <!--/modal-footer-collapse -->
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

Javascript:

$('button.btnDelete').on('click', function (e) {
    e.preventDefault();
    var id = $(this).closest('tr').data('id');
   //aqui passamos a ID do registro para dentro do modal, atraveś do click do botão...
    $('#myModal').data('id', id).modal('show');
});

$('#btnDelteYes').click(function () {
    var id = $('#myModal').data('id');
    $('[data-id=' + id + ']').remove();
    $('#myModal').modal('hide');
});

Here an example in JSFIDDLE.

Now let’s move the action to the back end, so that the deletion is met in PHP. First we change the method so that it allows to make a post via ajax:

$(function() {
  $('#status').hide();
});
$('#btnDelteYes').click(function () {
    var id = $('#myModal').data('id');
    $.post('detalhesTarefas.php',{acao:'delete',id:id},function(r) { 
       var m = jQuery.parseJSON(r);
       if (m.success) {
        $('[data-id=' + id + ']').remove();
        $('#myModal').modal('hide');
        $('#status').removeClass('alert-danger')
                    .addClass('alert-success')
                    .text(m.msg).fadeIn('slow');
       } else {
        $('#myModal').modal('hide');
        $('#status').removeClass('alert-success')
                    .addClass('alert-danger')
                    .text(m.msg).fadeIn('slow');
       }
          hideMessage();
    }
});

function hideMessage() {
    setTimeout(function() {
        $('#status').hide();
    }, 4000);
}

In php, since you are using everything in a single file, it is important that this code is placed at the beginning of it and that this file does not contain html code along with its output, because JSON should be your only response output, for this I will use the die(), to stop any execution that comes under this action, so that he understands that only in this condition he must be answered, I put a POST entry called "action", which will be who will tell the back end,in which part of your file he will answer the answer. Your php file should receive so:

<?php //primeira linha do arquivo php
if ($_POST) {
    $data = array('success' => '0',
                  'msg' => 'Ocorreu um erro, nada foi excluído!');
        $id = (int) $_POST['id'];
        if ($_POST['acao'] == 'delete' && is_int($id)) {
            $comandoExcluir = "DELETE FROM tbTarefa WHERE idTarefa =" .$id; 
            $resultado = $c ->criarConsulta($comandoExcluir);
            if ($resultado) {
               $data = array('success' => '1',
                             'msg' => 'Registro excluído com sucesso!');
            } 
        }
   echo json_encode($data);
   die();
}
//aqui abaixo virá o resto do seu código, html etc....
?>

Browser other questions tagged

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