How do insert and retrieve checkbox value using codeigniter? - php

My problem is, I key in the sibling details in the first row textboxs and i select the check box no error display. If i didn't select the checkbox its display the below error. Can you give some idea? i am new for CodeIgniter.
I got error message: (How i can solve the error)
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: controllers/registration.php
Line Number: 288
Below my Code:
foreach($querystud_frm->result() as $row)
{
echo "<tr><td>".$i.")</td>";
$data=array('name'=>'s_sibling_name[]','class'=>'textbox','value'=>$row->s_sibling_name,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$data=array('name'=>'s_sibling_nric[]','class'=>'textbox','value'=>$row->s_sibling_nric,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$sib_dob=date('d-m-Y',strtotime(trim($row->s_sibling_dob)));
$data=array('name'=>'s_sibling_dob[]','class'=>'textbox','value'=>$sib_dob,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$data=array('name'=>'s_sibling_relation[]','class'=>'textbox','value'=>$row->s_sibling_relation,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$data=array('name'=>'s_sibling_occupation[]','class'=>'textbox','value'=>$row->s_sibling_occupation,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$data=array('name'=>'s_sibling_income[]','class'=>'textbox','value'=>$row->s_sibling_income,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$sib_yes = $row->s_sibling_yes;
echo $sib_yes;
if($sib_yes == 'YES')
{
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'YES', 'checked' => TRUE);
echo "<td >".form_checkbox($data)."</td>";
}
else
{
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'NO', 'checked' => FALSE);
echo "<td >".form_checkbox($data)."</td>";
}
echo "</tr>";
$i++;
}
if($i<10)
{
$var=array("s_sibling_name","s_sibling_nric","s_sibling_dob","s_sibling_relation","s_sibling_occupation","s_sibling_income");
for($j=$i;$j<=10;$j++)
{
echo "<tr><td>".$j.")</td>";
foreach($var as $value)
{
$value=$value.'[]';
$data_val=array('name'=>$value,'class'=>'textbox','value'=>'','style'=>'text-transform:uppercase;');
echo "<td>".form_input($data_val)."</td>";
}
if($sib_yes == 'YES')
{
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'YES', 'checked' => TRUE);
echo "<td >".form_checkbox($data)."</td>";
}
else
{
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'NO', 'checked' => FALSE);
echo "<td >".form_checkbox($data)."</td>";
}
echo "</tr>";
}
unset($var);
}
$querystud_frm->free_result();
}
else
{
$var=array("s_sibling_name","s_sibling_nric","s_sibling_dob","s_sibling_relation","s_sibling_occupation","s_sibling_income");
$var_sib=array("s_sibling_yes");
for($i=1;$i<=10;$i++)
{
echo "<tr><td>".$i.")</td>";
foreach($var as $value)
{
$name=$value.'[]';
$data=array('name'=>$name,'class'=>'textbox','value'=>'','style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
}
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'YES', 'checked' => FALSE);
echo "<td >".form_checkbox($data)."</td>";
echo "</tr>";
}
unset($var,$i,$data,$var_sib);
}
controller/registration.php
if($this->input->post('siblingsfrm'))
{
$this->data['nric']=$this->input->post('s_nric');
//echo $this->input->post('name');
$name=$this->input->post('s_sibling_name');
$nric=$this->input->post('s_sibling_nric');
$dob=$this->input->post('s_sibling_dob');
//$dob=strtotime($dob);
//$dob=date('Y-m-d',strtotime($dob));
$relation=$this->input->post('s_sibling_relation');
$occupation=$this->input->post('s_sibling_occupation');
$income=$this->input->post('s_sibling_income');
$sib_yes=$this->input->post('s_sibling_yes');
$sib_id=$this->input->post('s_sibling_id');
//print_r($sib_id);
//print_r($name);
//exit();
//$this->load->helper('date');
for($i=0;$i<count($name);$i++)
{
if($name[$i]!='')
{
$income[$i]=trim($income[$i]);
if($income[$i]=='')
$income[$i]=0;
if($sib_yes[$i]!= 'YES')
$sib_yes[$i]='NO';
$date=date('Y-m-d',strtotime(trim($dob[$i])));
$insert_values=array('s_nric'=>$this->data['nric'],'s_sibling_name'=>strtoupper(trim($name[$i])),
's_sibling_nric'=>strtoupper(trim($nric[$i])),'s_sibling_dob'=>$date,
's_sibling_relation'=>strtoupper(trim($relation[$i])),
's_sibling_occupation'=>strtoupper(trim($occupation[$i])),
's_sibling_income'=>strtoupper(trim($income[$i])),
's_sibling_yes'=>trim($sib_yes[$i]));
if(is_array($sib_id) && isset($sib_id[$i]) )
{
$where=array('s_sibling_id'=>$sib_id[$i]);
$this->db->update('si_student_siblings',$insert_values,$where);
}
else
{
//print_r($insert_values);
$this->db->insert('si_student_siblings',$insert_values);
}
}
}
$this->data['level']=7;
}

The problem is that if a checkbox wasn't checked, it won't send any data at all to the server. So, this line of code...
$name=$this->input->post('s_sibling_name');
...will actually set the $name variable to FALSE (see $this->input->post() documentation in the guide)
Thus, the first time through your loop, your code is looking for the array item at $name[0], when in fact $name is not even an array, it's FALSE.
You could surround your for loop with an if/else statement to solve this problem (not the most elegant solution, but it would work):
if (is_array($name) && count($name) > 0)
{
for($i=0;$i<count($name);$i++)
{
if($name[$i]!='')
//etcetera...
}
}

Related

How do I create and name checkboxes within a foreach loop PHP

I seem to be a little stuck with this.
I am trying to create checkboxes within a table of data within a foreach loop.
foreach($datas as $data){
echo "<tr>";
echo "<td><input type='checkbox' name='counter[]'></input></td>";
echo "<td>" .$data['employeeName']. "</td>";
echo "<td>" .$data['amount']. "</td>";
echo "<td>" .$data['reason']. "</td>";
}
This will print out a table of employee reimbursements that have yet to be reimbursed. From here I am wanting to be able to have the user check the checkboxes in multiple rows, and run a SQL database UPDATE statement to update the date of reimbursement in the database.
I'm really confused on how I would name the checkboxes, and submit them to the following page. Thank you in advance for your help, and please let me know if you need any additional information!
You will have to give the employee id as the value of the checkbox
<form name="employee" method="POST">
foreach($datas as $data)
{
echo "<tr>";
echo "<td><input type='checkbox' name='counter[]' value=$data['id']></input></td>";
echo "<td>" .$data['employeeName']. "</td>";
echo "<td>" .$data['amount']. "</td>";
echo "<td>" .$data['reason']. "</td>";
}
<button type="submit" value="Submit">Submit</button>
</form>
When You Submit the form you will get all employees id checked in the form.
$emloyee=$_POST['counter'];
You will get the data as array.
Then for each employeeid you can update the date of reimbursement.
Hope this helps.
You need to pass value of employee id in checkbox; so when you select checkbox and submit form, you will get all checked employee id's in post data. Here is complete code that may be useful for you to go through.
// On form post this code will be executed
if (isset($_POST['submit'])) {
// this will give you all employee id which you have selected in array
// it will be blank if you have not selected any employee
$counter = isset($_POST['counter']) && !empty($_POST['counter']) ? $_POST['counter'] : [];
// update statement here
if (!empty($counter)) {
foreach ($counter as $key => $empId) {
// update statement goes here
// you can update statement based on $empId here
}
}
}
// sample data; make sure you have employee id that you can use in update statement later on
$datas = [
['id' => 1, 'employeeName' => 'John', 'amount' => 100, 'reason' => 'reason 1'],
['id' => 2, 'employeeName' => 'Heily', 'amount' => 200, 'reason' => 'reason 2'],
['id' => 3, 'employeeName' => 'Keith', 'amount' => 150, 'reason' => 'reason 3']
];
// Your form
echo "<form method='post'>";
echo "<table>";
foreach($datas as $data){
echo "<tr>";
echo "<td><input type='checkbox' name='counter[]' value='".$data['id']."'></input></td>"; // added employee id as value here
echo "<td>" .$data['employeeName']. "</td>";
echo "<td>" .$data['amount']. "</td>";
echo "<td>" .$data['reason']. "</td>";
}
echo "</table>";
echo "<input type='submit' name='submit'>";
echo "<form>";

Cakephp 2.X disable/enable syntax

I'm using the following example
http://jsfiddle.net/nc6NW/1/
Yet when I change this to formhelper syntax the Jquery does not re-enable the disabled save functionality. How does one remove this attribute given this function
<div id="newArticleForm">
<?php
echo $this->Form->create('Post', array('action' => 'add'));
echo $this->Form->input('article_title',array('type' => 'text', 'id'=>'ArticleHeader','div'=>false,'label'=>false,'class'=>'centertext',"placeholder"=>"Article Header"));
echo $this->Html->para(null,'<br>', array());
echo $this->Form->input('article_link',array('type' => 'text', 'id'=>'ArticleLink','div'=>false,'label'=>false,'class'=>'centertext',"placeholder"=>"Article Link"));
echo $this->Html->para(null,'<br>', array());
echo $this->Form->button('Cancel', array('type' => 'reset'), array('inline' => false));
echo $this->Form->button('Save', array('type' => 'submit', 'disabled'=>true), array('inline' => false));
echo $this->Form->end();
?>
</div>
<script>
$(':text').keyup(function() {
if($('#ArticleHeader').val() != "" && $('#ArticleLink').val() != "") {
$('#submit').removeAttr('disabled');
} else {
$('#submit').attr('disabled', true);
}
});
</script>
Solved it, sorry for wasting everyone's time
submit had the wrong identifier, needed a colon not a hash.
i.e.
$(':text').keyup(function() {
if($('#ArticleHeader').val() != "" && $('#ArticleLink').val() != "") {
$(':submit').removeAttr('disabled');
} else {
$(':submit').attr('disabled', true);
}
});

Codeigniter getting multiple data in foreach in controller

I have a problem regarding my foreach loop wherein i cannot access the first array or the array[0] and i dont know the problem.
here is the controller:
$this->SessionCheck();
$this->user->initialize($this->session->userdata('userid'));
$this->load->model('project_model', 'Project');
$ProjectID = $this->input->post('ProjectID');
/***************** Intialize Project model ******************/
$this->Project->Initialize($ProjectID);
$Options = Work_breakdown_structure::$WithBaseTaskID;
//$PhaseTaskID = (int)$this->input->get_post('TaskID',TRUE);
$PhaseTaskID = $this->Project->getPhaseBaseTaskID($ProjectID);
$postlist->PhaseTaskID = $this->Project->getPhaseBaseTaskID($ProjectID);
$postlist->phaseList = $this->Project->LatestApplicablePlan->WBS->GetPhaseList($Options);
if($PhaseTaskID == null)
{ }
else
{
foreach($PhaseTaskID as $index=>$value)
{
$finalArr[$value['TaskName']] = $value['BasetaskID'];
$postlist->taskList = $this->Project->LatestApplicablePlan->WBS->GetWBS($finalArr[$value['TaskName']], $Options);
}
echo print_r($finalArr);
for($x = 1 ; $x < 2 ; $x++)
{
//$postlist->taskList = $this->Project->LatestApplicablePlan->WBS->GetWBS($phaseID, $Options);
}
}
$postlist->project = $ProjectID;
return $this->load->view('MyToDoPhaseDropdown', $postlist);
here is my view:
echo '<td style="padding-top:5x;font-size:14px;" colspan="2"> <br> Phases : ';
echo '<select id="phases_select" style="width:400px;" onchange="search_filter()" >';
echo '<option value="0" selected="selected"> Select Project Phase </option>';
foreach($phaseList as $row)
{
if(preg_match("/^CYCLE/", strtoupper($row['TaskName'])))
{
foreach($row['Child'] as $child)
{
echo '<option value="'. $child['TaskID']. '">';
echo $row['TaskName'].' > '.$child['TaskName'] . '</option>';
}
}
else
{
if($Iterate['BaseTaskID'] != $row['TaskID'])
{
echo '<option value="'. $row['TaskID']. '">';
echo $row['TaskName'].'</option>';
}
foreach($taskList as $Iterate)
{
if($row['TaskID'] == $Iterate['BaseTaskID'] )
{
echo '<option value="'. $row['TaskID']. '">';
echo $Iterate['TaskName'].' '.$Iterate['IterationNumber']. '</option>';
}
}
}
}
echo '</select>';
echo '</td>';
The problem is that i need to get all the values into an array to pass it to the view. but i only get the latest value which is the 2nd data that i retrieve in the database.
What you are doing wrong is :
return $this->load->view('MyToDoPhaseDropdown', $postlist);
You need to set the data in a variable to be accessible in view : http://codeigniter.com/user_guide/general/views.html
$data = array('title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message');
$this->load->view('MyToDoPhaseDropdown', $data);
And in view file : MyToDoPhaseDropdown.php
<html>
<?php
//Access them like so
echo $title.$heading.$message; ?>
</html>

PHP or JQUERY JSON Handling

I have a simple JSON StdClass Object from a PHP, and I wish to format it into a table/list/div and eliminate other keys and values in the process. The JSON looks like this:
stdClass Object (
[msc] => 150
[number] => 309
[status] => OK
[msc_mcc] => 652
[imsi] => 652010154107728
[mcc] => 652
[operator_country] => Botswana
[msc_operator_name] => MSC
[msc_operator_country] => Botswana
[msc_mnc] => 01
[mnc] => 01
[id] => 1072540715
[msc_location] =>
[operator_name] => MSC )
I have tried PHP and did make a table, but the problem is I need to pick certain values other that the whole body, and also I need to eliminate empty values
function print_nice($elem,$max_level=10,$print_nice_stack=array()){
if(is_array($elem) || is_object($elem)){
if(in_array($elem,$print_nice_stack,true)){
echo "<font color=red>RECURSION</font>";
return;
}
$print_nice_stack[]=&$elem;
if($max_level<1){
echo "<font color=red>nivel maximo alcanzado</font>";
return;
}
$max_level--;
echo "<table class='table table-bordered table-striped'>";
if(is_array($elem)){
echo '<tr><th colspan=2><strong><font><h3>Results, with love</h3></font></strong></th></tr>';
}else{
echo '<tr><th colspan=2 class=hdrs><strong>';
echo '<font color=white>OBJECT Type: '.get_class($elem).'</font></strong></th></tr>';
}
$color=0;
foreach($elem as $k => $v){
if($max_level%2){
$rgb=($color++%2)?"#f5f5f5":"#efeeee";
}else{
$rgb=($color++%2)?"#f5f5f5":"#efeeee";
}
echo '<tr><td valign="top" style="width:40px;background-color:'.$rgb.';">';
echo '<strong>'.$k."</strong></td><td>";
print_nice($v,$max_level,$print_nice_stack);
echo "</td></tr>";
}
echo "</table>";
return;
}
if($elem === null){
echo "<font color=green>NULL</font>";
}elseif($elem === 0){
echo "0";
}elseif($elem === true){
echo "<font color=green>TRUE</font>";
}elseif($elem === false){
echo "<font color=green>FALSE</font>";
}elseif($elem === ""){
echo "<font color=green>EMPTY STRING</font>";
}else{
echo str_replace("\n","<strong><font color=red>*</font></strong><br>\n",$elem);
}
}
get_object_vars() and in_array() may be helpful here
For example:
<?php
$object = json_decode($jsonstring);
?>
<table>
<?php
foreach (get_object_vars($object) as $k => $v)
{
if (in_array($k, array('msc', 'number', 'status')) && ! empty($v))
{
echo '<tr>';
echo "<td>{$k}</td><td>{$v}</td>";
echo '</tr>';
}
}
?>
</table>
Where $object is the name of your json_decoded variable
Edit:
Added a check for empty values too

multidimensional array

i have a multidimensional array like this
$role = array (
'Dashboard' => null,
'Students' =>
array (
'Admission' => array ( 0 => 'Entry' ,1 => 'Review' , 2 => 'Approved/Reject'
),
'Search' => null,
'AdvanceSearch' => null,
'Courses' => null
),
'HR' => array ('Settings' => null),
'Employee Management' => array ( 0 => 'Entry',1 => 'Association',2 => 'Search' ),
'Employee Attendance' => null,
'Payroll' => array (0 => 'Generate Pay Slip',1 => 'Payroll Run' , 2 => 'Payroll Revert',3 => 'View Pay Slips'),
'Finance' => null,
'More' => null);
and i want to print this array result in my html as
i am trying to do this by using recursion but unable to do that as DIV are not properly closed ..
here is the code that i am trying in my html
<?php
$child = 0;
function RecursiveWrite($array, $child ) {
$parent_array_size = count($array);
foreach ($array as $key => $vals) {
if(is_array($vals)){
$inner_array_size = count($vals);
echo "<div class='main clear'><input type='checkbox'/> ".$key." ";
RecursiveWrite($vals,$child);
}else{
$child = 0;
if(is_numeric($key)){
echo " <div class='left'> <input type='checkbox' class=''/> ".$vals." </div></div>";
}else{
echo "<div class='clear'><input type='checkbox'/> ".$key." </div></div>";
}
}
//
}
}
RecursiveWrite($role, $child);
?>
here is working code
How can i get this Any suggestion ... ?
Your Problem is missing closing div after recursion
Try this Function
function RecursiveWrite($array, $child )
{
$parent_array_size = count($array);
foreach ($array as $key => $vals)
{
if(is_array($vals))
{
$inner_array_size = count($vals);
echo "<div class='deep'><div class='extra'><input type='checkbox'/> ".$key."</div>";
RecursiveWrite($vals,$child);
echo "</div>";
}
else
{
if(is_numeric($key)){
echo "<span class='single'><input type='checkbox' class=''/> ".$vals."</span>";
}else{
echo "<div class='single'><input type='checkbox'/> ".$key." </div>";
}
}
}
}
Use This Css
<style type="text/css">
.parent {border: solid 1px #000;}
.parent div {border: solid 1px #000; margin:5px;}
.extra {border:0px !important;}
.single {margin-left:10px !important; border:0px !important;}
span.single {display:inline-block; margin-left:20px;}
</style>
Use this to call your Function
<div class="parent"><? RecursiveWrite($role, $child);?></div>
Put all the code Provided in one page with your array.
For better Codding standard you should Septate your style html and php for this try your luck ;)
You're not closing the div in the right places, when calling the recursion, right after ending the recursion you need to write the ending div:
open div
run recursion
close div
As well, you have two unnecessary div closing. Always make sure you open as many div as you close and vice versa. I've marked the places that needed to be changed in the code.
code:
<?php
$child = 0;
function RecursiveWrite($array, $child ) {
$parent_array_size = count($array);
foreach ($array as $key => $vals) {
if(is_array($vals)){
$inner_array_size = count($vals);
echo "<div class='main clear'><input type='checkbox'/> ".$key." ";
RecursiveWrite($vals,$child);
echo "</div>"; /* <== ADD THIS */
}else{
$child = 0;
if(is_numeric($key)){
echo " <div class='left'> <input type='checkbox' class=''/> ".$vals." </div>"; /* <== REMOVE EXTRA DIV */
}else{
echo "<div class='clear'><input type='checkbox'/> ".$key." </div>"; /* <== REMOVE EXTRA DIV */
}
}
//
}
}
RecursiveWrite($role, $child);
?>
you can find a working example at http://codepad.viper-7.com/507rLc

Categories