CodeIgniter活动记录一次删除多个记录 [英] CodeIgniter Active Record Delete Multiple Records At Once
问题描述
这是我的控制器功能之一。它从名为用户的数据库表中获取所有行,并将其放入数组中。然后,它将通过传递的数组数据加载一个名为 deleteuser的视图。
This is one of my controller functions. It grabs all the rows from a database table called 'users' and puts it into an array. It then loads a view called 'deleteuser' with the array data passed through.
function deleteuser(){
$this->load->model('users');
$employees['staff'] = $this->users->getStaff();
$this->load->view('deleteuser', $employees);
}
在deleteuser视图中,数组生成了一个复选框类型输入。
In the deleteuser view, there's a checkbox type input generated from the array. The form action calls on a function called remove.
<form action="remove" method = "post">
<?php foreach($staff as $row): ?>
<div class="checkbox">
<label>
<input type="checkbox" name="delete[]" value="<?php echo $row->id ?>" />
<?php echo $row->lastName . ", " . $row->firstName; ?>
<br />
</label>
<?php endforeach; ?>
<br />
<br />
<input type="submit" name = "remove" value = "Delete" class = "btn btn-danger btn-lg pull-left" />
</div>
remove函数从输入中获取delete数组,并将其传递给名为deleteUser的模型函数。 / p>
The remove function grabs the delete array from the input and passes it to a model function called deleteUser.
function remove(){
$data = $this->input->post('delete');
$this->users->deleteUser($data);
}
现在这是我遇到麻烦的地方。以下是deleteUser的模型函数,但给了我一个未定义的偏移量:1错误。任何帮助将不胜感激。
Now this is where I'm running into some trouble. Below is the model function for deleteUser, but it's giving me an undefined offset: 1 error. Any help would be appreciated.
function deleteUser($data)
{
if ($data) {
for ($i = 0; $i <= count($data); $i++)
{
$this->db->where('id', $data[$i]);
$this->db->delete('users');
}
}
}
推荐答案
尽管@DamienPirsy的回答在解决您的问题上是正确的,但我还是建议您使用另一种方法。我会一次删除所有记录,而不是循环删除。
Though answer by @DamienPirsy is correct in addressing your problem, I would suggest an alternate approach. I would delete all records at once, rather than in a loop. This will minimize your number of queries against the DB.
function deleteUser($data)
{
if (!empty($data)) {
$this->db->where_in('id', $data);
$this->db->delete('users');
}
}
这篇关于CodeIgniter活动记录一次删除多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!