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");
}
CodePudding user response:
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.
CodePudding user response:
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.