I need to insert data from multiple rows. And each of these rows has an array on the third column, Class. I want to insert it such that the data in the database will look like that shown on the MYSQL screenshot below. The error I am having is that the class column inserts a duplicate data instead..
<script>
var rowCount = 1;
function addMoreRows(frm){
rowCount ++;
var inputer = '<div class="row rowCount'+rowCount+'"><div class="col-md-3"> <div class="form-group"><input type="text" class="form-control" name="subject[]"></div></div><div class="col-md-3"> <div class="form-group"><input type="text" class="form-control" name="highest_mark_obtainable[]"></div></div><div class="col-md-3"><div class="form-group"><select class="form-control" name="class[]"><?php foreach($class_rows as $class_row){echo'<option value="'.$class_row['group'].'">'.$class_row['class'].'</option>';}?></select></div></div><div class="col-md-2"><button class="btn btn-danger" onclick="removeRow('+rowCount+')"><i class="fa fa-minus"></i> Remove row</button></div></div>';
$('.gra-grp-row').append(inputer);
}
function removeRow(removeNum){
$('.rowCount'+removeNum).remove();
}
</script>
Below is my model
public function create_subject(){
$subject = $this->input->post('subject');
$highest_mark_obtainable = $this->input->post('highest_mark_obtainable');
$classes[] = implode(',', $this->input->post('class'));
for($i = 0; $i < count($subject); $i++){
for($p = 0; $p < count($classes); $p++){
$new_subject = array(
'subject' => $subject[$i],
'highest_mark_obtainable' => $highest_mark_obtainable[$i],
'class' => $classes[$p],
'username' => $this->session->userdata('username')
);
$this->db->insert('subject', $new_subject);
}
}
return TRUE;
}
}
Below is my controller
public function create_subject(){
$this->output->enable_profiler(TRUE);
if($this->input->is_ajax_request() && $this->input->post('ajax') == 1){
$this->form_validation->set_rules('subject[]', 'Subject',
'trim|required|min_length[2]|max_length[50]');
$this->form_validation->set_rules('highest_mark_obtainable[]', 'Maximum `enter code here`marks obtainable', 'trim|required|numeric');
$this->form_validation->set_rules('class[]', 'Class', 'trim|required');
if ($this->form_validation->run() == FALSE) {
$this->output->set_status_header('400');
echo '<span class="admin_validation_error" `enter code here`style="color:#ff0000">'.validation_errors().'</span>';
} else {
if($this->subject_model->create_subject() == true){
echo '<span class="validation_success" style="color:green; font- weight:bolder">Well done! Subject(s) successfully created.</span>';
}
}
}else{
redirect('errors/not_found');
}
} `
BELOW IS THE FORM
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="Subject">Subject<span class="asterix"> *</span></label>
<input type="text" class="form-control" name="subject[]" id="" placeholder="Mathematics" value="">
</div>
</div><!--Subject-->
<div class="col-md-4">
<div class="form-group">
<label for="Highest mark obtainable">Maximum marks obtainable<span
`class="asterix"> *</span></label>
<input type="text" class="form-control" name="highest_mark_obtainable[]"
id="" placeholder="100" value="">
</div>
</div><!--Highest mark obtainable-->
<div class="col-md-3">
<div class="form-group">
<label for="Class">Classes that do subject<span class="asterix"> *</span>
</label> <select class="form-control select2subjects" name="class[]" ` `multiple="multiple" style="width:100%">
<?php foreach ($class_rows as $class){
echo '<option value="'.$class['class'].'">'.$class['class'].'</option>';
}
?>
</select>
</div>
</div><!--class associated with subject-->
<div class="col-md-2">
</div>
</div>
Im not sure if your using Codeigniter 3 and im not sure if this function is exclusive to Codeginiter 3
You could use the function in the query builder $this->db->insert_batch()
$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);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
A further explanation here:
https://codeigniter.com/user_guide/database/query_builder.html?highlight=query%20builder#inserting-data
$classes = $this->input->post('class');
for($i = 0; $i < count($subject); $i++) {
$new_subject = array(
'subject' => $subject[$i],
'highest_mark_obtainable' => $highest_mark_obtainable[$i],
'class' => implode(',', $classes[$i]),
'username' => $this->session->userdata('username')
);
$this->db->insert('subject', $new_subject);
}
Related
I'm try to make crud with upload file but somehow it's keep return FALSE but i don't know what's wwrong with my code if i var_dump($data) before condition upload it's show the name of my image but if i var_dump($uploads) it's keep show false
This is my controller
public function saveReimburse()
{
validate_submitted_data(array(
'nama' => 'required',
'category_reimburse_id' => 'required',
'amount' => 'required|numeric',
'date_reimburse' => 'required',
));
// data
$data = [
'nama' => $this->input->post('nama'),
'category_reimburse_id' => $this->input->post('category_reimburse_id'),
'amount' => $this->input->post('amount'),
'date_reimburse' => $this->input->post('date_reimburse'),
'photo' => $_FILES['photo'],
];
// condition
$date = date('Y-m-d');
$date = strtotime($date);
$date = strtotime('-7 day', $date);
if ($data['date_reimburse'] < date('Y-m-d', $date)) {
echo json_encode(array('succes' => FALSE, 'message' => 'Max Reimburse was 1 week ago'));
} else {
if ($data['photo'] = "") {
} else {
$config = [
'upload_path' => './assets/reimburse',
'allowed_types' => 'jpg|png|gif',
'overwrite' => TRUE
];
$this->load->library('upload', $config);
$upload = $this->upload->do_upload('photo');
var_dump($upload);exit;
if (!$upload) {
json_encode(array('success' => FALSE, 'message' => 'Failed Upload'));
redirect('Reimburse/index', 'refresh');
} else {
$this->upload->data('file_name');
$save = $this->reimburseModel->saveReimburse('reimburse', $data);
var_dump($data);exit;
if (!$save) {
echo json_encode(array('success' => FALSE, 'message' => 'Failed to reccord'));
} else {
redirect('Reimburse/index', 'refresh');
echo json_encode(array('success' => TRUE, 'message' => 'Reimburse Success'));
}
}
}
}
}
and this my model
function saveReimburse($table,$data)
{
$this->load->database('default', TRUE);
if(!$this->db->insert($table,$data))
return FALSE;
$data["id"] = $this->db->insert_id();
return (object) $data;
}
This is my input code
<?php echo form_open_multipart(get_uri("Reimburses/saveReimburse"), array("id" => "formReimburse", "class" => "general-form", "role" => "form")); ?>
<div id="expense-dropzone" class="post-dropzone">
<div class="modal-body clearfix">
<!-- <form action =" " method='POST'> -->
<div class="form-group">
<label for="Nama">Nama</label>
<input type="text" class="form-control" id="nama" name="nama" placeholder="Nama">
</div>
<div class="form-group">
<label for="category_reimburse_id">Category</label>
<select class="form-control form-control-lg" name="category_reimburse_id">
<option value ="">-</option>
<?php
foreach($category as $ct){?>
<option value ="<?php echo $ct->id ?>"><?php echo $ct->category ?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<label for="amount">Amount</label>
<input type="text" class="form-control" id="amount" name="amount" placeholder="Amount">
</div>
<div class="form-group">
<label for="date_reimburse">Date</label>
<input type="date" class="form-control" id="date_reimburse" name="date_reimburse" value='<?php echo date('Y-m-d') ?>'>
</div>
<div class="form-group">
<div class="form-group">
<label for="photo">Input Photo</label>
<input type="file" class="form-control-file" id="photo" name ="photo">
</div>
</div>
<div class="float-right">
<button type="cancel" class="btn btn-warning ">Cancel</button>
<button type="submit" class="btn btn-primary ">Submit</button>
</div>
<!-- </form> -->
</div>
</div>
<?php echo form_close() ?>
Check the error using the error function
print_r($this->upload->display_errors());
Try adding bellow upload path
'upload_path' => '../assets/reimburse';
Put one / after reimburse like "./assets/reimburse/" can solve problem may be and assets folder in root directory
I am new to CodeIgniter, I carried out an e-commerce project left by the former developer. The case is that the category data is not inserting into my table.
The code is very long in both controller and model but I cut it out and posted only the necessary part of it.
This is my controller.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Category extends Admin_Controller {
public function create()
{
/* Breadcrumbs */
$this->breadcrumbs->unshift(2, "New Category" , 'admin/category/create');
$this->data['breadcrumb'] = $this->breadcrumbs->show();
/* Variables */
$tables = $this->config->item('tables', 'ion_auth');
/* Validate form input */
$this->form_validation->set_rules('cat_name', 'Category Name', 'trim|required');
if ($this->form_validation->run() == TRUE)
{
$config['upload_path'] = './assets/uploads/category/';
//die(var_dump(is_dir($config['upload_path'])));
$config['allowed_types'] = 'png,jpeg';
$config['max_size'] = '1024';
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "icon";
if ( ! $this->upload->do_upload($img))
{
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('admin/category');
}
else
{
$data=$this->upload->data();
$file = array('file_name' => $data['file_name'] );
$data = array('upload_data' => $this->upload->data());
$photo = base_url().'assets/uploads/category/'.$file['file_name'];
$data = array(
'category_name' => $this->input->post('cat_name'),
'category_photo' => $photo,
'category_description' => $this->input->post('cat_desc')
);
$this->category_model->insertcategory($data);
//$this->ion_auth->messages()
$this->session->set_flashdata('message', "Successfully inserted!");
redirect('admin/category', 'refresh');
}
}
else
{
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
/* Load Template */
$this->template->admin_render('admin/category/create', $this->data);
}
}
This is my model.
class Category_model extends CI_Model
{
function insertcategory($data) {
$query = $this->db->insert('category', $data);
if ($query) {
return true;
} else {
return false;
}
}
This is my form.
<div class="box-body">
<span style="color:red"><?php echo $message;?></span>
<?php echo form_open_multipart(current_url(), array('class' => 'form-horizontal', 'id' => 'form-create_user')); ?>
<div class="form-group">
<span class="col-sm-2 control-label">Category Name</span>
<div class="col-sm-10">
<input type="text" class="form-control" id="cat_name" placeholder="Category Name" name="cat_name" required>
</div>
</div>
<div class="form-group">
<span class="col-sm-2 control-label">Category Description</span>
<div class="col-sm-10">
<input type="text" class="form-control" id="cat_desc" placeholder="Description" name="cat_desc" >
</div>
</div>
<div class="form-group">
<span class="col-sm-2 control-label">Category Icon</span>
<div class="col-sm-10">
<input class="input-file uniform_on" id="icon" name="icon" type="file">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="btn-group">
<?php echo form_button(array('type' => 'submit', 'class' => 'btn btn-primary btn-flat', 'content' => lang('actions_submit'))); ?>
<?php echo form_button(array('type' => 'reset', 'class' => 'btn btn-warning btn-flat', 'content' => lang('actions_reset'))); ?>
<?php echo anchor('admin/category', lang('actions_cancel'), array('class' => 'btn btn-default btn-flat')); ?>
</div>
</div>
</div>
<?php echo form_close();?>
</div>
Could you please replace $img = "icon"; with $img = $this->input->post('icon');
Please check with the above data.
Also please post the error message you are getting.
I am trying to upload two images in database at once submit attempt from single form that have two different file input fields.
I tried but its not working when i try to show result using print_r it gives a single file name for both input fields. How can i do it perfectly in codeigniter. please help for your reference i am uploading my code. you if any error please let me know.
HTML Form Code
<form id="form_edit" method="post" action="<?php echo base_url(" admin/aboutus/update/".$aboutus->id); ?>" enctype="multipart/form-data" accept-charset="utf-8">
<div class="form-group row">
<div class="col-md-4 col-xs-4">
<input type="text" name="imgtitle" title="About Us Image Title" class="form-control input-sm" value="<?php echo set_value('imgtitle', $aboutus->imgtitle); ?>" placeholder="Image Title" required="required">
<?php echo form_textarea(['rows'=>'15', 'name'=>'imgdetail','title'=>'About Us Image Description','class'=>'form-control mptop input-sm','required'=>'required','value'=> set_value('detail', $aboutus->imgdetail)]); ?>
<input type="file" name="img" title="About Us Image" class="form-control input-sm">
</div>
<div class="col-md-4 col-xs-4">
<input type="text" title="About Us Title" class="form-control input-sm" name="title" value="<?php echo set_value('title', $aboutus->title); ?>" placeholder="Type left side title of about us of maximum 15 characters" required="required">
<?php echo form_textarea(['rows'=>'15', 'name'=>'detail','title'=>"About Us Detail",'class'=>'form-control mptop input-sm mptop','required'=>'required','value'=> set_value('detail', $aboutus->detail)]); ?>
</div>
<div class="col-md-4 col-xs-4">
<input type="text" name="img_2title" title="About Us Image Title" class="form-control input-sm" value="<?php echo set_value('imgtitle', $aboutus->img_2title); ?>" placeholder="Image Title" required="required">
<?php echo form_textarea(['rows'=>'15', 'name'=>'img_2detail','title'=>'About Us Image Description','class'=>'form-control mptop input-sm','required'=>'required','value'=> set_value('detail', $aboutus->img_2detail)]); ?>
<input type="file" name="img_2" title="About Us Image" class="form-control input-sm">
<!-- id="detail" -->
</div>
</div>
<div class="form-group row">
<div class="col-md-12 col-xs-12 mptop rmzero rpZero">
<div class="btn-group pull-right text-right">
<i class="fa fa-arrow-left"></i> Back
<!-- <i class="fa fa-search"></i> Preview -->
<button type="submit" class="btn btn-success btn-sm" name="submit" id="save"><i class="fa fa-save"></i> Save</button>
</div>
</div>
</div>
</form>
My Codeigniter Control Code
public function update($id)
{
$res = array();
//form field validation rules
$this->form_validation->set_rules('title', 'Title', 'required|max_length[15]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('detail', 'Detail', 'required|max_length[2000]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('imgtitle', 'Image Title', 'required|max_length[15]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('imgdetail', 'Image Description', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('img_2title', 'Second Image Title', 'required|max_length[15]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('img_2detail', 'Second Image Description', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$config['upload_path'] = 'fassets/images/aboutus';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
//$config['file_name'] = $_FILES['img']['name'];
$config['overwrite'] = TRUE;
//Load upload library and initialize configuration
$this->load->library('upload', $config);
// echo $image_path; exit;
if((!$this->upload->do_upload('img')) && (!$this->upload->do_upload('img_2')))
{
$userData = array(
'title' => $this->input->post('title'),
'detail' => $this->input->post('detail'),
'imgtitle' => $this->input->post('imgtitle'),
'imgdetail' => $this->input->post('imgdetail'),
'img_2title' => $this->input->post('img_2title'),
'img_2detail' => $this->input->post('img_2detail')
);
//Pass user data to model
$insertUserData = $this->AboutusModel->update($userData, $id);
}
else
{
$userData = array(
'title' => $this->input->post('title'),
'detail' => $this->input->post('detail'),
'imgtitle' => $this->input->post('imgtitle'),
'imgdetail' => $this->input->post('imgdetail'),
'img_2title' => $this->input->post('img_2title'),
'img_2detail' => $this->input->post('img_2detail'),
'img' => $this->upload->data('file_name'),
'img_2' => $this->upload->data('file_name')
);
echo "<pre>";
print_r($userData);
exit;
//Pass user data to model
$insertUserData = $this->AboutusModel->update($userData, $id);
}
//Storing insertion status message.
if($insertUserData){
$res = array(
'mes' => 'text-success',
'msg' => "Record has been saved successfully.",
);
echo json_encode($res);
} else {
$res = array(
'mes' => 'text-danger',
'msg' => "Oops! Something went wrong.",
);
echo json_encode($res);
}
}
With $this->upload->data('file_name'), you are getting only the last uploaded file name. You're missing the first one. To solve this simple issue, store both filenames in variables to use after both files have successfully been uploaded.
Before:
$this->load->library('upload', $config);
Add:
$img1 = $_FILES['img']['name'];
$img2 = $_FILES['img_2']['name'];
Replace:
'img' => $this->upload->data('file_name'),
'img_2' => $this->upload->data('file_name')
With:
'img' => $img1,
'img_2' => $img2
Another Issue:
In your current code, if your first upload succeeds the second will fail. To prevent that.
Replace:
if((!$this->upload->do_upload('img')) && (!$this->upload->do_upload('img_2')))
With:
$upload1_ok = $this->upload->do_upload('img');
$upload2_ok = $this->upload->do_upload('img_2');
if($upload1_ok == false && $upload2_ok == false)
I have the following error message while updating my records in database
Severity: Notice
Message: Array to string conversion
Filename: database/DB_query_builder.php
Line Number: 662
Backtrace:
File: C:\xampp\htdocs\Site\application\models\class_model.php Line: 48
Function: where
File: C:\xampp\htdocs\Site\application\controllers\class_con.php Line:
107 Function: update
File: C:\xampp\htdocs\Site\index.php Line: 292 Function: require_once
here my controller
function edit($id)
{
$rules = [
[
'field' => 'classname',
'label' => 'Class Name',
'rules' => 'trim|required'
],
[
'field' => 'inchargename',
'label' => 'Incharge Name',
'rules' => 'trim|required'
],
[
'field' => 'classstrength',
'label' => 'Class Strength',
'rules' => 'trim|required'
]
];
$this->form_validation->set_rules($rules);
$class = $this->class_model->find($id)->row();
if($this->form_validation->run() == FALSE)
{
$this->load->view('admin/class/classEdit',array('class'=>$class));
}
else
{
$data['classname'] = set_value('classname');
$data['inchargename'] = set_value('inchargename');
$data['classstregth'] = set_value('classstregth');
$this->class_model->update($id,$data);
$this->session->set_flashdata('message','Class has been Updated Successfully');
redirect('class_con/index');
}
}
and here's my model
public function find($id) {
$this->db->where('id',$id);
$row = $this->db->get('class');
return $row;
}
function update($data, $id)
{
try{
$this->db->where('id',$id);
$this->db->update('class', $data);
return true;
}
catch(Execption $e){
echo $e->getMessage();
}
}
and here is my view
<?php echo form_open_multipart('class_con/edit/'.$class->id); ?>
<div class="form-group" id="register-login-group">
<label for="classname">Class Name</label>
<div class="input-group">
<input type="text" class="form-control" id="classname" name="classname" value="<?php echo $class->classname; ?>" placeholder="Class Name">
<div class="input-group-addon"><i class="fa fa-pencil"></i></div>
</div>
</div>
<div class="form-group" id="register-login-group">
<label for="classname">Incharge Name</label>
<div class="input-group">
<input type="text" class="form-control" id="inchargename" name="inchargename" value="<?php echo $class->inchargename; ?>" placeholder="Incharge Name">
<div class="input-group-addon"><i class="fa fa-pencil"></i></div>
</div>
</div>
<div class="form-group" id="register-login-group">
<label for="classname">Class Strength</label>
<div class="input-group">
<input type="text" class="form-control" id="classstrength" name="classstrength" value="<?php echo $class->classstrength; ?>" placeholder="Class Stregth">
<div class="input-group-addon"><i class="fa fa-pencil"></i></div>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
<?=anchor('class_con/index','Cancel',['class'=>'btn btn-warning'])?>
<?php echo form_close(); ?>
In your controller You call the update method in model by this line :
$this->class_model->update($id,$data);
but in your Model you have defined function as :
function update($data, $id)
{
try{
$this->db->where('id',$id);
$this->db->update('class', $data);
return true;
}
catch(Execption $e){
echo $e->getMessage();
}
}
the problem is with the order of parameter's that you have passed :
change it to :
$this->class_model->update($data,$id);
Just remove ->row() from
$class = $this->class_model->find($id)->row();
Instead use
$class = $this->class_model->find($id);
foreach ($class->result() as $row)
{
echo $row->colunn_name;
}
And set_value()
Permits you to set the value of an input form or textarea. You must
supply the field name via the first parameter of the function.
So instead
$data['classname'] = set_value('classname');
$data['inchargename'] = set_value('inchargename');
$data['classstregth'] = set_value('classstregth');
Use to store value in $data array
$data['classname'] = 'classname';
$data['inchargename'] = 'inchargename';
$data['classstregth'] = 'classstregth';
It seems there is a bug in your query.
Please trace error using following steps.
1) use $this->db->last_query(); which prints your query....
2) Run that query in sql, it gives the appropriate row or not.
3) if query works properly, now print_r the o/p variable and trace weather it gives the result or not.
I am using Ben Edmunds Ion Auth Library.
I am having a problem with any function that uses the csrf_nonce methods - it is failing the check on post.
I have checked that the flashdata is getting set (I can see it in the form as a hidden input [edit_user for example]), but when you submit the form the flashdata check is failing.
I am using the database for the session if that makes any difference.
Code snippets;
Controller
function edit_user($id) {
$this->data['title'] = "Edit User";
if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
redirect('auth', 'refresh');
} //!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()
$user = $this->ion_auth->user($id)->row();
$groups = $this->ion_auth->groups()->result_array();
$currentGroups = $this->ion_auth->get_users_groups($id)->result();
//process the phone number
if (isset($user->phone) && !empty($user->phone)) {
$user->phone = explode('-', $user->phone);
} //isset($user->phone) && !empty($user->phone)
//validate form input
$this->form_validation->set_rules('first_name', $this->lang->line('edit_user_validation_fname_label'), 'required|xss_clean');
$this->form_validation->set_rules('last_name', $this->lang->line('edit_user_validation_lname_label'), 'required|xss_clean');
$this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'required|valid_email');
$this->form_validation->set_rules('company', $this->lang->line('edit_user_validation_company_label'), 'required|xss_clean');
$this->form_validation->set_rules('groups', $this->lang->line('edit_user_validation_groups_label'), 'xss_clean');
if (isset($_POST) && !empty($_POST)) {
// do we have a valid request?
if ($id != $this->input->post('id')) {
show_error($this->lang->line('error_csrf'));
} //$this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id')
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'company' => $this->input->post('company'),
'email' => $this->input->post('email')
);
//Update the groups user belongs to
$groupData = $this->input->post('groups');
if (isset($groupData) && !empty($groupData)) {
$this->ion_auth->remove_from_group('', $id);
foreach ($groupData as $grp) {
$this->ion_auth->add_to_group($grp, $id);
} //$groupData as $grp
} //isset($groupData) && !empty($groupData)
//update the password if it was posted
if ($this->input->post('password')) {
$this->form_validation->set_rules('password', $this->lang->line('edit_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', $this->lang->line('edit_user_validation_password_confirm_label'), 'required');
$data['password'] = $this->input->post('password');
} //$this->input->post('password')
if ($this->form_validation->run() === TRUE) {
$check = $this->ion_auth->update($user->id, $data);
if (FALSE == $check) {
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect("auth/edit-user/$id", 'refresh');
} else {
//check to see if we are creating the user
//redirect them back to the admin page
$this->session->set_flashdata('message', "User Saved");
redirect("auth/users", 'refresh');
}
} //$this->form_validation->run() === TRUE
} //isset($_POST) && !empty($_POST)
//display the edit user form
$this->data['csrf'] = $this->_get_csrf_nonce();
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
//pass the user to the view
$this->data['user'] = $user;
$this->data['groups'] = $groups;
$this->data['currentGroups'] = $currentGroups;
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name', $user->first_name)
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name', $user->last_name)
);
$this->data['company'] = array(
'name' => 'company',
'id' => 'company',
'type' => 'text',
'value' => $this->form_validation->set_value('company', $user->company)
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'email',
'value' => $this->form_validation->set_value('email', $user->email)
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password'
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password'
);
$this->_render_page('auth/admin/users/update', $this->data);
}
function _get_csrf_nonce() {
$this->load->helper('string');
$key = random_string('alnum', 8);
$value = random_string('alnum', 20);
$this->session->set_flashdata('csrfkey', $key);
$this->session->set_flashdata('csrfvalue', $value);
return array(
$key => $value
);
}
function _valid_csrf_nonce() {
if ($this->input->post($this->session->flashdata('csrfkey')) !== FALSE &&
$this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue')) {
return TRUE;
} //$this->input->post($this->session->flashdata('csrfkey')) !== FALSE && $this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue')
else {
return FALSE;
}
}
View;
<h1><?php echo lang('edit_user_heading');?></h1>
<p><?php echo lang('edit_user_subheading');?></p>
<!--<div id="infoMessage" class="info"><?php echo $message;?></div>-->
<?php
if (isset($message)) {
?>
<div id="infoMessage" class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Message</h4>
<?php echo $message;?>
</div>
<?php
}
?>
<?php echo form_open(uri_string(), 'class="form-horizontal"'); ?>
<div class="control-group <?php echo form_error_class('first_name') ?>">
<label class="control-label" for="first_name">
<?php echo lang('edit_user_fname_label'); ?>
</label>
<div class="controls">
<input type="text"
id="first_name"
name="first_name"
placeholder="<?php echo lang('edit_user_fname_label'); ?>"
value="<?php echo set_value('first_name', $first_name['value']); ?>"
class="error"/>
<?php echo form_error('first_name'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('last_name') ?>">
<label class="control-label" for="last_name">
<?php echo lang('edit_user_lname_label'); ?>
</label>
<div class="controls">
<input type="text"
id="last_name"
name="last_name"
placeholder="<?php echo lang('edit_user_lname_label'); ?>"
value="<?php echo set_value('last_name', $last_name['value']); ?>"
class="error"/>
<?php echo form_error('last_name'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('company') ?>">
<label class="control-label" for="company">
<?php echo lang('edit_user_company_label'); ?>
</label>
<div class="controls">
<input type="text"
id="company"
name="company"
placeholder="<?php echo lang('edit_user_company_label'); ?>"
value="<?php echo set_value('company', $company['value']); ?>"
class="error"/>
<?php echo form_error('company'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('email') ?>">
<label class="control-label" for="email">
<?php echo lang('edit_user_email_label'); ?>
</label>
<div class="controls">
<input type="text"
id="email"
name="email"
placeholder="<?php echo lang('edit_user_email_label'); ?>"
value="<?php echo set_value('email', $email['value']); ?>"
class="error"/>
<?php echo form_error('email'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('password') ?>">
<label class="control-label" for="password">
<?php echo lang('edit_user_password_label'); ?>
</label>
<div class="controls">
<input type="password"
id="password"
name="password"
placeholder="<?php echo lang('edit_user_password_label'); ?>"
value="<?php echo set_value('password'); ?>"
class="error"/>
<?php echo form_error('password'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('password_confirm') ?>">
<label class="control-label" for="password_confirm">
<?php echo lang('edit_user_password_confirm_label'); ?>
</label>
<div class="controls">
<input type="password"
id="password_confirm"
name="password_confirm"
placeholder="<?php echo lang('edit_user_password_confirm_label'); ?>"
value=""
class="error"/>
<?php echo form_error('password_confirm'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('groups') ?>">
<div class="controls <?php echo form_error_class('groups') ?>">
<h3><?php echo lang('edit_user_groups_heading');?></h3>
<?php
foreach ($groups as $group) {
?>
<label class="checkbox">
<?php
$gID=$group['id'];
$checked = null;
$item = null;
foreach($currentGroups as $grp) {
if ($gID == $grp->id) {
$checked= ' checked="checked"';
break;
}
}
?>
<input type="checkbox" name="groups[]" value="<?php echo $group['id'];?>"<?php echo $checked;?>>
<?php echo $group['name'];?>
</label>
<?php
}
?>
</div>
</div>
<?php echo form_hidden('id', $user->id);?>
<?php echo form_hidden($csrf); ?>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-success" value="<?php echo lang('edit_user_submit_btn'); ?>" />
</div>
</div>
<?php echo form_close();?>
First check
$this->session->set_flashdata('message',
$this->ion_auth->errors()
);
having set value
I have found the solution (or this fix works just for me).
I changed the session driver in the config to use native sessions from cookie.
Line 284 of config.php => $config['sess_driver'] = 'native';
Golden rule: never trust CI sessions!
Some notions about FLASHDATA
CSRF and Flashdata:
FLASHDATA will only be available for the NEXT server request, and are then automatically cleared!
e.g.:
AJAX calls function_1, which sends CSRF key/value back to function_1_success
function_1_success sets hidden input fields for CSFR key and value
and enables function_2, which compares POST variables with flashdata
this is how it works (with or without AJAX, that was just an example).
How it doesn't work: if you create a php function which does
$this->session->set_flashdata('item', 'value') and then try to read with echo $this->session->flashdata('item') you will get an empty string, only after a refresh of this function,your flashdata values show