Invalid argument supplied for foreach() Line 140 - codeigniter

Error ON 140 , invalid argument supplied for foreach() , i dont know what i have to do
MyController code :
if ($data['ms']['mspr_no'] != '') {
$mdpr = $this->input->post('mdpr');
foreach ($mdpr as $key => $value1) {
foreach ($mdpr[$key] as $idx => $value2) {
if ($mdpr['mdpr_mspd_no'][$idx] != '') {
$data['md'][$idx]['mdpr_no'] = $data['ms']['mspr_no'];
if ($key == 'mdpr_net') {
$data['md'][$idx][$key] = ftodouble($value2);
} else {
$data['md'][$idx][$key] = $value2;
}
}
}
}
}
My Form Promo view :
<?php
if ($action == 'view') {
if (isset($promo)) {
foreach ($promo as $value) { ?>
<tr>
<td><input type="text" name="mdpr[mdpr_mspd_no][]" class="form-control srstyle-ta-center mdpr_mspd_no" value="<?php echo $value['mdpr_mspd_no']; ?>" readonly /></td>
<td><input type="text" class="form-control msph_pl" value="<?php echo $value['msph_pl']; ?>" readonly/></td>
<td><input type="text" class="form-control msph_hjkk_net" value="<?php echo $value['msph_hjkk_net']; ?>" readonly/></td>
<td><input type="text" class="form-control msph_hjkj_net" value="<?php echo $value['msph_hjkj_net']; ?>" readonly/></td>
<td><input type="text" name="mdpr[mdpr_net][]" class="form-control mdpr_net srstyle-ta-right auto-numeric" value="<?php echo $value['mdpr_net']; ?>" readonly/></td>
</tr><?php
}
}
}
?>
Thanks

“Warning: Invalid argument supplied for
foreach() ”
Its because of either null or false or argument is not array
foreach($mdpr as $key => $value1){
^
see var_dump($mdpr),
$mdpr is either null or false or not array you get above error
So what you can do is
$mdpr = $this->input->post('mdpr');
if(is_array($mdpr))
{
foreach($mdpr as $key => $value1)
{
// your remaining code goes here
}
}else
{
echo 'Bad data posted';
}
We can regenerate this error like this for example
$ php -r 'foreach(null as $e){}'
PHP Warning: Invalid argument supplied for foreach() in Command line code on line 1
/*false OR FALSE*/
$ php -r 'foreach(false as $e){}'
PHP Warning: Invalid argument supplied for foreach() in Command line code on line 1
/* Not array */
$ php -r 'foreach("somestring" as $e){}'
PHP Warning: Invalid argument supplied for foreach() in Command line code on line 1
I see OP made an edit - Line No : 140

Use a if(is_array()) to validate that is a array to be looping.

Related

Severity: Notice Message: Undefined variable: questions Filename: views/quiz.php

**view**
<?php foreach($questions as $row){ ?>
<?php $ans_array = array($row->choice1,$row->choice2,$row->choice3,$row->answer);
shuffle($ans_array);?>
<p><?=$row->quizID?>.<?=$row->question?></p>
<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[0]?>"> <?=$ans_array[0]?><br>
<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[1]?>"> <?=$ans_array[1]?><br>
<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[2]?>"> <?=$ans_array[2]?><br>
<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[3]?>"> <?=$ans_array[3]?><br>
<?php } ?>
</div>
controller
public function quest ()
{
$this->Model_students;
$this->data['questions']=$this->Model_students->quest();
$this->load->view('quest',$this->data);
}
public function quiz ()
{
$this->load->view('quiz');
}
model
public function quest()
{
$this->db->select("quizID,question,choice1,choice2,choice3,answer");
$this->db->from("quiz");
$query = $this->db->get();
return $query->result();
$num_data_returned = $query->num_rows;
if ($num_data_returned < 1)
{
echo "there is no data in the db";
exit();
}
}
after submitting this i get 2 errors;
1. Severity: Notice
Message: Undefined variable: questions
Filename: views/quiz.php
Line Number: 14
2.everity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/quiz.php
Line Number: 14
Remove $this
$data['questions']=$this->Model_students->quest();
$this->load->view('quest',$data);

Prevent duplicate entry in database Codeigniter

I would like to know how to prevent my upload function to insert duplicate entries into the database by using the uid.
public function upload(){
if(!empty($_FILES['uploaded_file']))
{
$path = FCPATH . "/file_attachments/signature_file/";
$path = $path . basename( $_FILES['uploaded_file']['name']);
$base64 = base64_encode(file_get_contents($_FILES['uploaded_file']['tmp_name']));
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path))
{
$data = array (
'uid' => $this->user->get_uid(),
'image' => $base64,
'name' => basename( $_FILES['uploaded_file']['name']),
);
$this->load->database('employee');
$this->db->insert('signatures', $data);
// echo "The file ". basename( $_FILES['uploaded_file']['name']).
// " has been uploaded";
$alert = "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
}
else
{
// echo "There was an error uploading the file, please try again!";
$alert ="There was an error uploading the file, please try again!";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
}
}
}
Here's my view file. I haven't got the time to edit the unnecessary things in here. The problem is still that if it got duplicate entries the database error still shows up and that is what I'm preventing to do so. Cheers!
<div class="bod">
<div class="insta">
<form enctype="multipart/form-data" style="padding-top: 10px" name="exit_form" method="post" action="<?= base_url() ?>signature_uploader/upload">
<input type="hidden" name="uid" value="<?= $agent->get_uid() ?>" />
<input type="hidden" name="gid" value="<?= $agent->get_gid() ?>" />
<input type="hidden" name="fname" value="<?= $agent->get_fname() ?>" />
<input type="hidden" name="lname" value="<?= $agent->get_lname() ?>" />
<div style="text-align: center; font-size: 25pt; margin-bottom: 15px">Signature Uploader</div>
<table width="105%">
<tr>
<td width="40%"><strong>Name: </strong><input class="textinput" disabled="disabled" type="text" name="full_name" id="textfield3" size="35" value="<?= $agent->get_fullName() ?>" /></td>
<tr/>
<tr>
<td><label>Upload Image File:</label><br /> <input name="uploaded_file" type="file" accept=".png" required/>
</tr>
<table/>
<br />
<input type="submit" value="Submit" class="button1" />
</form>
<br/>
</div>
You can use from Codeigniter form validation to prevent from duplicate entry:
at first you must get the uid in the form view like this:
<input type="hidden" name="uid" value="<?php echo $this->user->get_uid() ?>">
and then in your controller:
public function upload(){
if(!empty($_FILES['uploaded_file']))
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('uid', 'UID', 'is_unique[signatures.uid]');
if ($this->form_validation->run() == FALSE)
{
// Your Code if the uid is duplicate
$alert ="Could't upload because of duplicate entry!";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
}
else
{
// Your Code if the uid is unique
$path = FCPATH . "/file_attachments/signature_file/";
$path = $path . basename( $_FILES['uploaded_file']['name']);
$base64 = base64_encode(file_get_contents($_FILES['uploaded_file']['tmp_name']));
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
$data = array (
'uid' => $this->input->post('uid'),
'image' => $base64,
'name' => basename( $_FILES['uploaded_file']['name']),
);
$this->load->database('employee');
$this->db->insert('signatures', $data);
// echo "The file ". basename( $_FILES['uploaded_file']['name']).
// " has been uploaded";
$alert = "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
} else{
// echo "There was an error uploading the file, please try again!";
$alert ="There was an error uploading the file, please try again!";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
}
}
}
}
Either you can check weather such file exists or not, but normally while creating a code which uploads file, has a function which will generate unique name for each file that we upload. So in such cases it will have duplicate entries with different name.
Only way i see is to create a function that will check weather the file name already exists in database.

submit multiple inputs within a forloop in codeigniter

My code is to fetch questions of users saved in the database by a foreach loop and let the admin answer each question and save the answer of each question after checking of validation rules in the database , Here we go :
Model is :
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result();
}
My view is:
foreach ($questions as $id => $row) :
?>
<?php
echo "<h5>".$row->question;
echo "<br>";
echo "from : ".$row->user_name."</h5>";
echo date('Y-m-d H:i');
echo "<br>";
$q_no='save'.$row->id;
$ans_no='answer'.$row->id;
echo "<h4> Answer:</h4>";
echo form_open('control_panel');
?>
<textarea name='<?php echo 'answer'.$row->id; ?>' value="set_value('<?php echo 'answer'.$row->id; ?>')" class='form-control' rows='3'> </textarea>
<input type='hidden' name='<?php echo $q_no ; ?>' value='<?php echo $q_no; ?>' />
<input type='hidden' name='<?php echo $ans_no ; ?>' value='<?php echo $ans_no ; ?>' />
<?php
echo form_error($ans_no);
echo "
<div class='form-group'>
<div >
<label class='checkbox-inline'>
<input type='checkbox' name='add_faq' value='yes' />
Adding to FAQ page .
</label>
</div>
</div>
<p>";
?>
<input type='submit' name='<?php echo 'save'.$row->id; ?>' value='<?php echo 'save'.$row->id; ?>' class='btn btn-success btn-md'/>
<?php
echo 'answer'.$row->id;
?>
<hr>
<?php endforeach; ?>
and my controller is :
$this->load->model('control_panel');
$data['questions']=$this->control_panel->get_questions();
$data['no_of_questions']=count($data['questions']);
if($this->input->post($q_no))
{
$this->form_validation->set_rules($ans_no,'Answer','required|xss_clean');
if($this->form_validation->run())
{
/* code to insert answer in database */
}
}
of course it did not work with me :
i get errors :
Severity: Notice
Message: Undefined variable: q_no
i do not know how to fix it
I am using codeigniter as i said in the headline.
In your controller on your post() you have a variable called q_no you need to set variable that's why not picking it up.
I do not think name="" in input can have php code I think it has to be text only.
Also would be best to add for each in controller and the call it into view.
Please make sure on controller you do some thing like
$q_no = $this->input->post('q_no');
$ans_no = $this->input->post('ans_no');
Below is how I most likely would do lay out
For each Example On Controller
$this->load->model('control_panel');
$data['no_of_questions'] = $this->db->count_all('my_table');
$data['questions'] = array();
$results = $this->control_panel->get_questions();
foreach ($results as $result) {
$data['questions'][] = array(
'question_id' => $result['question_id'],
'q_no' => $result['q_no'],
'ans_no' => $result['ans_no']
);
}
//Then validation
$this->load->library('form_validation');
$this->form_validation->set_rules('q_no', '', 'required');
$this->form_validation->set_rules('ans_no', '', 'required');
if ($this->input->post('q_no')) { // Would Not Do It This Way
if ($this->form_validation->run() == TRUE) {
// Run Database Insert / Update
// Redirect or load same view
} else {
// Run False
$this->load->view('your view', $data);
}
}
Example On View
<?php foreach ($questions as $question) {?>
<input type="text" name="id" value="<?php echo $question['question_id'];?>"/>
<input type="text" name="q_no" value"<?php echo $question['q_no'];?>"/>
<input type="text"name="a_no" value="<?php echo $question['a_no'];?>"/>
<?php }?>
Model
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result_array();
}

Showing input field blank if the date value from database is 0000--00--00 00:00:00 in codeigniter

$_POST["s_plan"] = $data['tasks_detail'][0]->nt_start_date;
$_POST["e_plan"] = $data['tasks_detail'][0]->nt_end_date;
$_POST["s_due"] = $data['tasks_detail'][0]->nt_start_due_date;
$_POST["e_due"] = $data['tasks_detail'][0]->nt_end_due_date;
This is how i am passing values from my controller for 4 date fields in view code below:
<input type="text" name="s_plan" id="s_plan" value="<?php echo set_value('s_plan');?>" class="datepicker" />
<input type="text" name="s_due" id="s_due" value="<?php echo set_value('s_due');?>" class="datepicker" />
<input type="text" name="e_plan" id="e_plan" value="<?php echo set_value('e_plan');?>" class="datepicker" />
<input type="text" name="e_due" id="e_due" value="<?php echo set_value('e_due');?>" class="datepicker" />
Now every thing is working but i want that if in database the values of these date fields are 0000--00--00 00:00:00. that it should not set_value on my form. or may be echo "";
Updated:
$_POST["s_plan"] = ($data['tasks_detail'][0]->nt_start_date != "0000-00-00") ? $data['tasks_detail'][0]->nt_start_date : "";
$_POST["e_plan"] = ($data['tasks_detail'][0]->nt_end_date != "0000-00-00") ? $data['tasks_detail'][0]->nt_end_date : "";
$_POST["s_due"] = ($data['tasks_detail'][0]->nt_start_due_date != "0000-00-00") ? $data['tasks_detail'][0]->nt_start_due_date : "";
$_POST["e_due"] = ($data['tasks_detail'][0]->nt_end_due_date != "0000-00-00") ? $data['tasks_detail'][0]->nt_end_due_date : "";
Now when i put condition in my controller as above. Now nothing is being shown in view even if the date field has a date value
[I wrote a Function for this the other Day:]
function ctd($datetime, $format=false, $displayzero=false){
$timestamp = strtotime($datetime);
if(!$format){
$format = 'd.m.Y'; // <---------- your default Date-Format
}
if($timestamp > strtotime('0000-00-00 00:00:00')){
return date($format, $timestamp);
}else{
if($displayzero){
return str_replace(1, 0, date($format, strtotime('0001-01-01 00:00:00')));
}else{
return false;
}
}
}

Updating one data on datagrid using checkbox codeigniter

i have some issue when i updating every single or one data using checkbox. i want to do is to update only the selected checkbox updated. How do I stop the foreach from running if a checkbox has not been checked.
this is my model
function save_cargo_details() {
$data = array();
$waybillno = $this->input->post('waybillno');
$quantity = $this->input->post('quantity');
$waybilldate = $this->input->post('waybilldate');
$declared_value = $this->input->post('declared_value');
$consignee = $this->input->post('consignee');
$count = count($waybillno);
if(empty($waybillno)){
}else{
for ($i = 0; $i < $count; $i++) {
$data = array(
'waybillno' => $waybillno[$i],
'quantity' => $quantity[$i],
'waybilldate' => $waybilldate[$i],
'declared_value' => $declared_value[$i],
'consignee' => $consignee[$i],
);
// SUBRACT REMAINING_QUANTITY //
$this->db->select('wd.remaining_qty');
$this->db->where('wd.waybillno',$waybillno[$i]);
$this->db->from(self::WAYBILL_DETAILS_TABLE. " as wd");
$query = $this->db->get()->row();
$qty = $query->remaining_qty;
$remaining = abs($data['quantity'] - $qty);
$this->db->where('waybillno',$waybillno[$i]);
$this->db->set('remaining_qty',$remaining);
$this->db->update(self::WAYBILL_DETAILS_TABLE);
// INSERT DATA //
$this->db->insert('sys_cargodetails', $data);
$this->session->set_flashdata('success', '<p id="success_message">Record has been successfully saved.</p>');
}
}
}
this is my controller
public function create_cargo_manifest(){
$core_model = new Core_m;
$core_model->save_cargo_details();
redirect('core/cargo_lookup/');
}
this is my view
<?php foreach($waybill_header as $waybill_header) { ?>
<?php echo form_open('core/create_cargo_manifest'); ?>
<tr style="text-align: center;">
<td><input type="checkbox" name="waybillno[]" 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->remaining_qty; ?>" name="quantity[]">
<input type="hidden" value="<?php echo $waybill_header->declared_value; ?>" name="declared_value[]">
<input type="hidden" value="<?php echo $waybill_header->consignee; ?>" name="consignee[]">
</td>
</tr>
<?php } ?>
You can give an extra field in the database for the checkbox.If the check box is checked it takes 1 as the value and if unchecked 0 as the value.Give the default value as per your requirement.If you want every checkbox to be checked give 1 as default else otherwise.Then you will just need to put a condition before foreach loop,i.e. if value of checkbox is 1 run the foreach loop else not.

Resources