mercredi 27 septembre 2017

JS delete multiple rows from MySQL db with checkbox

I have been trying to figure out how to delete multiple records from MySQL with checkbox and JavaScript.

At this moment I have got working script, that deletes only one record from my db (latest id).

For each product I got checkbox

<input class="checkboxProduct" type="checkbox" name="deleteProduct" value="<?php echo $product['id'];?>">

I have a button and JS form (working - It gets all needed id, and I can display them, but can't delete.

<script>
$(function(){
    var e = document.getElementById( "selectAction" );

    $("#btn-action").click(function(){
        if(e.options[ e.selectedIndex ].value == "delete"){
            var checked = $('.checkboxProduct:checked');
            var id = checked.map(function() {
                return this.value;
            }).get().join(",");
            if (id) {
                checked.closest(".product").remove();
                $.ajax(
                    { url: "<?php echo $_SERVER['PHP_SELF']; ?>?deleteProduct=true?action=select&id=" + id,
                      type: "get",
                      success: function(result){
                          alert("You have successfully deleted these products!");
                      }
                    });
            }
        }
    });
});
</script>

Delete function:

public function deleteProduct(){
    try{

        $product_id = $_GET['id'];

        $stmt = $this->conn->prepare("DELETE FROM products WHERE id=('$product_id')");
        $stmt->execute();

    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}




Aucun commentaire:

Enregistrer un commentaire