Radio button values in a foreach loop in PHP Codeigniter - php

I am trying to create an input element of type radio within a foreach loop and save the values in a database when the submit button is clicked. I'm using Codeigniter framework.
My views:
<?php echo form_open('students_report/produce_aptitude_score/'.$y->id); ?>
<table>
<tbody>
<?php
$i = 1;
foreach ($aptitudes as $p) { ?>
<input type="hidden" name="aptitude[]" value="<?php echo $p->aptitude; ?>" />
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $p->aptitude; ?></td>
<td>
<div class="form-group">
<input class="form-control" type="radio" name="score[<?php echo $i; ?>]" value="1" />
</div>
</td>
<td>
<div class="form-group">
<input class="form-control" type="radio" name="score[<?php echo $i; ?>]" value="2" />
</div>
</td>
</tr>
<?php $i++; //increment index
} //endforeach ?>
</tbody>
</table>
<button class="btn btn-success btn-lg">Submit</button>
<?php echo form_close(); ?>
My Controller
public function produce_aptitude_score($id) {
$y = $this->common_model->get_student_details_by_id($id);
$this->form_validation->set_rules('aptitude[]', 'Aptitude', 'trim');
$aptitude = $this->input->post('aptitude', TRUE);
$score = $this->input->post('score', TRUE);
if ($this->form_validation->run()) {
for ($i = 0; $i < count($aptitude); $i++) {
$d_aptitude = $aptitude[$i];
$d_score = $score[$i];
$query = $this->students_report_model->check_aptitude_score_exists($id, $d_aptitude);
if ($query->num_rows() == 0) { //data does not exists, do insert
$this->students_report_model->insert_aptitude_score($id, $d_aptitude, $d_score);
} else { //data already exists, do update
$this->students_report_model->update_aptitude_score($id, $d_aptitude, $d_score);
}
}
$this->session->set_flashdata('status_msg', "Aptitude score submitted successfully for {$y->first_name}");
redirect($this->agent->referrer());
} else {
$this->produce_report($id); //form validation fails, reload page with errors
}
}
My Model
public function insert_aptitude_score($id, $aptitude, $score) {
$y = $this->common_model->get_student_details_by_id($id);
$data = array(
'admission_id' => $y->admission_id,
'aptitude' => $aptitude,
'score' => $score,
'session' => current_session,
'term' => current_term,
);
return $this->db->insert('aptitude_scores', $data);
}
public function update_aptitude_score($id, $aptitude, $score) {
$y = $this->common_model->get_student_details_by_id($id);
$query = $this->check_aptitude_score_exists($id, $aptitude);
$result_id = $query->row()->id;
$data = array(
'aptitude' => $aptitude,
'score' => $score,
);
$this->db->where('id', $result_id);
return $this->db->update('aptitude_scores', $data);
}
When I submit, why do I get the following error?
PHP: Undefined offset: 0
Database: Column 'score' cannot be null

Related

Unable to insert multiple checkbox data in the database

UPDATED. I'm having problem about inserting multiple checkbox data in the database.
Here is my view
<?php
$i = 0;
$qArr = array();
$qArrc = 0;
$qArr1 = array();
$qArrc1 = 0;
$uArr = array();
$u = 0;
foreach($questions->result() as $q){ ?>
<input type="checkbox" name="check[<?php echo $i; ?>]" value="<?php echo $qArr[$qArrc++] = $q -> questions; ?>"> <?php echo $q->questions; ?> <br>
<input class="form-control" value="<?php echo $uArr[$u++] = $this->session->userdata('user_id'); ?>" name="hidden[<?php echo $i; ?>]" type="hidden">
<input class="form-control" value="<?php echo $qArr1[$qArrc1] = $q->id; ?>" name="hidden1[<?php echo $i; ?>]" type="hidden">
<?php
$i++;
}?>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
Here's my controller
for($i = 0; $i<count($this->input->post('check')); $i++){
$data1 = array(
'question' => $this->input->post('check')[$i],
'speaker_id' => $this->input->post('hidden')[$i],
'question_id' => $this->input->post('hidden1')[$i]
);
$this->input->post('submit');
$this->Speaker_Model->insert_speakerfeedback($data1);
}redirect('speaker/createfeedback');
Here's my model
public function insert_speakerfeedback($data1){
$this->db->insert("speakerdata", $data1);
}
Modify your for loops :
for($i = 0; $i<count($this->input->post('check')); $i++){
to use foreach instead` :
foreach ($this->input->post('check') as $i => $value) {
So it will prevent getting undefined index if you skip some checkbox. And the redirect line should be outside of the loops.
For bulk insert, you could use insert_batch function.
Within the loop, change :
$data1 = array(
to
$data1[] = array(
So it will not overwriting on each iteration.
And on the Model, change :
$this->db->insert("speakerdata", $data1);
to :
$this->db->insert_batch("speakerdata", $data1);

How to insert row by row values in single submit

This is my view Page
This is Dynamically fields Test Name and units are from Table I need to insert Test name and Result and Normal value also Unit.
My Controller
$patient_id = $this->input->post('patient_id');
$doctor_id = $this->input->post('doctor_id');
$prescription_id = $this->input->post('prescription_id');
$lab_result =$this->input->post('lab_result');
$lab_test =$this->input->post('lab_test');
$units =$this->input->post('units');
$normal_value =$this->input->post('normal_value');
$cat_id = $this->input->post('cat_id');
for($i=0; $i<count($prescription_id); $i++)
{
$labreport[] = array(
'patient_id' => $patient_id[$i],
'doctor_id' => $doctor_id[$i],
'prescription_id' =>$prescription_id[$i],
'lab_result' => $lab_result[$i],
'lab_test' => $lab_test[$i],
'units' => $units[$i],
'normal_value' => $normal_value[$i],
'cat_id' => $cat_id, );
//echo '<pre>'; print_r($labreport); '</pre>'; exit;
}
$stringlabreport= json_encode($labreport);
$this->db->insert('patient_lab_report',$stringlabreport);
if($this->db->affected_rows()){
return true;
} else {
return false;
}
$this->session->set_flashdata('message','Lab Report Added Successfully');
redirect('laboratory_report/all');
=========================
And This is My View Code
<tr>
<td><input type="hidden" value="<?php echo $data->name; ?>"name="lab_test[]"><?php echo $data->name; ?></td>
<td><input type="text" value="" name="lab_result[]" class="form-control"></td>
<td><input type="hidden" value="<?php echo $data->units; ?>" name="units[] "> <?php echo $data->units; ?></td>
<td><input type="hidden" value="<?php echo $data->n_value; ?>" name="normal_value[] "> <?php echo $data->n_value; ?></td>
</tr>
Use array names for input. I.E.:
<form action="" method="post" name="someform">
<input name="row[0][test_name]"/>
<input name="row[0][result]"/>
<input name="row[1][test_name]"/>
<input name="row[1][result]"/>
<input type="submit" name="submitted" value="send">
</form>
So upon submission, parsing in php, use filter_input with FILTER_REQUIRE_ARRAY as option:
<?php
$submitted = filter_input(INPUT_POST, 'submitted');
if(!empty($submitted)){
$rows = filter_input(INPUT_POST,'row', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
$parsed_rows = [];
foreach($rows as $row){
if(!empty($row['test_name']) && !empty($row['result'])){
$parsed_rows[] = $row;
}
}
}
?>

codeigniter Insert_batch not working

I am trying to insert multiple rows into my database table using codeigniter insert_batch. base on the error report it seems like the table columns are not set. just the number of arrays:
My view:
<table class="table">
<center><h3> Activity Name: <?php echo $activity_name; ?></h3><h4> Date: <?php echo $activity_date; ?></h4></center>
<tr>
<td>Member Name and Course</td>
<td>Attendance</td>
<td>fee</td>
</tr>
<?php
$count = 1;
$member_count = 1;
foreach ($students as $row) {
$uID = $row['user_ID'];
$cID = $row['council_ID'];
$aID = $row['activity_ID'];
$name = $row['user_LastName'].", ".$row['user_FirstName'];
$course = $row['user_Course'];
$year = $row['user_Year'];
?>
<tr>
<td>
<h4> <?php echo $member_count.". ".$name; ?></h4>
<h5> <?php echo $course." - ".$year; ?></h5>
</td>
<?php echo form_open('Isidran/InsertAttendance'); ?>
<input type="hidden" id="uID<?php echo $count; ?>" name="uID[]" value="<?php echo $uID;?>">
<input type="hidden" id="cID<?php echo $count; ?>" name="cID[]" value="<?php echo $cID;?>">
<input type="hidden" id="aID<?php echo $count; ?>" name="aID[]" value="<?php echo $aID;?>">
<input type="hidden" id="aname<?php echo $count;?>" name="aname[]" value="<?php echo $activity_name; ?>">
<td><select id="attendance<?php echo $count; ?>" name="attendance[]" class="form-control">
<option value="Absent"> Absent </option>
<option value="Present"> Present </option>
</select>
</td>
<input type="hidden" id="name<?php echo $count;?>" name="name[]" value="<?php echo $name;?>">
<input type="hidden" id="fines<?php echo $count; ?>" name="fines[]" value="<?php echo $activity_fee; ?>">
<td><div id="fee<?php echo $count; ?>"><?php echo $activity_fee; ?></div> </td>
</tr><br />
<script type="text/javascript">
$(function() {
$('#attendance<?php echo $count; ?>').change(function(){
var activity_fee = '<?php echo $activity_fee; ?>'
if($('#attendance<?php echo $count; ?>').val() == 'Absent') {
$('#fee<?php echo $count; ?>').show();
$('#fee<?php echo $count; ?>').text('<?php echo $activity_fee; ?>');
} else {
$('#fee<?php echo $count; ?>').show();
$('#fee<?php echo $count; ?>').text('0');
$('#fines<?php echo $count; ?>').val('0');
}
});
});
</script>
<?php $count++; $member_count++; } ?>
<tr>
<td colspan="3"><button type="submit" id="btn_submit" class="btn btn-info pull-right">Submit</button></td>
</tr>
<?php echo form_close(); ?>
</table>
My Controller:
public function InsertAttendance()
{
$attendance_data = array(
'attendance_userID' => $this->input->post('uID[]'),
'attendance_councilID' => $this->input->post('cID[]'),
'attendance_activityID' => $this->input->post('aID[]'),
'attendance_activity' => $this->input->post('aname[]'),
'attendance_status' => $this->input->post('attendance[]'),
'attendance_sname' => $this->input->post('name[]'),
'attendance_fines' => $this->input->post('fines[]'));
$data['result'] = $this->Site_model->insertAttendance($attendance_data);
if($data['result'] == true)
{
$this->session->set_flashdata('feedback', '<div class="alert alert-success alert-dismissable">
×
<strong>Added Successfully</strong>
</div>');
redirect('Isidran/Home');
}
}
and Model:
public function insertAttendance($data)
{
$this->db->insert_batch('tbl_council_activity_attendance', $data);
if($this->db->affected_rows() > 0)
{
return true;
}
}
Try
public function insertAttendance($data)
{
$attendance=array(
'column1' => $data['index1'],
'column2' => $data['index2'],
'column3' => $data['index3'],
.
.
);
$this->db->insert('tbl_council_activity_attendance', $attendance);
if($this->db->affected_rows() > 0)
{
return true;
}
}
If you want to insert batch than your data array will be
$array_name=array(
array(
'col1'=>'data',
'col2'=>'data',
'col3'=>'data'
),
array(
'col1'=>'data',
'col2'=>'data',
'col3'=>'data'
)
);

Update Textbox value which are in loop using Post Submit (Codeigniter)

i have 2 textbox in loop
and i want to update their value in database when i press button.
the issue is that when i press button it updates only last textbox value .
following is my model.
function approvedHrs($taskid,$data)
{
//$this->db->where('id', $id);
$this->db->where('taskid', $taskid);
$this->db->update(MILESTONE, $data);
}
Following is my View (For lop is here)
<?php
foreach ($result as $milestone_row) {
?>
<tr id="<?php echo $milestone_row->id; ?>">
<?php
if ($is_master_admin) {
if ($i > 1) {
if ($milestone_row->userid == $userid) {
} else {
$userid = $milestone_row->userid;
echo $milestone_row->usertitle;
}
} else {
$userid = $milestone_row->userid;
echo $milestone_row->usertitle;
}
}
?>
<li class="in">
Add Bug
<div class="message">
<span class="arrow"></span>
<span class="body">
<?php
echo '<b> <U> Task Title </U>:- </b> &nbsp';
echo $milestone_row->tasktitle;
echo '<br/>';
echo '<b> <U> Workspace Title </U>:- </b> &nbsp';
echo $milestone_row->workspacetitle;
echo '<br/>';
echo '<b> <U> Description </U>:- </b> &nbsp';
echo $milestone_row->description;
echo '<br/>';
echo '<b> <U> Hours </U>:- </b> &nbsp';
echo $milestone_row->esthours;
echo 'hrs';
echo '<br/>';
echo '<b> <U> Minutes </U>:- </b> &nbsp';
echo $milestone_row->estmin;
echo'mins';
echo '<br/>';
?>
<b><u>Approved Hours:-</u></b>
<input style="height:14px;font-size:10pt; width: 33px" type="text" id="hours" name="approvedhrs" data-required="1" value="<?php echo $milestone_row->esthours; ?>" placeholder="Hours" onkeypress="return isNumberKey(event)" />
<input style="height:14px;font-size:10pt; width: 33px" type="text" id="minutes" name="approvedmins" value="<?php echo $milestone_row->estmin; ?>" data-required="1" placeholder="Minutes" onkeypress="return isNumberKey(event)" />
Edit
<?php echo " | ";?>
Delete
<!--<span class="datetime">at <?php //echo $milestone_row->createddate; ?></span> -->
</span>
</div>
</li>
Followinf is myController
function approvedHrs($taskid)
{
if ($this->session->userdata('logged_in')){
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$username = $session_data['username'];
$is_master_admin = $session_data['master'];
$imagethumb = $session_data['imagethumb'];
$pendingbug = $this->bugmodel->getBug($id, $is_master_admin);
$pendingtask = $this->taskmodel->getTask($id, $is_master_admin);
$data = '';
$data = array(
'approvedhrs' =>$this->input->post('approvedhrs'),
'approvedmins'=>$this->input->post('approvedmins')
);
// print_r($data);
// exit;
$result = $this->milestonemodel->approvedHrs($taskid,$data);
// $this->session->set_userdata('msg', $result);
redirect('task', 'refresh');
}
else
{
redirect('login', 'refresh');
}
}
When i use array like this it gives me following error
PHP Error Occured :Message: Array to string conversion
Database Error : Unknown column 'Array' in 'field list'
UPDATE milestone SET approvedhrs = Array, approvedmins = Array WHERE taskid = '17'
You should simplify your code like this
$post = $this->input->post();
$data['approvedhrs'] = $post['approvedhrs'];
$data['approvedmins'] = $post['approvedmins'];
print_r($data);
$result = $this->milestonemodel->approvedHrs($taskid,$data);
You should make sure $post['approvedhrs'] and $post['approvedmins'] do not have arrays. They could contain array when defined in the form like this
<input type='text' name="approvedhrs[]" />
<input type='text' name="approvedmins[]" />
EDIT
As you are making inputs inside loops there fore both approvedhrs and approvedmins are posted as array. Which is causing problem in updating.
EDIT
You should make the inputs in your loop like this
<input type='text' name="approvedhrs[]" />
<input type='text' name="approvedmins[]" />
Make hidden inputs for row id and task id
<input type='hidden' name="rowid[]" />
<input type='hidden' name="taskid[]" />
<input type='text' name="approvedhrs[]" />
<input type='text' name="approvedmins[]" />
And now php
$post = $this->input->post();
$data['approvedhrs'] = $post['approvedhrs'];
$data['approvedmins'] = $post['approvedmins'];
for($i=0;$i<count($data['approvedhrs']);$i++){
$update_data['approvedhrs'] = $data['approvedhrs'][$i];
$update_data['approvedmins'] = $data['approvedmins'][$i];
$taskid = $data['taskid'][$i];
print_r($update_data);
$result = $this->milestonemodel->approvedHrs($taskid,$update_data);
unset($update_data);
unset($taskid);
}
As you are passing array of data to update, you can use update_batch mentod.
In your controller, prepare the data as below.
$k= 0 ;
$data = array();
$aphrs = $this->input->post('approvedhrs'); // returns array
$apmis = $this->input->post('approvedmins'); //
foreach($aphrs as $hrs)
{
$data[] = array(
'approvedhrs' =>$hrs,
'approvedmins'=>$apmis[$k]
);
$k++;
}
// call your model function
$result = $this->milestonemodel->approvedHrs($taskid,$data);
In your model function: add update_batch method. So no need to call update method in forloop.
for update_batch, check this tutorial.
http://ellislab.com/codeigniter/user-guide/database/active_record.html#update
View
<input type='hidden' name="milestoneid[]" value ="<?php echo $milestone_row->id ?>" />
<input type="text" id="hours" name="approvedhrs[<?php echo $milestone_row->id ?>][]" value="<?php echo $milestone_row->esthours; ?>"/>
<input type="text" name="approvedmins[<?php echo $milestone_row->id ?>][]" value="<?php echo $milestone_row->estmin; ?>"/>
Controller
function approvedHrs($taskid) {
if ($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$username = $session_data['username'];
$is_master_admin = $session_data['master'];
$imagethumb = $session_data['imagethumb'];
$pendingbug = $this->bugmodel->getBug($id, $is_master_admin);
$pendingtask = $this->taskmodel->getTask($id, $is_master_admin);
$data = array();
$milestoneIDs = $this->input->post('milestoneid');
$approvedhrs = $this->input->post('approvedhrs');
$approvedmins = $this->input->post('approvedmins');
foreach ($milestoneIDs as $milestoneID) {
$data = array(
'approvedhrs' => isset($approvedhrs[$milestoneID]) ? $approvedhrs[$milestoneID] : '',
'approvedmins' => isset($approvedmins[$milestoneID]) ? $approvedmins[$milestoneID] : '',
);
$this->milestone_model->approvedHrs($milestoneID,$data);//change this model name as per you use
unset($data);
}
redirect('task', 'refresh');
} else {
redirect('login', 'refresh');
}
}
Model
function approvedHrs($milestoteid, $data) {
//$this->db->where('id', $editid);
$this->db->where('milestoteid', $milestoteid);
$this->db->update(MILESTONE, $data);
}

Inserting multiple rows in database codeigniter

I have some issue about the inserting data. It will insert only the waybillno data but the quantity is always same. Please check my code - I think the model is wrong.
Controller
public function create_cargo_manifest(){
$core_model = new Core_m;
$core_model->save_cargo_details($this->input->post());
redirect('core/cargo_lookup/');
}
Model
function save_cargo_details(){
$quantity = $this->input->post('quantity');
$waybilldate = $this->input->post('waybilldate');
$data = array();
foreach($this->input->post('sys_wbdetails') as $sys_wbdetails) {
$data[] = array(
'waybillno' => $sys_wbdetails,
'quantity' => $quantity,
'waybilldate' => $waybilldate,
);
}
return $this->db->insert_batch('sys_cargodetails', $data);
}
View
<?php foreach($waybill_header as $waybill_header) { ?>
<?php echo form_open('core/create_cargo_manifest'); ?>
<td><input type="checkbox" name="sys_wbdetails[]" value="<?php echo $waybill_header->waybillno; ?>"></td>
<td><?php echo $waybill_header->waybillno; ?></td>
<td><?php echo $waybill_header->waybilldate; ?><input type="hidden" value="<?php echo $waybill_header->waybilldate; ?>" name="waybilldate"></td>
<td><input type="text" size="5" value="<?php echo $waybill_header->quantity; ?>" name="quantity"></td>
<td><input type="submit" value="save"></td>
<?php } ?>
<?php form_close(); ?>
All your inputs for quantity have the same name : quantity. So you're only submitting the last value in your form. You need to use an array for those inputs (quantity[]), just like for your checkboxes. And you might want to do the same for the waybilldate inputs.
<td><input type="text" size="5" value="<?php echo $waybill_header->quantity; ?>" name="quantity[]"></td>
And then in PHP, something like that :
$data = array();
// Count distinct entries in the form
$count = count($this->input->post['sys_wbdetails']);
for($i=0; $i < $count; $i++) {
$data[] = array(
'waybillno' => $this->input->post['sys_wbdetails'][$i],
'quantity' => $this->input->post['quantity'][$i],
'waybilldate' => $this->input->post['waybilldate'][$i],
);
}
EDIT : also, take a look at this answer if you want a clean way to keep track of which form input goes where.

Categories