phpcodeignitercodeigniter-3

How to insert multiple value data in codeigniter


In my select option I have value with two numbers Example value="163, 162"

I have a model function where can insert the first value number which would be category id 163

Var Dump

array(2) { [0]=> string(3) "163" [1]=> string(4) " 162" }

Question: I need to add parent_id = " . $this->db->escape($category['parent_id']) . " but not sure how to get the second value number and set it as the parent_id = " . $this->db->escape($category['parent_id']) . " parent id would be example 162

Model Function

public function page_update($page_id, $data) {
    $this->db->query("DELETE FROM " . $this->db->dbprefix . "page_to_category WHERE page_id = '" . (int)$page_id . "'");

    if (isset($data['categories'])) {
        foreach ($data['categories'] as $category) {

            //$data_sample = explode(',', $category['category_id']);
            //var_dump($data_sample);
            //exit;

            $this->db->query("INSERT INTO " . $this->db->dbprefix . "page_to_category SET 
            page_id = '" . (int)$page_id . "', 
            category_id = " .  $this->db->escape($category['category_id']) . "
            ");
        }
    }
}

View

<div class="form-group">
    <label class="col-sm-2">Category</label>
    <div class="col-sm-10">
        <select class="form-control" name="categories[1][category_id]">
            <option value="0">-- No Category Required --</option>
            <?php foreach ($categories as $category) {?>
            <?php if ($category['category_id'] == $category_id) {?>
            <option value="<?php echo $category['category_id'];?>, <?php echo $category['parent_id'];?>" selected="selected">
            <?php echo $category['name'];?></option>
            <?php } else { ?>
            <option value="<?php echo $category['category_id'];?>, <?php echo $category['parent_id'];?>"><?php echo $category['name'];?></option>
            <?php }?>
            <?php }?>
        </select>
    </div>
</div>

Solution

  • The answer would be something like this:

    public function page_update($page_id, $data) {
        $this->db->query("DELETE FROM " . $this->db->dbprefix . "page_to_category WHERE page_id = '" . (int)$page_id . "'");
    
        if (isset($data['categories'])) {
            foreach ($data['categories'] as $category) {
    
                $data_sample = array_map("trim",explode(',', $category['category_id']));
    //Here $data_sample[0] will always be your category id and $data_sample[1] will be your parent id
    
    
                $this->db->query("INSERT INTO " . $this->db->dbprefix . "page_to_category SET 
                page_id = '" . (int)$page_id . "', 
                category_id = " .  $this->db->escape($data_sample[0]) . "
                ");
            }
        }
    }
    

    Here $data_sample[0] will always be your category id and $data_sample[1] will be your parent id