Codeigniter:如何传递多个相同名称的多个输入?

时间:2014-10-27 21:50:31

标签: codeigniter

首先,感谢您宝贵的时间和兴趣 - 非常感谢任何对初学者的投入!

如何插入多个输入(在大多数情况下)多个相同的名称?这是我的代码:

查看:

  //Simplified version, original is a jquery append script
  Passes: <input type="text" name="passes[]">
  Points: <input type="text" name="points[]">
  Passes: <input type="text" name="passes[]">
  Points: <input type="text" name="points[]">

控制器:

//Loops through a table like form for inputting stats
function add_stat() {
   $i = 0;
   foreach ($this->input->post('points') as $points) {
     $dataSet1[$i++] = array (
          'points' => $points
     );
   }

   foreach ($this->input->post('passes') as $passes) {
     $dataSet2[$i++] = array (
           'passes' => $passses
     );
   }
 //Not sure how to pass multiple arrays, or if even possible
 $this->sport_model->insert_stat($dataSet1, $dataSet2);
 }

型号:

//Passing multiple params error out due to "String to Array Conversion"
function insert_stat($dataSet1, $dataSet2) {
    $this->db->insert_batch('table', $dataSet1, $dataSet2);
    return $this->db->insert_id();
}

2 个答案:

答案 0 :(得分:2)

将您的控制器和型号设置为:

控制器:

//Loops through a table like form for inputting stats
function add_stat() {

   $points = $this->input->post('points');
   $passes = $this->input->post('passes'); 
   for($i=0;$i<sizeof($points);$i++)
   {
     $dataSet[$i] = array ('points' => $points[$i], 'passes' => $passses[$i]);
   }
   // $dataSet is an array of array
   $this->sport_model->insert_stat($dataSet);
 }

模型:

function insert_stat($dataSet)
{
    $this->db->insert_batch('table', $dataSet);
    return $this->db->insert_id(); // this will return the id of last item inserted.
}

答案 1 :(得分:0)

首先,insert_batch()只需要两个参数:表名和数据集。

其次,insert_id()不会对批量插入做很多好处,但这并不是一件大事。

我假设您希望积分和通行证在同一记录中,并且您通过JS附加另一组积分/通过输入。

查看:

Passes: <input type="text" name="scores[0][passes]">
Points: <input type="text" name="scores[0][points]">
Passes: <input type="text" name="scores[1][passes]">
Points: <input type="text" name="scores[1][points]">
// etc...

在您的控制器中,您只需使用一个$ dataSet数组并循环遍历$this->input->post('scores')

$ dataSet完成后,您可以批量插入$this->db->insert_batch('table', $dataSet)