简体   繁体   中英

How to save added data into database with output jason in codeigniter

I have a field that can be multiple when user will add another data. Here's a screenshot

在此处输入图片说明

Here's my html code

<tr>
                <td>経歴(学歴)</td>
                <td>
                    <div id="academic">
                        <select name="c_ac_year">
                            <option value="2019">2019</option>
                            <option value="2018">2018</option>
                            <option value="2017">2017</option>
                        </select>
                        <select name="c_ac_month">
                            <option value="January">January</option>
                            <option value="February">February</option>
                            <option value="March">March</option>
                        </select>
                        <input type="text" id="form-control" name="c_ac_desc">
                    </div>
                    <div id="new_chq"></div>
                    <a href="" class="add">Add</a>
                </td>
            </tr>
            <tr>

When click add, another set of fields will be added. How will i save these data in the database in array form? Can you please help me guys?

Use array names in the html like name="c_ac_year[]"

Then in controller $this->input->post('c_ac_year'); will be an array and you can use indexing to get the other associated fields for that row

You need to use php array[] input in HTML side as like this :

<div id="academic">
   <select name="c_ac_year[]">
      <option value="2019">2019</option>
      <option value="2018">2018</option>
      <option value="2017">2017</option>
  </select>
  <select name="c_ac_month[]">
      <option value="January">January</option>
      <option value="February">February</option>
      <option value="March">March</option>
 </select>
 <input type="text" id="form-control" name="c_ac_desc[]">

In PHP side, You can get value :

if(!empty($_POST))
{
    $years = $_POST['c_ac_year']; //or $this->input->post('c_ac_year');
    $months = $_POST['c_ac_month']; // or $this->input->post('c_ac_month');
    $descs = $_POST['c_ac_desc']; // or $this->input->post('c_ac_desc');
     $response = array();
    foreach($years as $key=> $year)
    {
       $response[$key]['year'] = $year;
       $response[$key]['month'] = $months[$key];
       $response[$key]['desc'] = $descs[$key];
    }
    echo json_encode($response); exit;
}

Output will be :

  [
{
year: "2019",
month: "January",
desc: "value 1",
},
{
year: "2018",
month: "February",
desc: "value 2",
},
{
year: "2017",
month: "March",
desc: "value 3",
},
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM