Question about <button></button>

Asked

Viewed 58 times

-1

I am making a system of comments, in the form of a list. In each of the lines in the list there is a button of the type <button>, each with a different name.

And my question is how to make the following syntax of if-lse 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 you click the button, the comment whose "id" matches the name of the button is deleted from the database.

If you can’t do it in PHP, how would it look in Javascript? Remembering that I would have to perform a BD operation.

1 answer

1


The way you want to do I do not consider it a good practice, you should not run the functionality on view, that is the responsibility of controller. Then you can do as follows, in your comments display loop you will 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 be executed at the time of click 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 file PHP 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 above examples are only to illustrate the way you should do, so copying and pasting the code will not solve your problem.

  • I tested in the browser and gave that the $ of $('.btn-remove') is not set...

  • Friend, what would be this comment_id???

  • comment_id is the primary key of the comments entity in your database. About the previous comment, I talked about not just copying and pasting the code, the examples are only for you to base on the idea and not copy and paste to work.

  • 1

    Ok, actually the cipher error was because it had not imported the jquery library

Browser other questions tagged

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