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'
)
);
Related
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;
}
}
}
?>
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
function chkQuestions($info)
{
$query = $this->handle->prepare("SELECT * FROM tbltest");
$query->execute();
$rows = $query->fetchAll();
$getPost = $query->rowCount();
foreach($rows as $row) {
for($i = 1; $i <= $getPost; $i++) {
$answerID[$i] = array($info['answer'.$i]);
$lo = array($answerID);
}
foreach($answerID as $question) {
if(array_key_exists($row['answer'],$question)) {
$test = "found";
return $test;
} else {
return $question;
}
}
}
}//chkQuestions
Above is my function, all works, but when I compare the row in my database called answer with the array it doesn't work?
I tried hard coding in the value and it works correctly but not with the array.
I checked to see the values of array and the value is indeed there.
In logic $answerID[$i] = array($info['answer'.$i]); = option1 and if the array value option1 = the database row answer which is set to option1 than return found, but it tells me it cannot find it.
array(1)
{
[0]=> string(7) "option1"
}
Above is the dum_var of the array $question. Any help?
foreach($questions as $question)
{
?>
<h3><?php echo $question['question'] ?></h3>
<div class = "col-xs-12">
<input type="radio" name="answer<?php echo $question['testID'] ?>" id="answer<?php echo $question['testID'] ?>" value="<?php echo $question['option1']?>" />
<label for="question-1-answers-A">A)<?php echo $question['option1'] ?> </label>
</div>
<div class = "col-xs-12">
<input type="radio" name="answer<?php echo $question['testID'] ?>" id="answer<?php echo $question['testID'] ?>" value="<?php echo $question['option2']?>" />
<label for="question-1-answers-B">B)<?php echo $question['option2'] ?></label>
</div>
<div class = "col-xs-12">
<input type="radio" name="answer<?php echo $question['testID'] ?>" id="answer<?php echo $question['testID'] ?>" value="<?php echo $question['option3']?>" />
<label for="question-1-answers-C">C)<?php echo $question['option3'] ?></label>
</div>
<div class = "col-xs-12">
<input type="radio" name="answer<?php echo $question['testID'] ?>" id="answer<?php echo $question['testID'] ?>" value="<?php echo $question['option4']?>" />
<label for="question-1-answers-D">D)<?php echo $question['option4'] ?></label>
<br>
<br>
</div>
<?php
}
echo "<input type='hidden' name='subaction' id='subaction' value='chkQuestion'> <button class='btn btn-primary' name='submit' type='submit'>Submit</button> </form>";
}
else
echo "No Quiz Found </form>";
?>
</div>
I don't have a lot of confidence in my answer because your coding method does a good job of confusing me. However, I feel like I need to get something on the page so we have some sort of solid base to work from:
function chkQuestions($info){
$check=array(); // this will hold the results to return
$stmt=$this->handle->prepare("SELECT `testID`,`answer` FROM tbltest");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
if($info['answer'][$row['testID']]==$row['answer']){
$check[$row['testID']]="correct";
}else{
$check[$row['testID']]="incorrect";
}
}
return $check; // handle this however you like on your main page
}
I'm using a foreach to save in database my form datas.
And, sometimes some values are empty because it's the same as the last value entered. I would like (if the current iteration value is empty) to get the last iteration value and to print it.
Do you have a solution?
Thank you!
<?php
$html = file_get_contents("Intranet link");
function parseTable($html){
$dom = new domDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = true;
$tables = $dom->getElementById('tblResultats');
$rows = $tables->getElementsByTagName('tr');
return $rows;
}
$rows = parseTable($html);
$i = 1;
$count = 0;
foreach ($rows as $row){
if($i <> 1 ){
$cols = $row->getElementsByTagName('td');
if (preg_match('/visite/i',$cols->item(0)->nodeValue)) {
$count = $count-1;
}else{
$cols->item(6)->nodeValue = str_replace(' ', '', $cols->item(6)->nodeValue);
$train_nbr = preg_replace("/[^0-9,.]/", "", $cols->item(6)->nodeValue);
if($train_nbr == ""){
$train_nbr = "00000";
}
?>
<div id="criter_<?php echo $count; ?>" class="panel <?php if($cols->item(4)->nodeValue == " -Z"){ echo "panel-z-series"; }elseif($cols->item(4)->nodeValue == " -X"){ echo "panel-x-series"; }elseif($cols->item(4)->nodeValue == " BB"){ echo "panel-bb-series"; }elseif($cols->item(4)->nodeValue == " -B"){ echo "panel-b-series"; } ?>">
<input type="hidden" name="trainid_<?php echo $count; ?>" value="<?php echo $train_nbr; ?>">
<input type="hidden" name="traintype_<?php echo $count; ?>" value="<?php echo $cols->item(4)->nodeValue; ?>">
<input type="hidden" name="userid_<?php echo $count; ?>" value="<?php echo $_SESSION["Auth"]["username"]; ?>">
<input type="hidden" name="entrydate_<?php echo $count; ?>" value="<?php echo date("d/m/Y"); ?> <?php echo $cols->item(2)->nodeValue; ?>">
<input type="hidden" name="leftdate_<?php echo $count; ?>" value="<?php echo $cols->item(8)->nodeValue; ?>">
<input type="hidden" name="openeddate_<?php echo $count; ?>" value="<?php echo date("d/m/Y H:i:s"); ?>">
<input type="hidden" name="entrynumber_<?php echo $count; ?>" value="<?php echo $cols->item(0)->nodeValue; ?>|<?php echo $cols->item(1)->nodeValue; ?>">
<input type="hidden" name="leftnumber_<?php echo $count; ?>" value="<?php echo $cols->item(7)->nodeValue; ?>|<?php echo $cols->item(9)->nodeValue; ?>">
<div class="panel-heading">
<button onclick='addValue();$("#criter_<?php echo $count; ?>").remove();' class="btn btn-default"><i class="fa fa-trash"></i></button>
<strong><?php echo $cols->item(2)->nodeValue; ?> </strong>
<div style="font-size:18px;margin-top:-30px"><?php if($cols->item(4)->nodeValue == " -Z"){ echo "<strong>Z</strong>"; }elseif($cols->item(4)->nodeValue == " -X"){ echo "<strong>X</strong>"; }elseif($cols->item(4)->nodeValue == " BB"){ echo "<strong>BB</strong>"; }elseif($cols->item(4)->nodeValue == " -B"){ echo "<strong>B</strong>"; } echo $train_nbr; ?></div>
<span class="pull-right">
<div class="input-group date picker" >
<input type="text" class="form-control" value="<?php echo $cols->item(8)->nodeValue; ?>"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</span>
<br>
<!-- If values from current iteration are empty, get the values from the -1 iteration -->
Train numéro <strong><?php echo $cols->item(0)->nodeValue; ?></strong> en provenance de <strong><?php echo $cols->item(1)->nodeValue; ?></strong> et à destination de <strong><?php echo $cols->item(9)->nodeValue; ?></strong> (<strong><?php echo $cols->item(7)->nodeValue; ?></strong>)
</div>
<div class="panel-body">
<div id="room_criter_<?php echo $count; ?>">
<p>
Commentaire sur l'engin :<br>
<input type="text" style="width:100%;display: inline-block;margin-bottom:8px;" name="comments_<?php echo $count; ?>" placeholder="Commentaire éventuel sur cet engin (imprévu par exemple)" class="form-control">
Planification des événements :<br>
<input type="text" style="width:70%;display: inline-block;margin-bottom:8px;" name="eventcriter_<?php echo $count; ?>[]" placeholder="Evènement ou intervention planifiée sur cet engin" class="form-control">
<input type="hidden" name="lastmodified_<?php echo $count; ?>[]" value="<?php echo $_SESSION['Auth']['username']; ?>" class="form-control">
<select style="width:19%;display: inline-block;" class="form-control" name="eventcriterstatus_<?php echo $count; ?>[]">
<option value="0" selected>Non effectuée</option>
<option value="1">En cours</option>
<option value="2">Terminée</option>
</select>
<a style="display: inline-block;border-radius: 4px;" class="btn btn-success" onclick="add_fields(<?php echo $count; ?>);"><span class="fa fa-plus"></span> Ajouter</a>
</p>
</div>
</div>
</div>
<?php
}
}
$i++;
$count++;
}
?>
I'm not sure if I understood the task right, but here's my try.
for ($i = 2, $n = count($rows); $i < $n; ++$i) {
$row = $rows[$i - 1];
$prevRow = $rows[$i - 2];
$cols = $row->getElementsByTagName('td');
$prevCols = $prevRow->getElementsByTagName('td');
$values = [];
for ($j = 0; $j < ITEMS_COUNT; ++$j) {
$value = $cols->item($j)->nodeValue;
if (empty($value)) {
$value = $prevCols->item($j)->nodeValue;
}
$values[$j] = $value;
}
//And then you can use $values[$j] instead of $cols->item($j)->nodeValue.
}
Im confused. I have been analyzing this for hours..
What I want:
"EACH table row with the checkbox thats checked would be updated with the value inputted."
Anyone can help?
thank you,
Leo
Admin.php
function submit_acc(){
$this->access_chk(); //CHECK USER ACCESS
$this->form_validation->set_error_delimiters(' ', '<br />');
$checkbox=$this->input->post('cek');
$sbm=$this->input->post('sbm');
if($sbm == "Update" && $checkbox!=false){
foreach ($checkbox as $row_id) {
// echo($this->input->post('bank_accname'));
$this->form_validation->set_rules("type", "bank name", "required");
$this->form_validation->set_rules("isactive", "Status Bank", "required");
if(!$this->form_validation->run()){ exit(validation_errors()); }
echo "update x where y =$row_id";
echo $_POST["accgroup"].$_POST["type"].$this->input->post('bank_accname').$_POST["bank_accnumber"].$_POST["isactive"];
$data[] = array (
"acc_id" => $row_id,
"acc_accgroup_id" => $_POST["accgroup"],
"acc_bank_name" => $_POST["type"],
"acc_bank_accname" => $this->input->post('bank_accname'),
"acc_bank_accnumber" => $_POST["bank_accnumber"],
"acc_isactive" => $_POST["isactive"]
);
$uid=$row_id;
// echo $uid;
}
//var_dump($data);
//var_dump($checkbox);
$this->db->update_batch('acc', $data, 'acc_id');
exit("end");
View.php
<form action="<?php echo site_url("admin/submit_acc"); ?>" method="post" id="form">
<table>
<tr >
<td align="center"><?php echo $i; ?></td>
<input type="hidden" name="id[]" value="<?php if(isset($r)) echo $r["acc_id"]; ?>" />
<input type="hidden" name="isactive[]" value="<?php if(isset($r)) echo $r["acc_isactive"]; ?>" />
<td><input type="text" class="textbox" style="width:200px;" value="<?php if(isset($r)) echo $r["acc_bank_name"]; ?>" name="type[]" id="type" /></td>
<td><input type="text" class="textbox" style="width:200px;" value="<?php if(isset($r)) echo $r["acc_bank_accname"]; ?>" name="bank_accname[]" id="bank_accname" /></td>
<td><input type="text" class="textbox" style="width:200px;" value="<?php if(isset($r)) echo $r["acc_bank_accnumber"]; ?>" name="bank_accnumber[]" id="bank_accnumber" /></td>
<!--<input type='radio' name="isactive_<?php echo $r['acc_id'];?>" value=1
<?php if ($r["acc_isactive"]=='1') echo 'checked'; ?> > -->
G
<select name="accgroup[]">
<option value='<?php echo $r["accgroup_no"]; ?>' id="account_id"><?php echo $r['accgroup_no']; ?></option>
<?php echo $stropt; ?></select>
<!-- <input type='radio' name='isactive_<?php echo $r['acc_id'];?>' value=0 <?php if ($r["acc_isactive"]=='0')echo 'checked'; ?>> Off -->
" >
</table>
</form>
MY TRY AND ITS NOT WORKING : if I dont select the first row, the second row wont be updated . the point is my checkbox should be checked all to function properly. if not, it would start updating the rows according to numbers of checked checkboxes. Can somebody please tell me what did I miss?????
$data=array();
$data['checkbox']=$this->input->post('cek');
$data['id']=$this->input->post('id',true);
$data['accgroup']=$this->input->post('accgroup',true);
$data['type']=$this->input->post('type',true);
$data['bank_accname']=$this->input->post('bank_accname',true);
$data['bank_accnumber']=$this->input->post('bank_accnumber',true);
$data['isactive']=$this->input->post('isactive',true);
$sbm=$this->input->post('sbm');
if($sbm == "Update" && $data['checkbox']!=false){
foreach ($data['checkbox'] as $key => $each) {
// echo($this->input->post('bank_accname'));
echo $data["accgroup"][$key];
$this->form_validation->set_rules("type", "bank name", "required");
$this->form_validation->set_rules("isactive", "Status Bank", "required");
if(!$this->form_validation->run()){ exit(validation_errors()); }
$temp[] = array (
"acc_id" => $data["id"][$key] ,
"acc_accgroup_id" => $data["accgroup"][$key],
"acc_bank_name" => $data["type"][$key],
"acc_bank_accname" => $data['bank_accname'][$key],
"acc_bank_accnumber" => $data["bank_accnumber"][$key],
"acc_isactive" => $data["isactive"][$key]
);
$uid=$key;
// echo $uid;
}
var_dump($temp);
//var_dump($checkbox);
$this->db->update_batch('acc', $temp, 'acc_id');
exit("end");