php/codeigniter-通过数据数组删除基于多个where条件的记录

67up9zun  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(289)

我正在为我的项目使用php/code-igniter,我正在尝试找出处理此查询的最佳方法。
我有一个数组的数据,我想作为我的 WHERE 用于删除记录的子句。

Array
(
    [0] => Array
        (
            [CustomerID] => 8
            [Denomination] => 40
        )

    [1] => Array
        (
            [CustomerID] => 9
            [Denomination] => 425
        )

)

我试着这样做:

public function remove_customers_from_order($formData){
        $this->db
        ->where($formData)
        ->delete("customer_rewards");
    }

有没有比每次循环删除更有效的方法? CustomerID 以及 Denomination 两者都匹配where子句的列名。
期望结果: DELETE FROM customer_rewards WHERE CustomerID = 8 AND Denomination = 40; DELETE FROM customer_rewards WHERE CustomerID = 9 AND Denomination = 425; 错误:
像这样运行时,出现以下错误: Array to string conversion database/DB_query_builder.php

rta7y2nd

rta7y2nd1#

尽管它已经有了一个公认的答案,但在ci中,正确的方法是:

$arrData = [
    [
        'CustomerID' => 8,
        'Denomination' => 40
    ],
    [
        'CustomerID' => 9,
        'Denomination' => 425
    ]
];

foreach($arrData AS $arrItem)
{
    $this->db->or_group_start();
        $this->db->where('CustomerID', $arrItem['CustomerID']);
        $this->db->where('Denomination', $arrItem['Denomination']);
    $this->db->group_end();
}
$this->db->delete('customer_rewards');

在这种情况下,您可以免受sql注入的影响

blmhpbnm

blmhpbnm2#

I think you can use:
foreach($formData as $w){
    $this->db->or_where("(`CustomerID` = '".$w['CustomerID']."' AND `Denomination`='".$w['Denomination'].')",NULL,false);
}
$this->db->delete();
hfwmuf9z

hfwmuf9z3#

此查询效率更高:

DELETE 
  FROM customer_rewards 
 WHERE (CustomerID = 8 AND Denomination = 40)
    OR (CustomerID = 8 AND Denomination = 425);

你能想出如何相应地调整你的循环吗?

相关问题