Reputation: 115
I stumbled upon a concern regarding my friends CI project: he wanted to add a new <input>
tag to the body and insert to MySQL, so I made this code:
<?php echo form_open('welcome');?>
<div id="container">
<p id="add_field"><a href="#"><span>» Add Educational Background.....</span></a></p>
</div>
<div class="spacer"></div>
<input id="go" name="btnSubmit" type="submit" value="insert" class="btn" />
<?php echo form_close();?>
Controller:
$this->load->view('welcome_message');
$this->load->model('test');
if($this->input->post('attain',true) != null){
foreach ($this->input->post('attain',true) as $a) {
foreach ($this->input->post('major',true) as $m)
foreach ($this->input->post('school',true) as $s)
$data = array(
'attain'=>$a,
'major'=>$m,
'school'=>$s);
$this->db->insert('stress',$data);
print_r($data); // for show purposes
redirect(base_url());
}
}
the Javascript:
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<input id="major' + count + '" name="attain[]' + '" type="text" />' +
'<input id="major' + count + '" name="major[]' + '" type="text" />' +
'<input id="' + count + '" name="school[]' + '" type="text" /><br />' );
});
});
</script>
This was written in CodeIgniter.
Upvotes: 5
Views: 4916
Reputation: 171669
There are too many loops nested inside each other which would result in far too many database entries.
Also the redirect was inside the loop so as soon as the first insert was made the redirect would occur
Try:
if ($this->input->post('attain')) { // returns false if no property
$attain = $this->input->post('attain', true);
$schools = $this->input->post('school', true);
$major = $this->input->post('major', true);
foreach ($attain as $i => $a) { // need index to match other properties
$data = array(
'attain' => $a,
'major' => isset($majors[$i]) ? $majors[$i] : '',
'school' => isset($schools[$i]) ? $schools[$i] : ''
);
if (!$this->db->insert('stress', $data)) {
// quit if insert fails - adjust accordingly
print_r($data);
die('Failed insert');
}
}
// don't redirect inside the loop
redirect(base_url());
} else{
echo 'No Data';
}
Upvotes: 4