0

Is there a way to save multiple selection or checkbox to database table in 1 column and then parse to get it in array ?

I have this screnario:

I have a right permission, and id 1,2,3 and 5 has access to a page.

id,username,password,right
1, admin, 123, 1
2, john, john, 2
3, doe, doe, array(1,2,3)

model:

$insert_member = array(
                'username' => $this->input->post('username'),
                'password' => md5($this->input->post('password')),
                'right' => $this->input->post('right')          
            );
            $insert = $this->db->insert('members', $insert_member);
            return $insert;

Any help is appreciated.

2 Answers 2

3

Use json_encode: Try below:

$right_value   = $this->input->post('right');
$insert_member = array(
            'username' => $this->input->post('username'),
            'password' => md5($this->input->post('password')),
            'right' => json_encode($right_value)
        );
        $insert = $this->db->insert('members', $insert_member);
        return $insert;

Hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice move, so after that, to get on view ? i need to parse it again to json_decode ? as i will need to check if is in array. Thanks
@Dario, yes json_decode will turn it back into an array.
0

For permissions you can use bitwise operators. These allow you to store multiple values in one column by using binary. In a standard int(11) column you can have a number up to 32 bits in binary, or 4,294,967,295 in decimal (unsigned).

What you do is you assign each permission a bit in the column, so for example if you have 3 pages and you want to control access to each page you have the following:

        |  Page 3  |  Page 2  |  Page 1  |  Right (Binary / Decimal)
User 1  |     0    |     0    |     0    |     000 / 0
User 2  |     0    |     0    |     1    |     001 / 1
User 3  |     0    |     1    |     0    |     010 / 2
User 4  |     0    |     1    |     1    |     011 / 3
User 5  |     1    |     0    |     0    |     100 / 4
User 6  |     1    |     0    |     1    |     101 / 5

etc.. You can have any combination, and the binary bits don't interfere with each other.

Then once you load the information back out of the database you can use the bitwise operators to check whether a user has the correct permissions. So to check if a user has permission to access page 2 you would do the following:

// We use 2 here because page 2 is the second bit, which is 2 in decimal
if(($right & 2) == 2) {
    // has access...
} else {
    // doesn't have access...
}

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.