PHP ask for confirmation before deleting

Asked

Viewed 5,899 times

0

Hi

In a course I’m doing the person did not teach how to delete a record in the first comics ask for a confirmation before deleting. So I made this code.

<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
include_once("../../controle/conexao.php");
include_once("../../controle/seguranca.php");
$id = $_GET['id'];

$consulta = "SELECT * FROM ordem_producao WHERE op_clientes = '$id'";
$resultado_consulta = mysqli_query($conn, $consulta);   
$row = mysqli_fetch_assoc($resultado_consulta);

if(mysqli_affected_rows($conn) != 0){
        echo "<META HTTP-EQUIV=REFRESH CONTENT = '0;URL=../../paginas/layout/dashboard.php?link=12'>
            <script type=\"text/javascript\">
                alert(\"Este cliente não pode ser apagado, pois existem transações.\");
            </script>"; 
    }else{              
    }?>

My doubt now how I put the message to delete on LSE, and also the code DELETE FROM cadastro_clientes WHERE id='$id';

Thank you

  • You want the user to confirm to delete something in the database through the block else?

4 answers

5

This type of validation is usually done on the client side. You can do it with Javascript in the onclick event of your html tag, which calls your method.

Ex.

<a href="deletar?id=1" onclick="return confirm('Tem certeza que deseja deletar este registro?')">Excluir</a>
  • And if javascript, for any reason, is disabled in the browser?

  • Well this is very unusual, since 99% of the pages are done with JS, but you can do a recursive method, which calls the same page with a new parameter and put a validation before this delete method. Ex. if (isset($_GET['confirmed])){ // your delete method}

  • Thank you I’ll test here.

  • 2

    Rarely is a "normal" user with JS turned off. Just add-on (but out of question!), it is ideal to include a token/código security next to id, for example: deletar?id=1&token=123456789. Such code can be generated pseudo-randomly on the server. Then, when the user confirms, the server checks whether both codes match (both the one sent by the client, and the one stored in Session by the server). This prevents someone from sending you a link (mostly shortened) to delete something. Why send yourself deletar?id=1 there will be no token. ;)

  • @Inkeliz Good tip, man

3


Suggestion of how to do

if (mysqli_affected_rows($conn) != 0) {
        echo "<META HTTP-EQUIV=REFRESH CONTENT = '0;URL=../../paginas/layout/dashboard.php?link=12'>
            <script type=\"text/javascript\">
                alert(\"Este cliente não pode ser apagado, pois existem transações.\");
            </script>"; 
}else{

        $sql = "DELETE FROM op_clientes WHERE id = '$id'";
        $executa = mysqli_query($conn, $sql); 

    ?>
        <script type="text/javascript">
        alert(“o cliente foi excluído”);
        </script>
<?php
}
?>

note: I refrain from commenting on logistics or security and technical methods. However, I recommend studying the business model and the basics of programming logic and the tools in use. First analyze the business model, if it’s really good what you’re doing (e.g., delete client permanently)

  • I agree with the "note". I believe NEVER to delete anything, if not to save space or compress (i.e., otherwise store the same data), including removing the permission. The "ideal" for me is to create a datum for Status, at least boolean. In the form that 1 would be an active user (default) and 0 a user/data that is "deleted". This can also be better for backups and monitoring and accidental (or related) deletions. This is what I usually use (not being boolean), there must be other solutions, even better. But, really the fact is deleting the data directly is important to be noticed.

  • Got it, thank you very much for the explanation

2

First of all I want to say that this line in the block of else

</script>";

is wrong and would cause an interpretation error in the code. You had to have put the quote before the first byte '<': "</script>", and would otherwise cause an interpretation error since there is no statement that needs a string (if it were in Javascript, it would be different, "</script>" would be returned on the console, or if it were equal to "use strict" would go the strict way, or ignored; Edit: in PHP the string is ignored). Use echo to play a string in HTML.


I understood that you want to display a confirmation box to delete something in the database. In this example I will show the function confirm javascript.

confirm is global, ie is located in the object window. When calling this function -_- the page is locked while the user does not confirm (does not reply) the confirmation box that was opened with the function itself confirm, and once confirmed returns true whether the user’s response was "Yes", or false if the answer was "Cancel", or something like that. Then with this function we can make a condition like if(confirm("Quer me responder?")) alert("Então você quer me responder"); else confirm(":(");, or confirm("Quer me responder?") && alert("Uau! Você é incrível! :D Herói!").

The goal is for the user to answer "yes" to the confirmation box and for something to be removed from a database table. You cannot do this directly from Javascript, so you will have to use AJAX, which will run the file next to the server (the *.php file). It will greatly amplify the answer if I explain about it, but I leave the link of a question answered that will help you.

And another thing, I see no point in using PHP to build the HTML page and run Javascript. To answer your question, try putting this inside your else.

echo '<script>
    if(confirm("Deseja remover o *?")) {
        var xhr = new XMLHttpRequest;
        xhr.get("GET", "delete.php?id='. $id .'", true);

        xhr.onreadystatechange = function() {
            if(this.readyState === 4) {
                if(this.status === 200) {
                    alert("Deletado.");
                }else{
                    /* Erro ao requisicionar o arquivo *.php */
                }
            }
        };

        xhr.send();
    }
</script>';

And the delete.php file should have an id specified in the URL -. -, actually there is the method POST besides the GET. I’m not going to explain that much because the question is a little broad, but let’s see if you understand:

<?php

// se o id foi declarado no URL, e.g: *url*/?id=num
if(isset($_GET['id'])) {
    // pega e converte o id no url para número (caso vier como uma string, mas impossível de acontecer, eu creio)
    $id = intval($_GET['id']);

    // obs: isso é inseguro se você não
    //detectar o usuário que está deletando algo do db
    // remova algo do db usando $id
}
  • Thank you very much for the explanation.

  • Hard that in these lessons I learned the teacher did not use ajax. use it now will confuse me more than help me.

  • @Junior Understand. AJAX is most used to not have the need to reload the page.

0

I use the confirmation via javascript, but in this case only to confirm the action, does not make checks. Anyway it is essential to send accidental actions.

onclick="return confirm('Tem certeza que deseja editar este registro?')"

Browser other questions tagged

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