CodeIgniter Active Record Delete Multiple Records At Once

不想你离开。 提交于 2020-06-16 02:37:50

问题


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

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>

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

}

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

回答1:


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



回答2:


Remove the equal = sign, should be

for ($i = 0; $i<count($data); $i++) 

you're fetching 1 element out of bounds. i.e, if count($data) is 4, you're looping: 0 1 2 3 4 ("count minor or equal to 4"), which is five elements indeed :)



来源:https://stackoverflow.com/questions/26810609/codeigniter-active-record-delete-multiple-records-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!