Doubt about button / button

-1

I'm doing a comment system, in list form. In each of the lines of the list there is a button of type <button> , each with a different name.

And my question is how to do the following if-else syntax in PHP:

If (o "< button >< /button >" de nome $idcomentario for clicado){***

    $comando = $PDO->prepare("DELETE comentario FROM comentarios WHERE 
    idcomentario = :idcomentario");

    $comando->bindValue(':idcomentario', $idcomentario);
    $comando->execute();    

}else{
    //nada acontece...
}

That is, when the button is clicked, the comment whose "id" corresponds to the button name is deleted from the database.

If you can not do it in PHP, how would you look at JavaScript? Remembering that I would have to perform a BD operation.

    
asked by anonymous 21.09.2018 / 21:10

1 answer

1

In the way that you want to do I do not consider it a good practice, you should not run functionality in view , this is the responsibility of controller. Then you can do it as follows, in your comments view loop you'll put some unique information to identify the comment.

<ul>
<?php foreach ( $comments as $comment ) ?>
    <li>
       <button class="btn-remove" data-id="<?php echo $comment->id ?>">Excluir</button>  // Esse data-id será o campo do qual vamos pegar o ID do comentário
    <li>
<?php endforeach; ?>
</ul>

Then you will create a ajax to run at the time of that button.

$('.btn-remove').click(function(){
    var id = $(this).data('id');
    $.ajax({
        url: url, // URL da rota onde você vai executar no PHP
        data: { comment_id: id },
        datatype: "json",
        type: "POST",
        success: function (data) {
            // Aqui você vai tratar o retorno da sua função em PHP
        }
    });
});

In your PHP file you will create the function to remove the selected comment.

// Antes de remover o comentário aconselho você fazer algumas validações
// Como por exemplo se o comentário já foi removido e etc.
function removeComment( $id ) {
    $comando = $PDO->prepare("DELETE comentario FROM comentarios WHERE idcomentario = :idcomentario");

    $comando->bindValue(':idcomentario', $id);
    $comando->execute();   

    return true; // Dependendo da sua validação retorne *true* ou *false* 
}

The examples above are just to illustrate the way you should do, so copying and pasting the code will not solve your problem.

    
21.09.2018 / 21:54