Crelix Crelix - 3 years ago 196
Javascript Question

JavaScript 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();
}
}

Answer Source

You need to use IN to match against a list, not =. And you can't put all the IDs into a single string, they need to be separate items in the literal list.

You should use a parametrized statement to prevent SQL injection.

$product_id = explode(',', $_GET['id']);
// Create a set of ?, ?, ?, ... placeholders the same length as the product ID array
$placeholders = implode(', ', array_fill(0, count($product_id), '?'));
$stmt = $this->conn->prepare("DELETE FROM products WHERE id IN ($placeholders)");
$stmt->execute($product_id);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download