Reputation: 205
I am trying to grab the data from an array of input fields and write them to a database. I have never worked with arrays before but this is the code I have. It is based off what I would do if it was just a single input value. I know this is wrong but I have no idea what to try next. Any ideas? Thanks.
//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);
}
Upvotes: 2
Views: 5502
Reputation: 318
In post:- $skills = $this->input->post('skills[]',TRUE);
'skills' => json_encode($skills) ,
It solved my problem.
Upvotes: -1
Reputation: 1412
Simply use json_encode() function to store array data in the database
json_encode(array('key' => 'value'))
OR
json_encode($_P0ST['ARRAY'])
OR IN CodeIgniter
json_encode($this->input->post('arraydata'));
Upvotes: 0
Reputation: 205
Thanks the answers. What ended up working best for me was this.
//controller
$assignments = $this->input->post('assignments');
$hours = $this->input->post('hours');
$this->load->model('create', 'create_model');
foreach($assignments as $key => $n){
$this->create_model->create_projects($n, $hours[$key]);
}
Upvotes: 2
Reputation: 102745
Of course you can't put a PHP array in the database as is:
$data = array(
'assignments' => $assignments, // this is an array
'hours' => $hours, // so is this
);
$this->db->insert('projects', $data);
You need a string representation of the array, two options come to mind:
Personally I prefer json_encode as it is not dependent on PHP for reading, serialize is useful for storing PHP objects but you don't need that here:
$data = array(
'assignments' => json_encode($assignments),
'hours' => json_encode($hours),
);
$this->db->insert('projects', $data);
Make sure your DB fields are TEXT
type so they are able to store variable length data. When you fetch the data later, you will have to run json_decode()
on each field to read it and turn it back into an array, for example:
$result = $this->db->get('projects')->result();
foreach ($result as $record)
{
$assignments = json_decode($record->assignments);
// Now $assignments is an array
}
Upvotes: 3