PHP - Loop checkboxes and save it to the database

I am having a challenge in PHP and HTML check boxes. Would you help me with this?

Here is my scenario:

I have a User Role module where you will create a user role and then assign what modules that role can access using check boxes. I will attach a screenshot.

What I want to do is to loop through that check box array, and then save each checkbox with a check on it.

Getting all the checked check boxes is fine. I have found a code for that.

Now, I checked a check box for example Delivery module, and then save it, of course it will go to the database. What if I edited the user role, and then unchecked the Delivery module, and saved it, should I delete that row? Because what I understand each checkbox will be saved as a row in the database.

That is the part that I can't imagine how to implement. Would you help me how is the design for that?

Hope I explained myself well. Please let me know if there are unclear parts. Thank you any suggestion, I appreciate it.

Here are some details Hope it would help:

I am using CodeIgniter and MS SQL Server as database.

Here is my code:

          <?php if ($this->session->userdata('portalModules')):
            $portalModules = $this->session->userdata('portalModules');
            $prevGroup = NULL;
            $firstGroup = TRUE;
          ?>
          <?php foreach ($portalModules as $moduleGroup): ?>
            <?php if ($moduleGroup['moduleGroup'] !== $prevGroup): ?>
              <?php if (!$firstGroup): ?>
                </div>
              </div>
            <?php else: ?>
              <?php $firstGroup = FALSE; ?>
              <?php endif ?>

              <?php $prevGroup = $moduleGroup['moduleGroup']; ?>
              <div>
                <div class="form-group"><input type="checkbox" name=""><?php echo $moduleGroup['moduleGroup']; ?></div>
                <div>
                  <?php foreach ($portalModules as $menu): ?>
                    <?php if ($menu['moduleGroup'] == $moduleGroup['moduleGroup']): ?>
                    	<div class="form-group">
                      	<p style="margin-left: 20px;"><input type="checkbox" name=""><?php echo $menu['moduleName']; ?></p>
                    		
                    	</div>
                    <?php endif ?>
                  <?php endforeach ?>
            <?php endif ?>
            
          <?php endforeach ?>

Here is the screenshot of check boxes.

1 answer

  • answered 2018-01-14 06:03 Alex

    I would create a table called permissions consisting of boolean columns or enum columns with options being 1,0 and default option being 0:

    enter image description here

    When the user is created simply add their id to the table and if you set the default to 0 you don't have to worry about handling nulls when you do role checks.

    If an admin unchecks delivery_detailed checkbox then simply change the value from 1 to 0. No deleting rows. Easy.

       /**
         * Check to see if user is allowed for $cpermission
         * 
         * @param string $cpermission
         * @param int $uid User id
         * @return boolean
         */
        function check_user_role($cpermission, $uid) {
            $this->db->select($cpermission);
            $q = $this->db->get_where('user_roles', array('user_id' => $uid));
            if ($q->num_rows() !== 1) {
                return false;
            }
            return intval($q->row()->{$cpermission}) == 1; // is user allowed?
        }
    
        /**
         * Update a user role
         * 
         * @param string $cpermission
         * @param int $val ON/OFF 1,0
         * @param int $uid User id
         * @return boolean
         */
        function update_user_role($cpermission, $val, $uid) {
            $this->populate_user_roles($uid);
            $this->db->where('user_id', $uid);
            return $this->db->update('user_roles', array($cpermission => $val));
        }
    
        /**
         * Adds new user to user role table with all 0 permissions
         * 
         * @param int $uid
         * @return boolean
         */
        function populate_user_roles($uid) {
            $this->db->where('user_id', $uid);
            // user doesn't exist in user role table yet??
            if ($this->db->count_all_results('user_roles') < 1) {
                $columns = $this->db->list_fields('user_roles'); // get all columns
                $data = array_fill_keys($columns, 0); // fill with 0
                unset($data['user_id']); // remove user_id (we don't want [user_id] => 0
                $data['user_id'] = $uid; // add proper user_id to $data array
                return $this->db->insert('user_roles', $data);
            } else {
                return true; // user exists in roles table
            }
        }