4

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

2 Answers 2

12

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');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.