0

This question is very similar to Delete multiple rows with PDO and checkboxes using prepared statements?, but none of the answers suggested there worked in my case.

I have the product list page, where all the products from a database are listed using PHP class method. Each product has a checkbox, and in <HTML> part, this whole thing is wrapped in a <form> which submits on the click of a button. Then, in the end of the main page I call another PHP method from another class to delete the check-boxed products, based on one of the answers given in the similar question I mentioned above:

class MassDelete
{
    public function deleteSelected()
    {
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            print_r($_POST);
        }
        $skus = array();
        foreach ($_POST['delete'] as $pval) {
            $skus[] = strval($pval);
        }
        $skus = implode(',', $skus);
        $pdo = new Database;
        $conn = $pdo->getConnection();
        $query = $conn->prepare("DELETE FROM `products` WHERE `sku` IN ( $skus )");
        $query->execute();
    }
}

The problem is - it doesn't work. By using print_r($_POST); I see that $_POST gets the values I need (SKUs) from the respective products, so the problem shouldn't lie within the <HTML> part or the class that is responsible for displaying the products on this page.

Therefore, I believe it is this delete class and PDO statement to blame. Any suggestions on what to do/where to look?

  • If the `sku` values are not integers, they will need to be quoted. You would be better off using a properly prepared statement ([manual](https://www.php.net/manual/en/pdo.prepare.php)). As it stands you use `->prepare`, but you're actually just interpolating the variables into the query string. You prepare a query template with `:placeholders` and you pass the actual values into `->execute()`. – Markus AO Dec 16 '21 at 12:40
  • 1
    P.S. Rather than believing, crank up your error reporting and actually know what fails. – Markus AO Dec 16 '21 at 12:42
  • First, you must provide the actual array with data, not a verbatim description of it. Second, the foreach loop is totally useless, the $skus array is 100% equal to $_POST['delete'] array. Finally, this "prepared" statement prepares nothing, leaving SQL open to every single injection in the world. – Your Common Sense Dec 16 '21 at 13:26
  • Thank you both, guys. I fixed the `prepare` statement, and after a few extra steps everything worked. – Danylo Herasymov Dec 16 '21 at 15:49

0 Answers0