2016-02-23 79 views
0

我創建了一個類,它擴展PDO的功能,在這個類我創建了一個delete功能是這樣的:如何刪除更多行?

public function delete($table, $where, $limit = 1) 
{ 
    return $this->exec("DELETE FROM $table WHERE $where LIMIT $limit"); 
} 

使用它,簡單地說:

public function deleteData() 
{ 
    $id = 13; 
    $name = "Test"; 

    $where = "`id` = '{$id}' AND name = '{$name}'"; 
    $this->db->delete('wine', $where); 
} 

但是如果我想通過更多的行刪除我應該怎麼做?

+0

你爲什麼限制? –

+0

使用'$ this-> db-> delete('wine',$ where,99);'?或者任何其他數字而不是99. – syck

+0

那麼只需更改限制器? –

回答

1

事情是這樣的:

public function delete($table, array $binds) 
{ 
    $whereStatements = []; 
    foreach ($binds as $field => &$value) { 
     $whereStatements[] = " $field " . (is_array($value) ? "IN (:$field)" : "= :$field"); 
     $value = is_array($value) ? implode(',', $value) : $value; 
    } 

    $where = 'WHERE ' . implode(' AND ', $whereStatements); 

    $stmt = $this->prepare("DELETE FROM $table $where"); 
    $stmt->execute($binds); 

    // return how many records were deleted 
    return $stmt->rowCount(); 
} 

用法:

$rowsCount = $this->db->delete('MY_TABLE', array(
    'id' => array(1, 3, 5, 2, 6, 7), 
    'name' => 'myName' 
)); 

echo "I just deleted $rowsCount entries"; 

請注意這個代碼我沒有測試過。

+0

好的解決方案,但你的代碼只能刪除一行。按照你的例子,如果我有三個id去除代碼,只會刪除一行作爲與where子句匹配的第一個id。也許應該在迭代中插入'execute'? IDK –

+0

它取決於名稱字段... y –

+0

您必須確保您爲所有要刪除的ID設置相同的名稱 –

1

如下編寫代碼: -

public function delete($table, $ids) // No need to set limit 
{ 
    return $this->exec("DELETE FROM $table WHERE id IN($ids)"); 
} 

public function deleteData() 
{ 
    $id1 = 13; 
    $id2 = 14; 
    // Id(PK) is enough for "delete" query 
    $this->db->delete('wine', "$id1,$id2"); 
} 

OR 

public function deleteData() 
{ 
    $idsArr = ['13','14']; 
    $ids = implode(',',$idsArr); 
    // Id(PK) is enough for "delete" query 
    $this->db->delete('wine', "$ids"); 
} 

希望它會幫助你:)