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");
}
2
  • 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 Commented Feb 9, 2022 at 1: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 Commented Feb 9, 2022 at 1:45

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Good job there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.