将从表单检索到的数组数据存储到数据库
Posted
技术标签:
【中文标题】将从表单检索到的数组数据存储到数据库【英文标题】:store array data retrieved from forms to database 【发布时间】:2016-10-13 15:30:56 【问题描述】:我有一个表格。并且有添加按钮可以根据需要添加更多表单。 工作演示在 JSFiddle 中。 https://jsfiddle.net/szn0007/eanhpLkg/
我的 php 代码是:
$data['client_name'] = $_POST['client_name'];
$data['address'] = $_POST['address'];
$data['fiber_length'] = $_POST['fiber_length'];
$data['phone_number'] = $_POST['phone_number'];
$data['package'] = $_POST['package'];
$data['result'] = $_POST['result'];
$data['remarks'] = $_POST['remarks'];
foreach($data['client_name'] as $c )
$sql = "INSERT INTO ct_staff_activity_ftth(client_name) VALUE('$c') ";
$this->db->query($sql);
如何一次插入所有输入的数据。
【问题讨论】:
【参考方案1】:使用这个
for($i=0; $i<count($_POST['client_name']); $i++)
$client_name = $_POST['client_name'];
$address = $_POST['address'];
$fiber_length = $_POST['fiber_length'];
$phone_number = $_POST['phone_number'];
$package = $_POST['package'];
$result = $_POST['result'];
$remarks = $_POST['remarks'];
$data = array(
'cleint_name' => $client_name,
'address' => $address,
'fiber_length' => $fiber_length,
'phone_number' => $phone_number,
'package' => $package,
'result' => $result,
'remarks' => $remarks,
);
$q = $this->user_model->add_record($data);
【讨论】:
【参考方案2】:第一次创建一个新模型调用 Generic_model.php 然后粘贴这段代码 类 Generic_model 扩展 CI_Model
public function insertData($tablename, $data_arr=array())
$ret = 0;
try
//insert data
$this->db->insert($tablename, $data_arr);
//create return as last inserted record id
$ret = $this->db->insert_id() + 0;
//return $ret;
return true;
catch (Exception $err)
//return error
return $err->getMessage();
最后进入你的控制器 在相关函数中调用它为
//初始化模型
$this->load->model('Generic_model', '', TRUE);
$recid=$this->load->model->Generic_model->insertData('table_name',$data_array);
如果你 echo $rec_id 你可以看到最后插入的记录 id
只有这个
【讨论】:
【参考方案3】:使用以下语句构建语句,而不是单次写入:
$string = "";
foreach($data['client_name'] as $key => $c)
$string .= "(" . $c . "," . $data['address'][$key] . "," . $data['fiber_length'][$key] . "," . $data['phone_number'][$key] . "," . $data['package'][$key] . "," . $data['result'][$key] . "," . $data['remarks'][$key] . "),";
$sql = "INSERT INTO ct_staff_activity_ftth(client_name, address, fiber_length, phone_number, package, result, remarks) VALUES " . rtrim($string, ",");
$this->db->query($sql);
【讨论】:
@gerrard 我想存储所有表单值。即客户端名称、地址、光纤长度等.....以上是关于将从表单检索到的数组数据存储到数据库的主要内容,如果未能解决你的问题,请参考以下文章
如何一次将从 Firebase 检索到的数据存储在 ArrayList<String> 中?
将从 spring-boot 检索到的数据转换为 JSON 并在 Angular 前端获取它