我正在尝试从输入字段数组中获取数据并将其写入数据库。我以前从未使用过数组,但这是我的代码。它基于如果它只是一个输入值我会做什么。我知道这是错误的,但我不知道下一步该尝试什么。有任何想法吗?谢谢。
//view
<input type="text" name="assignments[]">
<input type="text" name="hours[]">
<input type="text" name="assignments[]">
<input type="text" name="hours[]">
<input type="text" name="assignments[]">
<input type="text" name="hours[]">
<input type="text" name="assignments[]">
<input type="text" name="hours[]">
<input type="text" name="assignments[]">
<input type="text" name="hours[]">
//controller
$assignments = $this->input->post('assignments', TRUE);
$hours = $this->input->post('hours', TRUE);
$this->load->model('create', 'create_model');
$this->create_model->create_projects($assignments, $hours);
//model
public function create_projects($assignments, $hours) {
$data = array(
'assignments' => $assignments,
'hours' => $hours,
);
$this->db->insert('projects', $data);
}
最佳答案
当然,你不能将 PHP 数组按原样放入数据库中:
$data = array(
'assignments' => $assignments, // this is an array
'hours' => $hours, // so is this
);
$this->db->insert('projects', $data);
您需要数组的字符串表示形式,我想到了两个选项:
我个人更喜欢 json_encode,因为它不依赖于 PHP 来读取,序列化对于存储 PHP 对象很有用,但这里不需要:
$data = array(
'assignments' => json_encode($assignments),
'hours' => json_encode($hours),
);
$this->db->insert('projects', $data);
确保您的数据库字段是 TEXT
类型,以便它们能够存储可变长度数据。当您稍后获取数据时,您必须在每个字段上运行 json_decode() 来读取数据并将其转回数组,例如:
$result = $this->db->get('projects')->result();
foreach ($result as $record)
{
$assignments = json_decode($record->assignments);
// Now $assignments is an array
}
关于database - CodeIgniter - 将输入数组写入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12944077/