Home > database >  Get value in dropdown, Codeigniter
Get value in dropdown, Codeigniter

Time:05-14

I want to edit/update the value of an item but I can't get its value from database. I have something like this in my database

Products table
   -id
   -category_id
   -sub_category_id
   -name
Category table
   -id
   -category
Sub Category table
   -id
   -sub_category

In my form, I have something like this. What should I do if the category_id in my products table exist, it should display its corresponding category name? I tried to use something like this in my form

<div >
    <label for="" > Category</label>
        <select name="category_id" id="category" >
            <option value="">Select Category</option>
               <?php
                   foreach ($category as $row) {
                       echo '<option value="' . isset($products->category_id) ? $row['id'] : ''  . '">' . $row['category'] . '</option>';
                 }
               ?>
      </select>
   </div>
<div >
 <label for="" >Sub Category</label>
      <select name="sub_category_id" id="subcategory" >
<option value="<?php isset($products->sub_category_id) ? $products->sub_category_id : ''; ?>">Select Sub Category</option>
</select>
</div>

Here's my controller

 public function edit_product($id)
{
    $data['title'] = 'Update Product';

    $this->load->view('../admin/template/admin_header');
    $products = new Admin_model;
    $data['category'] = $this->Admin_model->category();
    $data['products'] = $products->edit_product($id);
    $this->load->view('../admin/template/admin_topnav');
    $this->load->view('../admin/template/admin_sidebar');
    $this->load->view('../admin/products/manage_product', $data);
    $this->load->view('../admin/template/admin_footer');
}

And my model

public function edit_product($id)
{
    $query = $this->db->get_where("products", array('id' => $id));
    return $query->row();
}

public function category()
{
    $response = array();

    $this->search(array(), 'date_created');

    $this->db->select('*');
    $query = $this->db->get('categories');
    $response = $query->result_array();

    return $response;
}

CodePudding user response:

For each category that you're printing in the select box, check if the category id is the same as the product's category id. If they're the same, add 'selected' to the option:

           <?php
               foreach ($category as $row) {
                   echo '<option value="' . $row['id'] . '"';
                   if ($row['id'] == $products->category_id) {
                        echo ' selected'
                   }
                   echo '>' . $row['category'] . '</option>';
             }
           ?>
           

This selects the product's category name.

  • Related