如何使用数据表在数据库中插入多个表单
问题描述:
我试图用数据表提交多个表单。用户必须选择输入行数,在其中他可以提交一些信息 - 当你在db中插入行时,它就像Phpmyadmin一样。输入行的名称是相同的。我用循环显示许多行。但以这种方式与嵌套的foreach,当我提交两行信息,在数据库中有8行。怎么做? 这是我的观点:如何使用数据表在数据库中插入多个表单
echo form_open('admin/add_questions/');
?>
<table id='example'>
\t \t <thead>
\t <tr><th>Question</th><th>Code</th><th>Group</th><th>Is_reverse</th></tr>
</thead>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
<tbody>
<?php \t for($i=0; $i<=20; $i++) {
\t ?>
\t \t <tr>
\t \t <td>
\t \t \t <input type="text" name="question[]" id="add_question_table" />
\t \t </td><td>
\t \t \t <input type="text" name="code[]" id="add_question_table" />
\t \t </td><td>
\t \t \t <input type="text" name="group[]" id="add_question_table" />
\t \t </td><td>
\t \t \t <input type="text" name="is_reverse[]" id="add_question_table" />
\t \t </td></tr>
\t \t <?php
\t }
\t \t ?>
</tbody>
</table>
我的型号是:
<?php
class Admin_model extends CI_model {
\t public function __construct() {
parent:: __construct();
$this->load->database();
$this->load->library('session');
}
public function add_questions() {
$date = new DateTime("now");
foreach($this->input->post('question') as $v) {
foreach($this->input->post('code') as $f) {
foreach($this->input->post('group') as $val) {
\t $data = array(
'question'=>$v ,
'code'=>$f,
'survey_id'=>$this->uri->segment(3),
'group_id'=>$val,
'created_at'=>$date->format('Y-m-d H:i:s')
);
$this->db->insert('survey_questions',$data);
}
}
}
什么是做到这一点的呢? :)
答
嗨,从我的角度来看,它最好把$ _POST作为参数传递给你的add_questions()模型方法。你可以试试下面的办法:)
//controller code
$this->admin_model->add_questions($_POST);
//model code
function add_questions($data=array())
{
if(count($data) > 0)
{
$date = new DateTime("now");
for($i=0;$i<count($data['question']);$i++){
$insert = array();
$insert['question'] = $data['question'][$i];
$insert['code'] = $data['code'][$i];
$insert['survey_id'] = $data['survey_id'][$i];
$insert['group_id'] = $data['group_id'][$i];
$insert['created_at'] = $date->format('Y-m-d H:i:s');
$this->db->insert('survey_questions',$insert);
}
}
}
+0
非常感谢!现在完美了! :) :) – 2015-04-02 10:08:44
这将是有益的,如果你发布的控制器代码。 – Tpojka 2015-04-02 09:11:28