如何在codeigniter上将多个数组插入一行数据库?

时间:2018-05-31 18:54:16

标签: codeigniter codeigniter-3

很抱歉,如果之前已经提出这个问题,但我一直在寻找,我找不到我要找的东西。

这是我的数据库结构

| ID | collection_ID | valuation | postby_ID | post_datetime |

这是我的查看页面(输入数据)

<form action="insert.php" method="post">

<?php $i = 0; ?>

<?php foreach ($significance as $data): ?>

<input type="text" name="var[<?php echo $i; ?>][]" value="<?php echo $data->category; ?>" >
<select name="var[<?php echo $i; ?>][]">
<option value="0"> 0 </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
</select>
<input type="text" name="var[<?php echo $i; ?>][]">

<?php $i++; ?>

<?php endforeach; ?>

<button type="submit"> Submit </button>
</form>

到目前为止,这是我的控制器

$collectionID = $this->input->get('coll_id'); //get from url

$this->form_validation->set_rules('val[]', 'Some text', 'required', array('required'=>'%s required'));

if ($this->form_validation->run == FALSE)
{
  $data = array(
      'page_title' => 'Some Title',
      'part' => 'input-data',
      'detail' => $this->collection_db->get_collection_data($collectionID),
      'significance' => $this->significance_db->get_significance_list()
  );
  $this->load->view('form-registration', $data);
}
else
{
  $db_data = array(
      'collection_ID' => $collectionID,
      'valuation' => json_encode($this->input->post('val)),
      'post_by' => $this->session->userdata('user_ID'),
      'post_datetime => get_datetime_format() //some helper function
  );
  if ($this->significance_db->save_data($db_data) == TRUE)
  {
     'some function here if TRUE';
  }
  else
  {
     'some function here if FALSE;
  }
}

到目前为止,这是我的模型

function save_data($db_data)
{
   $this->db->insert('table_name', $db_data);
   if ($this->db->affected_rows > 0)
   {
      return TRUE;
   }
   else
   {
      return FALSE;
   }
}

这是我在评估列数据库中的价值,因为foreach循环生成了6个表单字段:

[["variable 1", "1", "description 1"],["variable 2", "0", "description 2"],["variable 3", "3", "description 3"],["variable 4", "3", "description 4"],["variable 5", "2", "description 5"],["variable 6", "0", "description 6"]]

那么,这是结果的一个很好的例子,或者我做错了编码?因为在另一个视图页面中我想在foreach循环中使用json_decode提取结果,如下所示:

Variable : variable 1
Score: 1
Description: description 1

Variable : variable 2
Score: 0
Description: description 2

Variable : variable 3
Score: 3
Description: description 3

Variable : variable 4
Score: 3
Description: description 4

Variable : variable 5
Score: 2
Description: description 5

Variable : variable 6
Score: 0
Description: description 6

另一个问题是:我如何从视图和控制器生成json_encode结果如上所示:

[
   ["variable" => "variable 1", "score" => "1", "description" => "description 1"],
   ["variable" => "variable 2", "score" => "0", "description" => "description 2"],
   [etc...]
]

1 个答案:

答案 0 :(得分:1)

经过这么多试验和错误并搜索了许多资源。最后我来找我自己的解决方案。希望我能用我的代码帮助别人。请随意为此问题添加其他解决方案......

查看输入数据的页面(form-input.php)

<?php echo form_open('#', array('class'=>'form') ); ?>

   <?php 
       $i = 0;
       if ($valuation != NULL):
   ?>

       // Form field will looping through this as many as foreach result
       <?php foreach ($valuation as $value): ?>

           <input type="text" name="variable[<?php echo $x; >?]" value="<?php echo $value->category; ?>" readonly="readonly">
           <select name="score[<?php echo $x; ?>]">
               <option value=""> — Choose Score — </option>
               <option value="0"> 0 </option>
               <option value="1"> 1 </option>
               <option value="2"> 2 </option>
               <option value="3"> 3 </option>
           </select>
           <textarea name="desc[<?php echo $x; ?>]" rows="5" required="required"></textarea>

       <?php
           $x++;
           endforeach;
       ?>

   <?php
        else:
            echo 'No input field generate';
        endif;
   ?>

<?php
    echo form_button(array('name'=>'submit', 'type'=>'submit', 'content'=>'Save') );
    echo form_close();
?>

控制器(Collection.php)

public function save()
{
   // get collection ID from URL
   $collectionID = $this->input->get('coll_id');

   //Form Validation
   $this->form_validation->set_rules('variable[]', 'Variable', 'required', array('required'=>'%s cannot empty'));
   $this->form_validation->set_rules('score[]', 'Score', 'required', array('required'=>'%s cannot empty'));
   $this->form_validation->set_rules('desc[]', 'Description', 'required', array('required'=>'%s cannot empty'));

   if ($this->form_validation->run() == FALSE)
   {
       $data = array(
           'page_title' => 'Add Significance Data for ' . $collectionID,
           'valuation' => $this->significance_db->get_value_list()
       );
       $this->load->view('form-input', $data);
   }
   else
   {
       $count = count($this->input->post('variable'));
       for ($i=0; $i<$count; $i++)
       {
           $json_data[] = array(
               'variable' => $this->input->post('variable')[$i],
               'score' => $this->input->post('score')[$i],
               'description' => $this->input->post('desc')[$i]
           );
       }
       $json_encode_data = json_encode($json_data);

       $db_data = array(
           'collection_ID' => $collectionID,
           'valuation' => $json_encode_data,
           'post_by' => $this->session->userdata('user_ID'),
           'post_datetime' => get_datetime_format()
       );

       if ($this->significance_db->save_data($db_data) == TRUE)
       {
          'some function here if TRUE';
       }
       else
       {
          'some function here if FALSE';
       }
   }
}

型号(significant_db.php)

function save_data($db_data)
{
     $this->db->insert('table_name', $db_data);
     if ($this->db->affected_rows() > 0)
     {
         return TRUE;
     }
     else
     {
         return FALSE;
     }
}

这就是如何将数据插入我的数据库表。它将使用评估列中的数组内容(使用json_encode生成)创建一行。

下面的另一个代码是如何查看此数据。我将展示我的Controller,Model和View的示例。

控制器(也在Collection.php内)

public function show()
{
    //get collection ID from URL
    $collectionID = $this->input->get('coll_id');

    $data = array(
        'page_title' => 'Show Significance Data from ' . $collectionID,
        'significance' => $this->significance_db->get_significance_data($collectionID)
    );
    $this->load->view('view-page', $data);
}

查看Diplaying数据页面(view-page.php)

<?php if ($significance != NULL: ?>

    <div class="row">
        <div class="col-sm-12">
            <div class="card">
                <div class="card-body">

                    <?php foreach ($significance as $value): ?>

                        <?php
                            $data = json_decode($value->valuation); 
                            $count = count($data);
                        ?>

                        <?php for ($i=0; $i<$count; $i++): ?>

                            <ul class="list-inline">
                                <li class="list-inline-item"><?php echo $data[$i]->variable; ?></li>
                                <li class="list-inline-item"><?php echo $data[$i]->score; ?></li>
                                <li class="list-inline-item"><?php echo $data[$i]->description; ?></li>
                            </ul>

                        <?php endfor; ?>

                    <?php endforeach; ?>

                </div>
            </div>
        </div>
    </div>

<?php else: ?>

    <strong> No Data Result. </strong>

<?php endif; ?>

如果您想知道来自 json_decode($ value-&gt;估价)的数据,您可以查看 print_r($ data)或您喜欢的任何脚本显示数组。

最后。希望这可以帮助别人。如果有人有另一种创建相同功能/方法的方法,请随意评论或添加其他方法。