PHP PDO和DELETE with in()不起作用

时间:2012-03-02 20:08:19

标签: php sql pdo

以下是该类的代码:

    class Delete_Category extends Category {

    private $idchain = array();

    public function __construct($id) {
        parent::__construct();
        $this->check_id($id);
        $this->get_delete_ids($this->id);
        $this->delete_category($this->idchain);
    }

//从数据库中获取所有子ID并将它们存储在数组中

    private function get_delete_ids($id) {
        $this->query = $this->db->prepare("SELECT id FROM `shop_categories` WHERE parent_id = :id");
        $this->query->execute(array("id" => $id));
        while($result = $this->query->fetch(PDO::FETCH_ASSOC)) {
            $this->get_delete_ids($result['id']);
        }
        $this->idchain[]= $id;
    }

//将数组内爆为id字符串并将其抛入查询

    private function delete_category($id_array) {
        $id = implode(",",$id_array);
        try {
            $this->query = $this->db->prepare("DELETE FROM `shop_categories` WHERE id IN (:id)");
            $this->query->execute(array(':id' => $id));
        }
        catch(PDOException $e) {
            // log it{
        }
    }
}

事情是,这总是最终只删除最后一个ID。该查询似乎正在起作用,因为它看起来完全正常,如果我回应它并用$ id替换:id。

//回显的SQL输出字符串:

DELETE FROM `shop_categories` WHERE id IN (11,6)

//如果我手动将其添加到数据库,它按预期工作,所以问题必须在PDO声明的某个地方......任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:4)

您可以使用FIND_IN_SET

DELETE FROM `shop_categories` WHERE FIND_IN_SET(id, :id)"