我创建了一个扩展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 :(得分: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");
}
希望它会对你有所帮助:)。
答案 1 :(得分: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";
请注意,此代码未经过测试。