0

I'm trying to handle a query to delete multiple items with checkboxes. I'm using react for my frontend and php for my backend.

My frontend sends the payload form data like this : P.S My Primary Key is the SKU.

sku: DVD0004
sku: DVD0005

I need to combine these values into 1 bracket like this (DVD0004,DVD0005) in order to put them in my query which is

My API

    public function deleteProduct($prdt_sku)
    {
        try {
            $this->db->query("DELETE FROM products WHERE product_sku = :sku");
            $this->db->bind(":sku", $prdt_sku);

            if ($this->db->execute()) {
                return true;
            } else {
                return false;
            }
        } catch (\Throwable) {
            header("HTTP/1.1 406 Error deleting product from database");
        }
    }

*My actual form destination *

$response = array();

if (isset($_POST['sku'])) {

    $sku = $_POST['sku'];

    $result = $api->deleteProduct($sku);

    if ($result) {
        header("HTTP/1.1 200 OK");
        header("Location: http://localhost:3000/");
        exit();
    } else {
        header("HTTP/1.1 406 Error deleting product");
    }
} else {
    header("HTTP/1.1 499 Required parameters missing");
}
Metwesh
  • 87
  • 1
  • 7
  • 1
    You can do `$sku = $_POST['sku']; foreach($sku as $Deletables){$result = $api->deleteProduct($Deletables);}` it will loop and delete one sku at a time – stillKonfuzed Feb 09 '22 at 01:01
  • It worked, just needed to turn all the SKUs into an array on the front end checkboxes using ```name="sku[]"``` Post this as an answer & I will upvote it – Metwesh Feb 09 '22 at 01:45

2 Answers2

3

To avoid running multiple delete queries, you can use WHERE IN (a, b, c) instead of deleting one record at a time. See this question for details.

BrianT
  • 169
  • 7
1

On the frontend I turned the multiple SKUs into an array using name="sku[]" & on the backend with the help of https://stackoverflow.com/users/9437124/stillkonfuzed by putting the database query into a foreach loop using

$sku = $_POST['sku']; 
foreach($sku as $Deletables){
  $result = $api->deleteProduct($Deletables);
}

It was fixed.

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Metwesh
  • 87
  • 1
  • 7