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

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.

var e = document.getElementById( "selectAction" );
if(e.options[ e.selectedIndex ].value == "delete"){
var checked = $('.checkboxProduct:checked');
var id = {
return this.value;
if (id) {
url: "<?php echo $_SERVER['PHP_SELF']; ?>?deleteProduct=true?action=select&id=" + id,
type: "get",
success: function(result){
alert("You have successfully deleted these products!");

Delete function:

public function deleteProduct(){
$product_id = $_GET['id'];
$stmt = $this->conn->prepare("DELETE FROM products WHERE id=('$product_id')");
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)");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download