0

I have a MySQL Table, related to Codeigniter project that is used to maintain the details of files as follows (tbl_documents) :

+-----+---------+-------+------------+-----------+--------+---------+--------+
| id  | file_no | name  | subject_id | folder_no | row_no | rack_no | status |
+-----+---------+-------+------------+-----------+--------+---------+--------+
| 100 | GSP/01  | Test  |          1 |         1 |      1 |       2 |      1 |
| 101 | GSP/02  | Test1 |          2 |         2 |      1 |       3 |      1 |
| 102 | GSP/03  | Test2 |          1 |         2 |      1 |       3 |      1 |
| 103 | GSP/04  | Test3 |          3 |         2 |      2 |       1 |      1 |
| 104 | GSP/05  | Test4 |          4 |         1 |      1 |       1 |      1 |
+-----+---------+-------+------------+-----------+--------+---------+--------+

subject_id is referenced from the following table (tbl_subjects) :

+------------+--------------+--------+
| subject_id | subject_name | status |
+------------+--------------+--------+
|          1 | A/01         |      1 |
|          2 | A/02         |      1 |
|          3 | A/03         |      1 |
|          4 | B/01         |      1 |
|          5 | B/02         |      1 |
|          6 | C/01         |      1 |
+------------+--------------+--------+

insert, update & delete records are working fine. If I edit record using an existing subject_id in the tbl_subject, the functionality is working properly. But I want to edit a record in the tbl_documents table, while inserting new subject to the tbl_subject table, the functionality is not working (My Requirement). My question is mainly aim to subject_id (s). I used the following lines in my controller.

Controller

public function store($id = null)
    {
    $this->form_validation->set_rules('name', "File/Document Name", 'required');  
    if ($this->form_validation->run()) {
        $subject_id = $this->input->post('subject_id');         
        $sub_data = []; 
        
            $sub_data = array(
               'subject_name' => $subject_id,
               'status' => 1                      
                ); 
            $data = array(
                'file_no' => $this->input->post('file_no'),
                'name' => $this->input->post('file_name'),
                'subject_id' => $this->input->post('subject_id'),                
                'folder_no' => $this->input->post('folder_no'),
                'rack_no' => $this->input->post('rack_no'),
                'row_no' => $this->input->post('row_no'),                
                'status' => 1
            );
     }
if ($this->form_validation->run() && $this->documents_model->save($data, $id, $sub_data)) {
            if ($id)
                $message = 'File/ Document Details have been Updated successfully..!!';
            else
                $message = 'File/ Document details have been saved successfully..!!';
            $this->session->set_flashdata('message', $message);
            redirect('documents');
        } else {
            redirect('documents');
        }
    }

Documents_model

public function save($item, $id, $sub_data = [])
{
     $this->db->trans_start();
     if (!empty($sub_data)) {
            $this->db->insert('tbl_subjects', $sub_data);
            $data['subject_id'] = $this->db->insert_id();
        }       
        if ($id) {          
            $this->db->update('tbl_documents', $item, array('id' => $id));
        } else {
            $this->db->insert('tbl_documents', $item);  
        }
        $this->db->trans_complete();
        return $this->db->trans_status();
}

Subject Part of View

<div class="form-group">
     <label for="subject_id">New Subject</label>
         <div class="input-group">
              <select class="form-control select2" name="subject_id" id="subject_id" style="width: 100%">
                    <option value=""> Select a New Subject</option>
                        <?php                       
                        $id = !empty($subjects) ? $subjects->subject_id : '';
                        foreach ($subjects as $sub) {
                            $selected = "";
                            if ($id == $sub->subject_id)
                                $selected = "selected";
                            echo "<option value= '$sub->subject_id' $selected>$sub- 
                        >subject_name</option>";
                        }
                        ?>
                    </select>
                    
<span class="input-group-addon x" aria-describedby="sizing-addon2"
      style="padding: 2px 4px !important;"> <a style="cursor: pointer" id="add-subject"
            title="Add New Subject"><i style="color: #337ab7 !important;" class="fa fa-2x fa-plus- 
            circle"></i></a>
            </span> 
</div>                      
</div>

<script type="text/javascript">
    $(document).on('click', '#add-subject', function (e) {
        e.preventDefault();
        bootbox.prompt("Enter New Subject", function (result) {
            if (result !== null && result !== '') {
                $('#subject_id').append('<option>' + result + '</option>')
                    .val(result);
                $("#subject_id").val(result).trigger("change");
            }

        });

    });
    
</script>
MCIT Trends
  • 275
  • 1
  • 9
  • Can you please explain more detailed what you want to achieve. Right now I read you want to *edit a record in the tbl_documents table* (does that mean update or insert?) and *while inserting new subject to the tbl_subject table* (which data do you want to insert, how are the 2 tables related?) thanks for more info on that. – Vickel Aug 16 '20 at 16:02
  • @ Vickel. Yes. You are correct. The function should be worked both update & insert in the tbl_documents. But the inserting subjects to tbl_subjects should be performed only inserting new subjects using plus mark in the view. – MCIT Trends Aug 16 '20 at 16:11
  • you can set a table column index as unique, and then use a `"insert into, on duplicate key update"` query, check e.g.: https://stackoverflow.com/questions/30569666/update-if-exists-else-insert-in-sql and many more examples if you search ? ON DUPLICATE KEY' – Vickel Aug 16 '20 at 16:18
  • @ Vickel. No. the error is in the following block of code in the model. if (!empty($sub_data)) { $this->db->insert('tbl_subjects', $sub_data); $data['subject_id'] = $this->db->insert_id(); } – MCIT Trends Aug 16 '20 at 16:22
  • 1
    why use php if and else, when you can do the whole thing with one mysql query, the `on duplicate key` is the correct way to approach this. – Vickel Aug 16 '20 at 16:27
  • @ Vickel. Your suggestion is ok for tbl_documents. But what about for tbl_subjects ? – MCIT Trends Aug 16 '20 at 16:43

0 Answers0