我想将帖子数据存储到数据库中,并且我有动态生成的字段course[]
、start_date[]
等,我编写以下代码来检索和存储帖子数据:
但执行以下命令后,所有字段中仅存储“0”零。
if($this->input->post('course'))
{
$education_data= array();
for($i=0; $i<count($_POST['course']); $i++)
{
$education = array(
'course' => $this->input->post('course' . $i),
'start_date' => $this->input->post('start_date' . $i),
'end_date' => $this->input->post('end_date' . $i),
'college_name' => $this->input->post('college_name' . $i),
'other_info' => $this->input->post('other_info' . $i),
);
$this->db->insert('education',$education);
}
}
然后我尝试了第二种方法:
if($this->input->post('course'))
{
$courses = $this->input->post("course");
$startdates = $this->input->post("start_date");
$end_date = $this->input->post("end_date");
$college_name = $this->input->post("college_name");
$other_infos = $this->input->post("other_info");
$education_data= array();
for($i=0; $i<count($_POST['course']); $i++)
{
$education = array(
'course' => $courses[$i],
'start_date' => $startdates[$i],
'end_date' => $end_date[$i],
'college_name' => $college_name[$i],
'other_info' => $other_infos[$i], //line number 101
);
// Insert Education data in 'education' table
$this->db->insert('education',$education);
}
}
但在这种情况下,仅运行一次迭代,并且在第二次迭代时,它在循环的第二次迭代中给出了一些错误。
第二次迭代时出现错误:
Severity: Notice
Message: Undefined offset: 1
Filename: models/resume_model.php
Line Number: 101
A Database Error Occurred
Error Number: 1048
Column 'other_info' cannot be null
INSERT INTO `education` (`course`, `start_date`, `end_date`, `college_name`, `other_info`) VALUES ('', '', '', '', NULL)
Filename: C:\wamp\www\resume\system\database\DB_driver.php
Line Number: 330
如果有人知道请提出解决方案。
var_dump 输出:
[course] => Array
(
[0] => course1
[1] => course2
)
[start_date] => Array
(
[0] => from1
[1] => from2
)
[end_date] => Array
(
[0] => to1
[1] => to2
)
[college_name] => Array
(
[0] => univ1
[1] => univ2
)
[other_info] => Array
(
[0] => other1
)
最佳答案
var_dump 更新
从 var_dump 中您可以看到 other_info 不会有 'other_info' => $other_infos[1]
因为数组中只有一项。如果您希望秒代码正常工作,您可以向 other_info 添加另一个索引。
@JoseVega 的更新我已经更新了上述问题,但有错误
您的错误指出为 other_info 传递的值为空,从该错误中我假设您的表架构不支持 other_info 列的空值。您可以更改架构以允许空值,也可以在空值时向其传递一个值。
尝试以下操作,然后查看结果。我假设并非所有数组的大小都相同,这就是第二次迭代失败的原因。
for($i=0; $i<count($courses); $i++) {
$education = array(
'course' => isset($courses[$i]) ? $courses[$i] : "",
'start_date' => isset($startdates[$i]) ? $startdates[$i] : "",
'end_date' => isset($end_date[$i]) ? $end_date[$i] : "",
'college_name' => isset($college_name[$i]) ? $college_name[$i] : "",
'other_info' => isset($other_infos[$i]) ? $other_infos[$i] : "",
);
// Insert Education data in 'education' table
$this->db->insert('education',$education);
}
关于php - 发布数据未正确存储在 codeigniter 的数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11798073/