PHP ask for confirmation before deleting

0

Hi

In a course I'm doing the person did not teach how to delete a record in the first bd 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 question now how do I put the delete message in the else, and also the code DELETE FROM cadastro_clientes WHERE id='$id';

Thank you

    
asked by anonymous 07.08.2016 / 17:12

4 answers

3

Suggestion 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 safety and technical methods. However, I recommend studying the business model and the basics about programming logic and the tools in use. First analyze the business model, if it is really good what it is doing (ex: delete client permanently)

    
07.08.2016 / 18:19
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>
    
07.08.2016 / 17:43
2

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

</script>";

is wrong and would cause a misinterpretation in the code. You had to have the quotation mark before the first byte '<' : "</script>" , and anyway it would cause an interpretation error since there is no statement that needs a string (if it was in JavaScript, would be different, "</script>" would be returned in the console, or if it was equal to "use strict" would go to strict mode, or ignored; edit : in PHP the string is ignored). Use echo to play a string in HTML.

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

confirm is global, that is, it is located in object window . When calling this function -_- the page is locked while the user does not confirm (does not respond) the confirmation box that was opened with the confirm function itself, and once it is confirmed it returns true if the user response was "Yes", or false if the answer was "Cancel", or something like that. Then with this function we can make a condition type 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 reply "yes" to the confirmation box and to have something removed from a database table. You can not do this directly from JavaScript, so you'll have to use AJAX, which will run the file beside the server (the * .php file). It will greatly magnify the answer if I explain about it, but I leave the question answered link 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 it within 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 -. -, there is in fact the method POST plus GET . I'm not going to explain that much because the question is a bit 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
}
    
07.08.2016 / 17:56
0

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

onclick="return confirm('Tem certeza que deseja editar este registro?')"
    
14.04.2018 / 20:06