当前位置: 动力学知识库 > 问答 > 编程问答 >

php - How to remove more rows?

问题描述:

I created a class that extends pdo functionality, in this class I have created a delete function like this:

public function delete($table, $where, $limit = 1)

{

return $this->exec("DELETE FROM $table WHERE $where LIMIT $limit");

}

for use it, simply:

public function deleteData()

{

$id = 13;

$name = "Test";

$where = "`id` = '{$id}' AND name = '{$name}'";

$this->db->delete('wine', $where);

}

but if I want pass more rows to delete I should I do?

网友答案:

Something like this:

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();
}

usage:

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

echo "I just deleted $rowsCount entries";

Please note that this code is not tested.

网友答案:

Write your code as below:-

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");
}

Hope it will help you :)

分享给朋友:
您可能感兴趣的文章:
随机阅读: