Codeigniter Update doesn't work - php

i'm having trouble getting my update to work. delete, view and add work fine.
this is my extraoptie_model:
function update($id, $extraOptie) {
$this->db->where('id', $id);
$this->db->update('extraOptie', $extraOptie);
}
my controller:
function update($id) {
// Check admin if not Acces Denied
$gebruiker = $this->session->userdata('gebruiker');
if ($gebruiker->accountLevel != "admin") {
$data['title'] = 'Acces Denied';
$partials = array('header' => 'main_header', 'content' => 'admin_noacces', 'footer' => 'main_footer');
$this->template->load('main_master', $partials, $data);
} else {
// prefill form values
$extraOptie = $this->extraoptie_model->get($id);
$data['id'] = $id;
$data['beschrijving'] = $extraOptie->beschrijving;
$data['actuelePrijs'] = $extraOptie->actuelePrijs;
$data['soort'] = $extraOptie->soort;
$data['aantalGangen'] = $extraOptie->aantalGangen;
$data['tabelNaam'] = $extraOptie->tabelNaam;
// set common properties
$data['title'] = 'Extra optie update';
$data['message'] = '';
$data['action'] = site_url('admin/extraoptie/updateExtraOptie/');
// load view
$partials = array('header' => 'main_header', 'content' => 'admin_extraoptieedit', 'footer' => 'main_footer');
$this->template->load('main_master', $partials, $data);
}
}
function updateExtraOptie() {
// Check admin if not Acces Denied
$gebruiker = $this->session->userdata('gebruiker');
if ($gebruiker->accountLevel != "admin") {
$data['title'] = 'Acces Denied';
$partials = array('header' => 'main_header', 'content' => 'admin_noacces', 'footer' => 'main_footer');
$this->template->load('main_master', $partials, $data);
} else {
// set common properties
$data['title'] = 'Update extra optie';
$data['action'] = site_url('admin/extraoptie/updateExtraOptie');
// save data
$id = $this->input->post('id');
$extraOptie = array('beschrijving' => $this->input->post('beschrijving'),
'actuelePrijs' => $this->input->post('actuelePrijs'),
'soort' => $this->input->post('soort'),
'aantalGangen' => $this->input->post('aantalGangen'),
'tabelNaam' => $this->input->post('tabelNaam'));
if ($extraOptie['aantalGangen'] == '') {
$extraOptie['aantalGangen'] = null;
}
if ($extraOptie['tabelNaam'] == '') {
$extraOptie['tabelNaam'] = null;
}
$this->extraoptie_model->update($id, $extraOptie);
// set user message
$data['message'] = '<div class="success">update success</div>';
// redirect to index
redirect('admin/extraoptie/index', 'refresh');
}
}
my view:
<table class='centered text'>
<form method="post" action="<?php echo $action; ?>">
<?php
$hidden = array('id' => $id);
form_hidden($hidden);
?>
<tr>
<td><?php echo form_label('Beschrijving:', 'beschrijving'); ?></td>
<td><?php echo form_textarea(array('name' => 'beschrijving', 'id' => 'beschrijving', 'value' => $beschrijving, 'cols' => '30', 'rows' => '5')); ?></td>
</tr>
<tr>
<td><?php echo form_label('Prijs:', 'prijs'); ?></td>
<td><?php echo form_input(array('name' => 'actuelePrijs', 'id' => 'actuelePrijs', 'value' => $actuelePrijs, 'size' => '10')); ?></td>
</tr>
<tr>
<td><?php echo form_label('Soort:', 'soort'); ?></td>
<td><?php echo form_input(array('name' => 'soort', 'id' => 'soort', 'value' => $soort, 'size' => '30')); ?></td>
</tr>
<tr>
<td><?php echo form_label('Aantal gangen:', 'aantalGangen'); ?></td>
<td><?php echo form_input(array('name' => 'aantalGangen', 'id' => 'aantalGangen', 'value' => $aantalGangen, 'size' => '10')); ?></td>
</tr>
<tr>
<td><?php echo form_label('Tabel naam:', 'tabelNaam'); ?></td>
<td><?php echo form_input(array('name' => 'tabelNaam', 'id' => 'tabelNaam', 'value' => $tabelNaam, 'size' => '30')); ?></td>
</tr>
<tr>
<td colspan='2' class='center'>
<?php echo form_submit('submit', 'Opslaan', 'id="opslaan"');; ?>
<?php echo form_button('annuleer', 'Annuleren', 'id="annuleer"'); ?>
<?php form_close(); ?>
</td>
</tr>
</table>
All help is welcome have been working on it for couple of hours and can't seem to find the problem.
Grtz Nella

possibly the issue arises from the fact that
you have a php form_close();
but do not have a php form_open();
not sure offhand how CI would react to a close without an open.

Do you have CSRF protection enabled? If so, you will need to either use form_open(), as steve has said, or add a hidden input with your csrf token such as:
<input type="hidden" name="<?php echo $this->security->get_csrf_hash();?>" value="<?php echo $this->security->get_csrf_token_name();?>"/>

Thank you both for your quick response!
I have found the error after staring at the code for another couple of hours together w/ a friend.
the problem was i didn't echo form_hidden($hidden) so no id was passed through to the update model.
<table class='centered text'>
<form method="post" action="<?php echo $action; ?>">
<?php
$hidden = array('id' => $id);
form_hidden($hidden);
?>
<tr>
so it had to be:
<table class='centered text'>
<form method="post" action="<?php echo $action; ?>">
<?php
$hidden = array('id' => $id);
echo form_hidden($hidden);
?>
<tr>

Related

Batch insert from a form in a foreach loop in code igniter

I have a view which contains a form that displays all the subjects from my database with input boxes for supplying a score for each subject and then clicking on a button to submit the data to the database in one fell swoop.
<?php echo form_open('teacher/submit_ca_score/'.$d->id); ?>
<table class="table table-bordered cell-text-middle" style="text-align: left">
<thead>
<tr>
<th class="w-10">S/N</th>
<th class="w-50">Subject</th>
<th class="w-15">CA Score</th>
</tr>
</thead>
<tbody>
<?php
$count = 1;
foreach ($subjects as $s) {
$query = $this->teacher_model->check_ca_score_exists($d->id, $s->subject); ?>
<tr>
<td><?php echo $count; ?></td>
<td><?php echo $s->subject; ?></td>
<td>
<div class="form-group">
<input type="hidden" name="subject[]" value="<?php echo $s->subject; ?>" />
</div>
</td>
</tr>
<?php $count++; ?>
<?php } ?>
</tbody>
</table>
<div class="form-group">
<button class="btn btn-success btn-lg">Submit</button>
</div>
<?php echo form_close() //submit_ca_score ?>
This is my controller:
public function submit_ca_score($id) {
$this->form_validation->set_rules('ca_score[]', 'CA Score', 'trim');
$subjects = $this->input->post('subject', TRUE);
$scores = $this->input->post('ca_score', TRUE);
$y = $this->common_model->get_student_details_by_id($id);
if ($this->form_validation->run()) {
$data = array();
foreach ($subjects as $key => $value) {
$row = array();
$row['admission_id'] = $y->admission_id;
$row['subject'] = $value;
$ca_score = "";
foreach ($scores as $key => $value) {
$ca_score = $value;
}
$row['ca_score'] = $ca_score;
$row['session'] = current_session;
$row['term'] = current_term;
$data[] = $row;
}
if ( ! empty($data) ) {
$this->teacher_model->batch_insert_ca_score($id, $data);
$this->session->set_flashdata('status_msg', "{$subject} CA score submitted successfully for {$y->first_name}");
} else {
$this->session->set_flashdata('status_msg_error', "Error submitting CA score!");
}
redirect($this->agent->referrer());
} else {
$this->produce_report($id); //form validation fails, reload page with errors
}
}
....and the model: Teacher_model
public function batch_insert_ca_score($id, $data = array()) {
$insert = $this->db->insert_batch('student_results', $data);
return $insert ? TRUE : FALSE;
}
The batch operation works, but the data from the ca_score field does not get picked. I know I'm doing something wrong but I just can't make out what it is. I have been trying this for hours, basically playing around but nothing seems to work. I just started experimenting with batch operation in code igniter. Can someone please point me to the right direction.
Try this :-
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name' ,
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
https://www.codeigniter.com/userguide2/database/active_record.html

update product details not working CodeIgniter

I'm making a fuction on the CodeIgniter framework so users are able to edit/update product detail information. But when I submit the form I get a blank page and the product isn't updated in my database. I couldn't find a mistake myself.
Here is my view file form (cadeaubewerken.php):
<table class="aanbieding-cadeau">
<form action="<?php echo base_url() . "KdGwController/update_product"; ?>" method="post">
<tr>
<h4>Cadeau naam</h4>
<td><?php echo form_input(array('id'=>'product_naam', 'name'=>'product_naam', 'value' => $product["product_naam"] , 'size'=>25));?></td>
<td><?php echo form_input(array('type'=>'hidden','id'=>'product_id', 'name'=>'product_id', 'value' => $product['product_id']));?>
</tr>
<tr>
<td><?php echo form_open_multipart('Product/upload'); ?> </td>
</tr>
<tr>
<td>
<h4>Kies een categorie</h4>
<select name="category_id">
<?php foreach (get_categories_h() as $category) :
if ($category->id == $product["category_id"]){
echo '<option value="'.$category->id .'" selected>' . $category->name . '</option>';
}else{
echo '<option value="'.$category->id .'">'.$category->name . '</option>';
}
endforeach; ?>
</select>
</td>
</tr>
<tr>
<td><h4>Ophaal plaats</h4><?php echo form_input(array('id'=>'ophaal_plaats', 'name'=>'ophaal_plaats', 'value' => $product["ophaal_plaats"], 'size'=>25));?></td>
<td><?php echo form_input(array('type'=>'hidden','id'=>'ophaal_plaats', 'name'=>'ophaal_plaats', 'value' => $product['ophaal_plaats']));?>
</tr>
<tr>
<td>
<div class="checkbox">
<label><input type="checkbox" value="">Gebruik adres van mijn account</label>
</div>
</td>
</tr>
<tr>
<td>
<h4>Huidig cadeau profiel foto</h4>
<img src="<?php echo base_url(); ?>upload/<?php echo $product['product_foto_thumb']; ?>" class="img-responsive">
</td>
</tr>
<tr>
<td>
<h4>Cadeau profiel foto veranderen</h4>
<input type="file" name="userfile"/>
</td>
</tr>
<tr>
<td><?php echo form_textarea(array('type'=>'textarea','id'=>'product_beschrijving', 'name'=>'product_beschrijving', 'value' =>$product['product_beschrijving'], 'size'=>25));?></td>
<td><?php echo form_input(array('type'=>'hidden','id'=>'product_beschrijving', 'name'=>'product_beschrijving', 'value' => $product['product_beschrijving']));?>
</tr>
<tr>
<td><input type="submit" class="btn btn-primary" name="submit" value="Cadeau bewerken!" /></td>
</tr>
</table>
</form>
This is my controller file (KdGwController.php):
<?php
class KdGwcontroller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Product_model');
$this->load->model('Update_product_model');
$this->load->helper(array('form', 'url'));
}
public function details_bewerken($product_id) {
//load the Product_model
$this->load->model('Product_model');
//call function getdata in de Product_model
$data['userdetail_list'] = $this->Product_model->getdata();
//get product details
$data['product'] = $this->Product_model->get_product_details($product_id);
//laad view
$data['main_content'] = 'cadeaubewerken';
$this->load->view('cadeaubewerken',$data);
}
public function update_product() {
$id= $this->input->post('product_id');
$data = array(
'product_naam' => $this->input->post('product_naam'),
'category_id' => $this->input->post('category_id'),
'ophaal_plaats' => $this->input->post('ophaal_plaats'),
);
}
}
And this is my model file : (Update_product_model.php):
<?php
class Update_product_model extends CI_Model {
function update_product($id,$data){
$this->db->where('product_id', $id);
$this->db->update('products', $data);
header ('location:https://kadokado-ferran10.c9users.io//AlleCadeausController');
}
}
?>
No need to add update in model.
Also, your controller update function should be like
public function update_product() {
$id= $this->input->post('product_id');
$data = array(
'product_naam' => $this->input->post('product_naam'),
'category_id' => $this->input->post('category_id'),
'ophaal_plaats' => $this->input->post('ophaal_plaats'),
);
// here I am assuming that `Product` is model
$this->Product->where($id);
$this->Product->update($data);
}
You have not call model function in your controller.
Change your controller update_product() function like this
public function update_product() {
$id= $this->input->post('product_id');
$data = array(
'product_naam' => $this->input->post('product_naam'),
'category_id' => $this->input->post('category_id'),
'ophaal_plaats' => $this->input->post('ophaal_plaats'),
);
$this->Update_product_model->update_product($id,$data);
}
You are not calling function update_product() of Update_product_model.php from KdGwController.php
Change this in your controller...
public function update_product() {
$id= $this->input->post('product_id');
$data = array(
'product_naam' => $this->input->post('product_naam'),
'category_id' => $this->input->post('category_id'),
'ophaal_plaats' => $this->input->post('ophaal_plaats'),
);
$this->Update_product_model->update_product($id,$data); // this line you missed
}

Invalid argument supplied for foreach() and Undefined property: stdClass::$title

I am new to codeigniter and I am trying to build a CMS by some tutorials on YouTube, but I am having a problem with updating/editing pages in admin area.
ERRORS:
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: helpers/form_helper.php
Line Number: 332
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$title
Filename: models/page_m.php
Line Number: 77
Controller page.php
class Page extends Admin_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('page_m');
}
public function index(){
//Fetch all pages
$this->data['pages'] = $this->page_m->get_with_parents();
// Load view
$this->data['subview']='admin/page/index';
$this->load->view('admin/_layout_main', $this->data);
}
public function edit($id = NULL){
// Fetch a page or set a new one
if ($id){
$this->data['page'] = $this->page_m->get($id);
count($this->data['page']) || $this->data['errors']='Page could not be found';
}
else{
$this->data['page'] = $this->page_m->get_new();
}
//Pages for dropdown
$this->data['pages_no_parents'] = $this->page_m->get_no_parents();
var_dump($this->data['pages_no_parents']);
//Set up the form
$rules = $this->page_m->rules;
$this->form_validation->set_rules($rules);
//Proccess the form
if ($this->form_validation->run() == TRUE){
$data = $this->page_m->array_from_post(array('title','slug','order','body', 'parent_id'));
$this->page_m->save($data, $id);
redirect('admin/page');
}
//Load the view
$this->data['subview'] = 'admin/page/edit';
$this->load->view('admin/_layout_main', $this->data);
}
public function _unique_slug($str){
// Do NOT validate if slug already exists
//UNLESS its the slug for the current page
$id = $this->uri->segment(5);
$this->db->where('slug', $this->input->post('slug'));
!$id || $this->db->where('id !=', $id);
$page = $this->page_m->get();
if (count($page)){
$this->form_validation->set_message('_unique_slug', '%s should be unique');
return FALSE;
}
return TRUE;
}}
Model page_m.php
class Page_m extends MY_Model
{
protected $_table_name = 'pages';
protected $_order_by = 'order';
public $rules = array(
'parent_id' => array(
'field' => 'parent_id',
'label' => 'Parent',
'rules' => 'trim|intval'
),
'title' => array(
'field' => 'title',
'label' => 'Title',
'rules' => 'trim|required|max_length[100]'
),
'slug' => array(
'field' => 'slug',
'label' => 'Slug',
'rules' => 'trim|required|max_length[100]|url_title|callback__unique_slug'
),
'order' => array(
'field' => 'order',
'label' => 'Order',
'rules' => 'trim|required'
),
'body' => array(
'field' => 'body',
'label' => 'Body',
'rules' => 'trim|required'
),
);
public function get_new()
{
$page = new stdClass();
$page->title = "";
$page->slug = "";
$page->order = "";
$page->body = "";
$page->parent_id = 0;
return $page;
}
public function delete($id)
{
//Delete a page
parent::delete($id);
//Reset parent ID for its children
$this->db->set(array('parent_id' =>0))->where('parent_id', $id)->update($this->_table_name);
}
public function get_with_parents($id = NULL, $single = FALSE){
$this->db->select('pages.*, p.slug as parent_slug, p.title as parent_title');
$this->db->join('pages as p', 'pages.parent_id=p.id', 'left');
return parent::get($id, $single);
}
public function get_no_parents()
{
// Fetch pages without parents
$this->db->select('id', 'title');
$this->db->where('parent_id',0);
$pages = parent::get();
// Return key => value pair array
$array = array(0 => 'No parent');
if (count($pages)){
foreach ($pages as $page){
$array[$page->id]=$page->title;
}
}
}}
View admin/page/edit.php
<h3><?php echo empty($page->id) ? 'Add a new page' : 'Edit page: '.$page->title; ?></h3>
<div class="modal-body">
<?php echo validation_errors(); ?>
<?php echo form_open(); ?>
<table class="table">
<tr>
<td>Parent</td>
<td><?php echo form_dropdown('parent_id', $pages_no_parents,
$this->input->post('parent_id') ? $this->input->post('parent_id') : $page->parent_id); ?></td>
</tr>
<tr>
<td>Title</td>
<td><?php echo form_input('title', set_value('title',$page->title)); ?></td>
</tr>
<tr>
<td>Slug</td>
<td><?php echo form_input('slug', set_value('slug', $page->slug)); ?></td>
</tr>
<tr>
<td>Order</td>
<td><?php echo form_input('order', set_value('order', $page->order)); ?></td>
</tr>
<tr>
<td>Body</td>
<td><?php echo form_textarea('body', set_value('body', $page->body)); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
</div>
View admin/page/index.php
<section>
<h2>Pages</h2>
<?php echo anchor('admin/page/edit' , '<i class="glyphicon glyphicon-plus"></i> Add a page'); ?>
<table class="table">
<thead>
<tr>
<th>Title</th>
<th>Parent</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php if (count($pages)): foreach ($pages as $page): ?>
<tr>
<td><?php echo anchor('admin/page/edit/' . $page->id, $page->title); ?></td>
<td><?php echo $page->parent_slug; ?></td>
<td><?php echo btn_edit('admin/page/edit/' . $page->id); ?></td>
<td><?php echo btn_delete('admin/page/delete/' . $page->id); ?></td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td class="col-sm-3"> We could not find any pages.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</section>
Thank You for your help.
I don't know your code error cause.
But general case is point out to #Abdulla Nilam.
For example.
Below simple code is error.because $values is null.
<?php
$values=null;
print_r($values);
foreach ($values as $value) {
print_r($value);
}
?>
PHP Warning: Invalid argument supplied for foreach() in /workspace/Main.php on line 6
I have found the error.
Clearly I wasn't getting a return array on my function.
public function get_no_parents()
{
// Fetch pages without parents
$this->db->select('id', 'title');
$this->db->where('parent_id', 0);
$pages = parent::get();
// Return key => value pair array
$array = array(0 => 'No parent');
if (count($pages)) {
foreach ($pages as $page) {
$array[$page->id] = $page->id;
//
}
}
return $array;
}

Looping through HTML table checked checkboxes using php

i have a similar thread using javascript but i found some problem and some bugs. so i changed to php
so far this is my code
if(!empty($_POST['check'])) {
foreach($_POST['check'] as $check) {
//get the html data beside the checked checkboxes
}
}else{
echo '<script language="javascript">';
echo 'alert("Nothing checked")';
echo '</script>';
}
and my stripped html code
<tr>
<td><?php echo $r['Name'] ?></td>
<td><?php echo $r['Age'] ?></td>
<td><?php echo $r['Address'] ?></td>
<td><input name="check[]" type="checkbox" ></td>
</tr>
i wan't to get the data on the same row where a checkbox is checked. please help me. thanks
You have to loop through the POST data, and assign $r[NAME] = VALUE
For the PHP code:
array $r;
foreach($_POST as $post=>$value) {
//get the html data beside the checked checkboxes
$r[ $post] = $value;
}
}
}else{
echo '<script language="javascript">';
echo 'alert("Nothing checked")';
echo '</script>';
}
Assuming that the HTML part your referring to is the result page
For the HTML:
<tr>
<td><?php echo $r['Name'] ?></td>
<td><?php echo $r['Age'] ?></td>
<td><?php echo $r['Address'] ?></td>
</tr>
First, lets add some data:
<?php
$data = [
'111' => [
'Name' => 'John',
'Age' => '25',
'Address' => 'Baker street, 11'
],
'222' => [
'Name' => 'Mary',
'Age' => '19',
'Address' => 'Elm street, 14'
],
'333' => [
'Name' => 'Nick',
'Age' => '23',
'Address' => '64th stree, 2'
]
];
?>
Output all data items and set checks from previous posted data:
<form method="POST">
<table>
<?php foreach($data as $id => $item): ?>
<tr>
<td><?= $item['Name'] ?></td>
<td><?= $item['Age'] ?></td>
<td><?= $item['Address'] ?></td>
<td><input name="check[]" type="checkbox" value="<?= $id; ?>"
<?php if (isset($_POST['check']) && in_array($id, $_POST['check'])): ?>
checked="checked"
<?php endif; ?>/></td>
</tr>
<?php endforeach; ?>
</table>
<input type="submit" />
</form>
<?php if (empty($_POST['check'])): ?>
<script>alert("Nothing checked");</script>
<?php endif; ?>
You'll get reloaded page with properly marked checkboxes after the form submission.

Codeigniter can't pass value to controller

i have views here
<?php echo form_open('c_kategorimaterial/tambah'); ?>
<table>
<tr>
<td>Kode Kategori Material / Jasa</td> //primary key of table
<td><?php $inkode=array('name' => 'kkmj', 'disabled' => 'disabled', 'value' => $nextval, 'class' => 'GUI'); echo form_input($inkode) ?></td>
<td class="error"> <?php echo form_error('kkmj'); ?></td>
//i make the form_input disabled, because the value is
//auto generated from the last ID of table in database
</tr>
<tr>
<td>Nama Material / Jasa</td>
<td><?php $innama=array('name' => 'nmj', 'class' => 'GUI'); echo form_input($innama) ?></td>
<td class="error"> <?php echo form_error('nmj'); ?></td>
</tr>
<tr>
<td></td>
<td><?php $intambah=array('name' =>'login','class' =>'button','value' => 'Tambah'); echo form_submit($intambah); echo nbs(); $inreset=array('name' =>'reset','class' =>'button','value' => 'Hapus'); echo form_reset($inreset); ?></td>
</tr>
<?php echo form_close(); ?>
and it pass the value to the controller
function tambah()
{
$id = $this->input->post('kkmj');
$nama = $this->input->post('nmj');
$this->form_validation->set_rules('nmj','Nama','trim|required|min_length[2]|max_length[20]|xss_clean');
if($this->form_validation->run() == false)
{
$lastval = $this->m_admin->getlastval('KKMJ','ms_kategori_material','kode_kategori_material_jasa');
$data['nextval'] = $this->m_admin->gencode('KKMJ',3,$lastval);
$data['title'] = 'QB Tambah Kategori Material';
$this->load->view('head',$data);
$this->load->view('content/add_kategori_material',$data);
}
else
{
echo 'id adalah '.$id.' namanya adalah '.$nama; //$id is not printed
}
}
and then i fill the second field with 'water' and click the button. my page showing blank white screen with a text id adalah namanya adalah water
how come the ID is not printed ? how do i resolve this ?
Disabled elements do not get posted when you submit a form. If you need a field with unchangeable value, try to set it as read-only instead of disabled.
Because the field is disabled.
Use readonly attribute.

Categories