I have a codeigniter form which allows the users to create dynamic fields .
I am able to store the data of the default fields in my database which I have given but how do I store the data dynamic fields which user generates into my database
html code:
<fieldset>
<h2 class="fs-title">Projects</h2>
<h3 class="fs-subtitle">Step 4</h3>
<div class="multi-field-wrapper">
<div class="multi-fields">
<div class="multi-field">
<?php echo validation_errors(); ?>
<input type="text" name="ptitle[]" id="ptitle" placeholder="Project Title" />
<input type="text" name="tech[]" id="tech" placeholder="Project Technology">
<textarea name="des" id="des[]" placeholder="Description" rows="10" cols="10"></textarea>
<button type="button" class="remove-field">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
controller code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->view('register');
}
public function __construct(){
parent::__construct();
this->load->helper('form');
$this->load->library('session');
$this->load->library('form_validation');
$this->load->model('Register_model');
$this->load->helper(array('form', 'url'));
}
public function register()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('rollno','Rollno','required');
$this->form_validation->set_rules('pass','Pass','required');
$this->form_validation->set_rules('cpass','Cpass','required');
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('branch','Branch','required');
$this->form_validation->set_rules('ypass','Ypass','required');
$this->form_validation->set_rules('phoneno','Phoneno','required');
$this->form_validation->set_rules('address','Address','required');
$this->form_validation->set_rules('year','Year','required');
$this->form_validation->set_rules('semester','Semester','required');
$this->form_validation->set_rules('percent','percent','required');
$this->form_validation->set_rules('ptitle','Ptitle','required');
$this->form_validation->set_rules('tech','Tech','required');
$this->form_validation->set_rules('des','des','required');
$this->form_validation->set_rules('achieve','achieve','required');
$this->form_validation->set_rules('skill','skill','required');
if($this->form_validation->run()==FALSE)
{
$this->load->view('register');
return false;
}
else
{
$data1 = array(
'email' => $this->input->post('email'),
'rollno' => $this->input->post('rollno'),
'password' => $this->input->post('pass'),
);
$data2 = array(
'name' => $this->input->post('name'),
'branch' => $this->input->post('branch'),
'ypass' => $this->input->post('ypass'),
'phoneno' => $this->input->post('phoneno'),
'address' => $this->input->post('address'),
'rollno' => $this->input->post('rollno'),
);
// $count = count($this->input->post('h'));
$yr = $this->input->post('year');
$sem = $this->input->post('semester');
$per = $this->input->post('percent');
$rol = $this->input->post('rollno');
/* for($i = 0;$i<$count;$i++)
{
*/
$data3 = array(
'year' => $yr,
'semester' => $sem,
'percent' => $per,
'rollno' => $rol,
/*'year' => $this->input->post('year'),
'semester' => $this->input->post('semester'),
'percent' => $this->input->post('percent'),
'rollno' => $this->input->post('rollno'),*/
);
// }
$data4 = array(
'ptitle' => $this->input->post('ptitle'),
'technology' => $this->input->post('tech'),
'description' => $this->input->post('des'),
'rollno' => $this->input->post('rollno'),
);
$data5 = array(
'achievement' => $this->input->post('achieve'),
'rollno' => $this->input->post('rollno'),
);
$data6 = array(
'skill' => $this->input->post('skill'),
'rollno' => $this->input->post('rollno'),
);
// }
$result = $this->Register_model->register($data1,$data2,$data3,$data4,$data5,$data6);
if($result == TRUE)
{
echo "your are registered successfully!";
}
else
{
// echo "unable to register,try again!";
$this->load->view('register');
}
}/*else */
} /*register*/
} //welcome
?>
model for above controller:
<?php
class Register_model extends CI_model
{
public function __construct()
{
parent::__construct();
}
public function register($data1,$data2,$data3,$data4,$data5,$data6)
{
$this->load->database();
$condition = "rollno =" . "'" . $data1['rollno'] . "'";
$this->db->select('*');
$this->db->from('signup');
$this->db->where($condition);
$this->db->limit(10);
$query = $this->db->get();
if ($query->num_rows() == 0) {
$this->db->insert('signup', $data1);
$this->db->insert('personaldetails', $data2);
$this->db->insert('academicdetails', $data3);
$this->db->insert('projects', $data4);
$this->db->insert('achievements', $data5);
$this->db->insert('skillset', $data6);
if ($this->db->affected_rows() > 0) {
return true;
}
}
else {
return false;
}
}
}
?>
You did not provided your html code and some more information, but let me give you an idea.
First, make the dynamic field as an array as i did below:
<textarea name="des[]" id="des" placeholder="Description" rows="10" cols="10"></textarea>
Now it does not matter how many new fields are added, it will have the same name as above.
When you get that field in your CI code, the des will be an array with all the values. Now you can apply validation to them using loop or what ever you want to do.
To save that fields data in database, it is good to save it in the form of json as below.
$des = $this->input->post('des');
$encoded = json_encode($des);
This way, it wont matter if you have a single dynamic field or hundred, it will be saved easily. And when you need that data, just fetch it from DB, json decode it as below and loop through it according to your purpose.
$dec = json_decode($value_from_db);
Hope it will help.
Related
I am getting the following error when trying to add a new function to my existing product. I am new to php codeIgniter and have been stuck on this for a while. Any help will be appreciated and thanks in advance. If any further file is needed, let me know and I will update the post. When I try to submit the search_add_view form, I get the following error:
Error Was Encountered The action you have requested is not allowed.
my profile controller profile.php is:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Profile extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('download');
$this->load->library('form_validation');
$this->load->library('table');
$this->load->model('searches_model');
$this->searches = $this->searches_model->get_searches();
$this->sites = $this->searches_model->get_sites();
$this->load->driver('scraper', array_column($this->sites, 'driver'));
//check auth
if (!is_admin() && !is_user()) {
redirect(base_url());
}
}
public function index()
{
if (user()->qr_code == '') {
$this->generate_qucode(user()->slug);
}
$data = array();
$data['page_title'] = 'Profile';
$data['user'] = $this->admin_model->get_user_info();
$data['payment'] = $this->admin_model->get_my_payment();
$data['features'] = $this->admin_model->active_features($data['payment']->package_id);
$data['fonts'] = $this->admin_model->select('google_fonts');
$data['countries'] = $this->admin_model->select('country');
$data['main_content'] = $this->load->view('admin/user/profile', $data, TRUE);
$this->load->view('admin/index', $data);
}
public function search_index()
{
$this->form_validation->set_rules('search[name]', 'Search Name', 'required');
$this->form_validation->set_rules('search[site_id]', 'Site', 'required');
$this->form_validation->set_rules('search[url]', 'Search URL', 'required');
if ($this->form_validation->run())
{
$data = $this->input->post('search', TRUE);
$search_id = $this->searches_model->add_search($data);
redirect();
}
$data = array(
'subview' => 'search_add_view',
'sites' => $this->sites,
'searches' => $this->searches
);
$data['page_title'] = 'Search View';
$data['subview'] = $this->load->view('admin/scraper/search_add_view', $data, TRUE);
$data['sites'] = $this->sites;
$data['searches'] = $this->searches;
$data['main_content'] = $this->load->view('admin/scraper/searches_view', $data, TRUE);
$this->load->view('admin/index', $data);
}
public function edit($search_id)
{
$search = $this->searches_model->get_search($search_id);
$this->form_validation->set_rules('search[name]', 'Search Name', 'required');
$this->form_validation->set_rules('search[site_id]', 'Site', 'required');
$this->form_validation->set_rules('search[url]', 'Search URL', 'required');
if ($this->form_validation->run())
{
$data = $this->input->post('search', TRUE);
$this->searches_model->update_search($search_id, $data);
redirect();
}
$data = array(
'subview' => 'search_edit_view',
'sites' => $this->sites,
'searches' => $this->searches,
'search' => $search
);
$data['main_content'] = $this->load->view('admin/scraper/search_edit_view', $data, TRUE);
$this->load->view('admin/index', $data);
}
/**
* Delete a search
*
* #param integer search id to delete
* #return none
*/
public function delete($search_id)
{
$search = $this->searches_model->get_search($search_id);
$search['id'] = $search_id;
if ($this->input->server('REQUEST_METHOD') == 'POST')
{
$data = array('id' => $search_id);
$this->searches_model->delete_search($data);
redirect();
}
$data = array(
'subview' => 'search_delete_view',
'sites' => $this->sites,
'searches' => $this->searches,
'search' => $search
);
$data['main_content'] = $this->load->view('admin/scraper/search_delete_view', $data, TRUE);
$this->load->view('admin/index', $data);
}
public function execute($search_id)
{
$search = $this->searches_model->get_search($search_id);
$this->form_validation->set_rules('search[url]', 'Search URL', 'required');
if ($this->form_validation->run())
{
$search['url'] = $this->input->post('search[url]', true);
$output = $this->scraper->scrape($search['url'], $search['driver']);
force_download($search['name'] . '.csv', $output);
}
$data = array(
'subview' => 'search_execute_view',
'sites' => $this->sites,
'searches' => $this->searches,
'search' => $search
);
$data['main_content'] = $this->load->view('admin/scraper/search_execute_view', $data, TRUE);
$this->load->view('admin/index', $data);
}
}
my routes.php is:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['default_controller'] = 'home/index';
$route['404_override'] = 'home/error_404';
$route['translate_uri_dashes'] = FALSE;
$route['index'] = 'home/index';
$route['error-404'] = 'home/error_404';
$uri = $this->uri->segment(1);
if ( $uri == 'searches_view' || $uri == 'search_add_view' || $uri == 'search_execute_view' || $uri == 'search_delete_view' || $uri == 'search_edit_view') {
$route['search_add_view/(:any)'] = 'admin/profile/search_add_view/$1';
$route['searches_view'] = 'admin/profile/search_index';
$route['search_execute_view'] = 'admin/profile/search_execute_view';
$route['search_delete_view'] = 'admin/profile/search_delete_view';
$route['search_edit_view'] = 'admin/profile/search_edit_view';
}
search_view.php is:
<?php include'include/header.php';?>
<?php include'include/left_sideber.php';?>
<div style="height:100vh; margin-left: 230px;" class="content">
<?php echo $subview;?>
<h2>Saved Searches</h2>
<?php
if (count($searches) == 0)
{
echo '<p>There are no saved searches.</p>';
}
else
{
$this->table->set_heading('Search Name', 'Site', 'Search URL', 'Edit', 'Delete', 'Execute');
foreach ($searches as $search)
{
$this->table->add_row(
$search['name'], $search['site_name'], $search['url'],
anchor('searches/edit/' . $search['id'], 'Edit'),
anchor('searches/delete/' . $search['id'], 'Delete'),
anchor('searches/execute/' . $search['id'], 'Execute')
);
}
echo $this->table->generate();
}
?>
<?php echo $main_content;?>
<?php include'include/footer.php';?>
search_add_view.php:
<div class="content">
<form method="post">
<fieldset>
<legend>Add a New Search</legend>
<p class="space">
<label for="name">Search Name</label>
<input type="text" id="name" name="search[name]" value="<?php echo set_value('search[name]', ''); ?>" size="32" maxlength="32" autofocus>
<?php echo form_error('search[name]', ' <br>', '<br>' . PHP_EOL); ?>
</p>
<p>
<label for="sites">Site</label>
<select id="sites" name="search[site_id]">
<option value="" selected>Select one</option>
<?php foreach ($sites as $row):?>
<option value="<?=$row['id']?>" <?php echo set_select('search[site_id]', $row['id']); ?>><?=$row['name']?></option>
<?php endforeach;?>
</select>
<?php echo form_error('search[site_id]', ' <br>', '<br>' . PHP_EOL); ?>
</p>
<p>
<label for="url">Search URL</label>
<input type="text" id="url" name="search[url]" value="<?php echo set_value('search[url]', ''); ?>" size="105" maxlength="254">
<?php echo form_error('search[url]', ' <br>', '<br>' . PHP_EOL); ?>
</p>
<p><input type="submit" name="submit" value="Ok"></p>
</fieldset>
</form>
<p> </p>
</div>
search_model.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Searches_model extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function get_searches()
{
return $this->db->query(
'SELECT
searches.id AS id,
searches.name AS name,
searches.url AS url,
sites.id AS site_id,
sites.name AS site_name,
sites.driver AS driver
FROM searches
INNER JOIN sites ON
searches.site_id = sites.id
;'
)->result_array();
}
public function get_search($search_id)
{
$query = $this->db->query(
'SELECT
searches.name AS name,
searches.url AS url,
sites.id AS site_id,
sites.name AS site_name,
sites.driver AS driver
FROM searches
INNER JOIN sites ON
searches.site_id = sites.id
WHERE searches.id = ' . $search_id . '
;'
)->result_array();
return $query[0];
}
public function add_search($data)
{
$this->db->insert('searches', $data);
return $this->db->insert_id();
}
public function update_search($id, $data)
{
$this->db->update('searches', $data, array('id' => $id));
}
public function delete_search($data)
{
$this->db->delete('searches', $data);
}
public function get_sites()
{
return $this->db->query(
'SELECT
sites.id AS id,
sites.name AS name,
sites.driver AS driver
FROM sites
;'
)->result_array();
}
}
my file structure is:
I managed to solve this issue with two steps:
First, I confirmed the config.json contains the following property:
$config['csrf_protection'] = TRUE;
Second, I had to add the following code to the html after form declaration:
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
I know maybe my question is very familiar, but i am a newbie in Codeigniter. I have been already implement a solution through searching in Stackoverflow, but the problem it's still persists. So i decided to ask again this question, through this forum.
I am trying to insert a data into a PostgreSQL table, but the error tells me that i have a null value in my query. I see thats the value that comes from option is not has any value.
This is my code.
Model
<?php
class M_Item extends CI_Model{
public function show_data(){
return $this->db->get('tb_item');
}
public function add_item($data){
$this->db->insert('tb_item', $data);
}
public function delete_item($where){
$this->db->delete('tb_item', $where);
}
public function edit_item($where, $table){
return $this->db->get_where($table,$where);
}
public function update_item($where, $data, $table){
$this->db->where($where);
$this->db->update($table, $data);
}
public function getAllItemName(){
$query = $this->db->query('select item_name from tb_item;');
return $query->result();
}
}
?>
Controller
<?php
class Purchase extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model(['m_purchase','m_inventory','m_item','m_grid','m_vendor']);
$this->load->helper(['string','form']);
}
// Show index
public function index(){
$data['purchase'] = $this->m_purchase->show_data()->result();
$this->load->view('templates/header');
$this->load->view('templates/sidebar');
$this->load->view('pages/transaksi/v_purchase', $data);
$this->load->view('templates/footer');
}
// Show form for input vendor
public function form_create(){
$item = $this->m_item->getAllItemName();
$grid = $this->m_grid->getAllGridName();
$vendor = $this->m_vendor->getAllVendorName();
$data = array(
'item' => $item,
'grid' => $grid,
'vendor' => $vendor
);
$this->load->view('templates/header');
$this->load->view('templates/sidebar');
$this->load->view('pages/transaksi/v_purchase_create', $data);
$this->load->view('templates/footer');
}
//method add vendor
public function add(){
$purchase_item = new stdClass();
date_default_timezone_set('Asia/Jakarta');
$now = date('Y-m-d H:i:s');
// User as dummy
$userId = 1;
$purchase_number = $this->input->post('purchase_id');
$purchase_item = $this->input->post('item_id');
$quantity = $this->input->post('quantity');
$grid = $this->input->post('grid_id');
$vendor = $this->input->post('vendor_id');
$data = array(
'purchase_id' => $purchase_number,
'purchase_time' => $now,
'item_id' => $purchase_item,
'quantity' => (int)$quantity,
'grid_id' => $grid,
'vendor_id' => $vendor,
'user_id' => $userId
);
$dataStock = array(
'item_id' => $purchase_item,
'grid_id' => $grid,
'stock' => $quantity,
'last_update' => $now
);
$this->db->trans_start();
$this->m_purchase->add_purchase($data, 'tb_purchase');
$this->m_inventory->updateStock($dataStock, 'tb_inventory');
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
throw
$message = "Gagal Simpan data";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
$success = "Sukses Simpan Data";
echo "<script type='text/javascript'>alert('$success');</script>";
redirect('pages/transaksi/purchase/index');
}
}
//Another Code hiding
View
<div class="col-sm-6">
<label for="">Purchase Item</label>
<select name="item_id" id="item_id" class="form-control">
<?php foreach ($item as $i) :{
echo "<option value='".$i->item_id."'>".$i->item_name."</option>";
}
endforeach; ?>
</select>
</div>
Error Result
ERROR: invalid input syntax for integer: "" LINE 1: ... VALUES ('PURCHASEOMS101', '2020-01-05 16:12:04', '', 100, '... ^
INSERT INTO "tb_purchase" ("purchase_id", "purchase_time", "item_id", "quantity", "grid_id", "vendor_id", "user_id") VALUES ('PURCHASEOMS101', '2020-01-05 16:12:04', '', 100, '', '', 1)
I was expected that the query has inserting some data to the table. Any help would be appreciated.
Finally, after some searching and implementation, i found a solution for this case, i made a change on 2 file, the controller and the view
Purchase Controller
// Show form for input purchase
public function form_create(){
$data['item'] = $this->m_item->show_data()->result();
$data['grid'] = $this->m_grid->show_data()->result();
$data['vendor'] = $this->m_vendor->show_data()->result();
$this->load->view('templates/header');
$this->load->view('templates/sidebar');
$this->load->view('pages/transaksi/v_purchase_create', $data);
$this->load->view('templates/footer');
}
//method add vendor
public function add(){
date_default_timezone_set('Asia/Jakarta');
$now = date('Y-m-d H:i:s');
// User as dummy
$userId = 1;
$purchase_number = $this->input->post('purchase_id');
$purchase_item = $this->input->post('purchase_item');
$quantity = $this->input->post('quantity');
$grid = $this->input->post('grid_id');
$vendor = $this->input->post('vendor_id');
$data = array(
'purchase_id' => $purchase_number,
'purchase_time' => $now,
'item_id' => (int) $purchase_item,
'quantity' => (int) $quantity,
'grid_id' => (int) $grid,
'vendor_id' => (int) $vendor,
'user_id' => $userId
);
$dataStock = array(
'item_id' => $purchase_item,
'grid_id' => $grid,
'stock' => $quantity,
'last_update' => $now
);
$this->db->trans_start();
$this->m_purchase->add_purchase($data, 'tb_purchase');
$this->m_inventory->updateStock($dataStock, 'tb_inventory');
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
throw
$message = "Gagal Simpan data";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
$success = "Sukses Simpan Data";
echo "<script type='text/javascript'>alert('$success');</script>";
redirect('pages/transaksi/purchase/index');
}
}
//another code hiding
V_Purchase_Create
<div class="col-sm-6">
<label for="">Purchase Item</label>
<select name="purchase_item" id="item_id" class="form-control">
<?php foreach($item as $row):?>
<option value="<?php echo $row->item_id;?>"><?php echo $row->item_name;?>
</option>
<?php endforeach;?>
</select>
</div>
So maybe this is not the best practice, (maybe you can do something like this with AJAX) but i think it's oke, thanks to #mikeyhun for answering my question, happy coding!!
I want to validate a form to make sure a user entered something in the description field in this situation form validation is correct.
But,
Here , I pass value to function 2 by fetching values from function 1
When function 2 loads first time it fetch data and display the values (OK)
But When function 2 resubmit for validation and submision data these valitable get empoty and it throw the error Message: Undefined variable: query (ERROR)
I don't know how to do this, hehe. I'm just a newbie PHP programmer.
Here's what I have so far:
function 1
public function ask()
{
$this->load->model('MainM');
$this->load->library('form_validation');
$this->form_validation->set_rules('index', 'AL Index', 'trim|required|min_length[7]|max_length[7]');
if($this->form_validation->run() == FALSE) {
$this->load->view('enterindex');
}else{
$query = null; //emptying in case
$index = $this->input->post("index"); //getting from post value
$query = $this->db->get_where('tbl_reg', array('reg_index' => $index));
$count = $query->num_rows(); //counting result from query
if ($count == 1) {
$data['query'] = $this->MainM->getregdata($index);
$result = $this->load->view('submitques',$data);
}else{
$data = array();
$data['error'] = 'error';
$this->load->view('enterindex', $data);
}
}
function 2
public function submitq()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('yourq', 'Question', 'required|min_length[7]');
if($this->form_validation->run() == FALSE) {
$this->load->view('submitques',$data);
} else {
//insert the submitq form data into database
$data = array(
'reg_id' => $this->input->post('reg_id'),
'ques' => $this->input->post('yourq'),
'call' => "yes",
'status' => "New",
'date' => date('Y-m-d H:i:s')
);
if ($this->db->insert('tbl_ques', $data))
{
// success
$this->session->set_flashdata('success_msg', 'Your Submission is success');
redirect('main/submitq');
}
else
{
$this->load->view('submitques', $data);
}
}
}
Actully you have $data variable put in else part so thats why this error appeared you need to define before loop.
public function submitq()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('yourq', 'Question', 'required|min_length[7]');
// define here before check condtions
$data = array(
'reg_id' => $this->input->post('reg_id'),
'ques' => $this->input->post('yourq'),
'call' => "yes",
'status' => "New",
'date' => date('Y-m-d H:i:s')
);
if($this->form_validation->run() == FALSE) {
$this->load->view('submitques',$data);
} else {
//insert the submitq form data into database
if ($this->db->insert('tbl_ques', $data))
{
// success
$this->session->set_flashdata('success_msg', 'Your Submission is success');
redirect('main/submitq');
}
else
{
$this->load->view('submitques', $data);
}
}
}
If you wish to use the posted $data variable on false condition, you could moving it up outside the validation block :
public function submitq()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('yourq', 'Question', 'required|min_length[7]');
$data = array(
'reg_id' => $this->input->post('reg_id'),
'ques' => $this->input->post('yourq'),
'call' => "yes",
'status' => "New",
'date' => date('Y-m-d H:i:s')
);
if($this->form_validation->run() == FALSE) {
$this->load->view('submitques',$data);
} else {
//insert the submitq form data into database
if ($this->db->insert('tbl_ques', $data))
{
// success
$this->session->set_flashdata('success_msg', 'Your Submission is success');
redirect('main/submitq');
}
else
{
$this->load->view('submitques', $data);
}
}
}
Try with This Code:
First Add Form Library to config/autoload.php
$autoload['libraries'] = array('database','form_validation');
html Code
This is view file login.php
<?php echo form_open('action_controller_name', array('class' => '', 'enctype' => 'multipart/form-data', 'role' => 'form', 'name' => 'myform', 'id' => 'myform')); ?>
<div class="form-group">
<label class="control-label" for="mobile">Mobile-No</label>
<input type="text" name="mobile" value="" placeholder="Enter Mobile No" id="mobile" class="form-control" />
<label class="error"><?php echo form_error('mobile'); ?></label>
</div>
<div class="form-group">
<label class="control-label" for="password">Password</label>
<input type="password" name="password" value="" placeholder="Password" id="password" class="form-control" />
<label class="error"><?php echo form_error('mobile'); ?></label>
</div>
<input type="submit" value="Login" class="btn btn-gray" id="submit" />
<a class="forgotten" href="<?php echo base_url('login/forgot_password'); ?>" style="font-size: 13px;">Forgot Password</a>
<?php
echo form_close();
?>
My Action Controller
public function action_controller_name() {
$this->load->helper(array('form')); // Load Form Library
$this->load->library('form_validation'); // Load Form Validaton Library
$this->form_validation->set_rules('mobile', 'mobile', 'required', array('required' => 'Please Enter Mobile Number.'));
$this->form_validation->set_rules('password', 'Password', 'required', array('required' => 'Please Enter passsword.'));
if ($this->form_validation->run() === TRUE) { // Check validation Run
// Your Login code write here
} else {
$this->load->view('login', $this->data);
}
}
Try this code.You can keep variable value if validation fails in codeigniter successfully.
i have a problem in a controller file called "pages.php". After login via login page with correct credentials pages.php does not open dashboard. I doubt that probably the source of this problem may be found in this pages.php
<?php
class Pages extends MY_Controller
{
public function view($page = 'login')
{
if (!file_exists(APPPATH.'views/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
if($page == 'section' || $page == 'subject' || $page == 'student' || $page == 'marksheet' || $page == 'accounting') {
$this->load->model('model_classes');
$data['classData'] = $this->model_classes->fetchClassData();
$this->load->model('model_teacher');
$data['teacherData'] = $this->model_teacher->fetchTeacherData();
$this->load->model('model_accounting');
$data['totalIncome'] = $this->model_accounting->totalIncome();
$data['totalExpenses'] = $this->model_accounting->totalExpenses();
$data['totalBudget'] = $this->model_accounting->totalBudget();
}
if($page == 'setting') {
$this->load->model('model_users');
$this->load->library('session');
$userId = $this->session->userdata('id');
$data['userData'] = $this->model_users->fetchUserData($userId);
}
if($page == 'dashboard') {
$this->load->model('model_student');
$this->load->model('model_teacher');
$this->load->model('model_classes');
$this->load->model('model_marksheet');
$this->load->model('model_accounting');
$data['countTotalStudent'] = $this->model_student->countTotalStudent();
$data['countTotalTeacher'] = $this->model_teacher->countTotalTeacher();
$data['countTotalClasses'] = $this->model_classes->countTotalClass();
$data['countTotalMarksheet'] = $this->model_marksheet->countTotalMarksheet();
$data['totalIncome'] = $this->model_accounting->totalIncome();
$data['totalExpenses'] = $this->model_accounting->totalExpenses();
$data['totalBudget'] = $this->model_accounting->totalBudget();
}
if($page == 'login') {
$this->isLoggedIn();
$this->load->view($page, $data);
}
else{
$this->isNotLoggedIn();
$this->load->view('templates/header', $data);
$this->load->view($page, $data);
$this->load->view('templates/footer', $data);
}
}
}
Please anyone who can edit this code just help. Or if you think the problem is not in pages.php (above page) please advice me how the problem can be solved. I have mentioned more pages:-
This is rootes.php.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
This is MY_Controller.php in core folder
<?php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function isLoggedIn()
{
$this->load->library('session');
if($this->session->userdata('logged_in') === true) {
redirect('../dashboard');
}
}
public function isNotLoggedIn()
{
$this->load->library('session');
if($this->session->userdata('logged_in') != true) {
redirect('../../');
}
}
}
This is Users.php in controllers folder
<?php
class Users extends MY_Controller
{
public function __construct()
{
parent::__construct();
// loading the users model
$this->load->model('model_users');
// loading the form validation library
$this->load->library('form_validation');
}
public function login()
{
$validator = array('success' => false, 'messages' => array());
$validate_data = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|callback_validate_username'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required'
)
);
$this->form_validation->set_rules($validate_data);
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if($this->form_validation->run() === true) {
$username = $this->input->post('username');
$password = md5($this->input->post('password'));
$login = $this->model_users->login($username, $password);
if($login) {
$this->load->library('session');
$user_data = array(
'id' => $login,
'logged_in' => true
);
$this->session->set_userdata($user_data);
$validator['success'] = true;
$validator['messages'] = "index.php/dashboard";
}
else {
$validator['success'] = false;
$validator['messages'] = "Incorrect username/password combination";
} // /else
}
else {
$validator['success'] = false;
foreach ($_POST as $key => $value) {
$validator['messages'][$key] = form_error($key);
}
} // /else
echo json_encode($validator);
} // /lgoin function
public function validate_username()
{
$validate = $this->model_users->validate_username($this->input->post('username'));
if($validate === true) {
return true;
}
else {
$this->form_validation->set_message('validate_username', 'The {field} does not exists');
return false;
} // /else
} // /validate username function
public function logout()
{
$this->load->library('session');
$this->session->sess_destroy();
redirect('../../');
}
public function updateProfile()
{
$this->load->library('session');
$userId = $this->session->userdata('id');
$validator = array('success' => false, 'messages' => array());
$validate_data = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'fname',
'label' => 'First Name',
'rules' => 'required'
)
);
$this->form_validation->set_rules($validate_data);
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if($this->form_validation->run() === true) {
$update = $this->model_users->updateProfile($userId);
if($update === true) {
$validator['success'] = true;
$validator['messages'] = "Successfully Update";
}
else {
$validator['success'] = false;
$validator['messages'] = "Error while inserting the information into the database";
}
}
else {
$validator['success'] = false;
foreach ($_POST as $key => $value) {
$validator['messages'][$key] = form_error($key);
}
} // /else
echo json_encode($validator);
}
public function changePassword()
{
$this->load->library('session');
$userId = $this->session->userdata('id');
$validator = array('success' => false, 'messages' => array());
$validate_data = array(
array(
'field' => 'currentPassword',
'label' => 'Current Password',
'rules' => 'required|callback_validate_current_password'
),
array(
'field' => 'newPassword',
'label' => 'Password',
'rules' => 'required|matches[confirmPassword]'
),
array(
'field' => 'confirmPassword',
'label' => 'Confirm Password',
'rules' => 'required'
)
);
$this->form_validation->set_rules($validate_data);
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if($this->form_validation->run() === true) {
$update = $this->model_users->changePassword($userId);
if($update === true) {
$validator['success'] = true;
$validator['messages'] = "Successfully Update";
}
else {
$validator['success'] = false;
$validator['messages'] = "Error while inserting the information into the database";
}
}
else {
$validator['success'] = false;
foreach ($_POST as $key => $value) {
$validator['messages'][$key] = form_error($key);
}
} // /else
echo json_encode($validator);
}
public function validate_current_password()
{
$this->load->library('session');
$userId = $this->session->userdata('id');
$validate = $this->model_users->validate_current_password($this->input->post('currentPassword'), $userId);
if($validate === true) {
return true;
}
else {
$this->form_validation->set_message('validate_current_password', 'The {field} is incorrect');
return false;
} // /else
}
}
This is login.php in views folder
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
<!-- bootstrap css -->
<link rel="stylesheet" type="text/css"
href="assets/bootstrap/css/bootstrap.min.css">
<!-- boostrap theme -->
<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap-theme.min.css">
<!-- custom css -->
<link rel="stylesheet" type="text/css" href="custom/css/custom.css">
<!-- jquery -->
<script type="text/javascript" src="assets/jquery/jquery.min.js"></script>
<!-- boostrap js -->
<script type="text/javascript" src="assets/bootstrap/js/bootstrap.min.js">
</script>
</head>
<body>
<div class="col-md-6 col-md-offset-3 vertical-off-4">
<div class="panel panel-default login-form">
<div class="panel-body">
<form method="post" action="index.php/users/login" id="loginForm">
<fieldset>
<legend>
Login
</legend>
<div id="message"></div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autofocus>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<button type="submit" class="col-md-12 btn btn-primary login-button">Submit</button>
</fieldset>
</form>
</div>
</div>
</div>
<script type="text/javascript" src="custom/js/login.js"></script>
</body>
</html>
login.js
$(document).ready(function(){
$("#loginForm").unbind('submit').bind('submit', function() {
var form = $(this);
var url = form.attr('action');
var type = form.attr('method');
$.ajax({
url : url,
type : type,
data : form.serialize(),
dataType: 'json',
success:function(response) {
if(response.success === true) {
window.location = response.messages;
}
else {
if(response.messages instanceof Object) {
$("#message").html('');
$.each(response.messages, function(index, value) {
var key = $("#" + index);
key.closest('.form-group')
.removeClass('has-error')
.removeClass('has-success')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger').remove();
key.after(value);
});
}
else {
$(".text-danger").remove();
$(".form-group").removeClass('has-error').removeClass('has-success');
$("#message").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
response.messages +
'</div>');
} // /else
} // /else
} // /if
});
return false;
});
});
Thanks to all, finally I have got a correct answer, the problem was due to the older version of codeignitor in php 7 server, for more info click
Codeigniter session data lost after redirect
Hi I was facing same issue. logs was showing nothing and my apache server got hanged. but in my case issue was with my controller. i did one mistake. i was printing array object in logs. instead of doing array to string conversion. i solved this and redirect function started working.
Just use refresh method, it works for me
$this->load->helper('url);
redirect('foo', 'refresh');
I have an issue where every time I click on login it just takes me to my page it seems to not be checking to see if the username or password was entered. I am not sure what the issue is I changed the line if ($this->form_validation->run() == FALSE) to true and then I just get redirected back to the login when I enter correct password. I think it is something simple I am just missing. If anyone has an idea any direction would help in the mean time I will keep figuring it out.
Controllers
Verifylogin.php controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
}
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
if($this->form_validation->run() == false)
{
//Field validation failed. User redirected to login page
$this->load->view('person_view');
}
else
{
//Go to private area
redirect('Person', 'refresh');
}
}
public function check_database() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_view.php');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->admin_database->login($data);
if($result == TRUE){
$sess_array = array(
'username' => $this->input->post('username')
);
}
}
}
}
Person.php controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Person extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('person_model','callin_list');
}
public function index()
{
if($this->session->userdata('logged_in'))
{
$this->load->view('person_view');
}else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
public function ajax_list()
{
$list = $this->callin_list->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $callin_list) {
$no++;
$row = array();
$row[] = $callin_list->Date_Scheduled;
$row[] = $callin_list->Employee_Name;
$row[] = $callin_list->Employee_Number;
$row[] = $callin_list->Time_Reported;
$row[] = $callin_list->Reason;
$row[] = $callin_list->Scheduled_Area;
$row[] = $callin_list->Contact;
$row[] = $callin_list->Comments;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void()" title="Edit" onclick="edit_person('."'".$callin_list->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
<a class="btn btn-sm btn-danger" href="javascript:void()" title="Hapus" onclick="delete_person('."'".$callin_list->id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->callin_list->count_all(),
"recordsFiltered" => $this->callin_list->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_edit($id)
{
$data = $this->callin_list->get_by_id($id);
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'Date_Scheduled' => $this->input->post('Date_Scheduled'),
'Employee_Name' => $this->input->post('Employee_Name'),
'Employee_Number' => $this->input->post('Employee_Number'),
'Time_Reported' => $this->input->post('Time_Reported'),
'Reason' => $this->input->post('Reason'),
'Scheduled_Area' => $this->input->post('Scheduled_Area'),
'Contact' => $this->input->post('Contact'),
'Comments' => $this->input->post('Comments'),
);
$insert = $this->callin_list->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'Date_Scheduled' => $this->input->post('Date_Scheduled'),
'Employee_Name' => $this->input->post('Employee_Name'),
'Employee_Number' => $this->input->post('Employee_Number'),
'Time_Reported' => $this->input->post('Time_Reported'),
'Reason' => $this->input->post('Reason'),
'Scheduled_Area' => $this->input->post('Scheduled_Area'),
'Contact' => $this->input->post('Contact'),
'Comments' => $this->input->post('Comments'),
);
$this->callin_list->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_delete($id)
{
$this->callin_list->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
//validation section were user must enter data in all fields
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('Date_Scheduled') == '')
{
$data['inputerror'][] = 'Date_Scheduled';
$data['error_string'][] = 'Date_Scheduled is required';
$data['status'] = FALSE;
}
if($this->input->post('Employee_Name') == '')
{
$data['inputerror'][] = 'Employee_Name';
$data['error_string'][] = 'Employee_Name is required';
$data['status'] = FALSE;
}
if($this->input->post('Employee_Number') == '')
{
$data['inputerror'][] = 'Employee_Number';
$data['error_string'][] = 'Employee_Number is required';
$data['status'] = FALSE;
}
if($this->input->post('Time_Reported') == '')
{
$data['inputerror'][] = 'Time_Reported';
$data['error_string'][] = 'Time_Reported is required';
$data['status'] = FALSE;
}
if($this->input->post('Reason') == '')
{
$data['inputerror'][] = 'Reason';
$data['error_string'][] = 'Reason is required';
$data['status'] = FALSE;
}
if($this->input->post('Scheduled_Area') == '')
{
$data['inputerror'][] = 'Scheduled_Area';
$data['error_string'][] = 'Scheduled_Area is required';
$data['status'] = FALSE;
}
if($this->input->post('Contact') == '')
{
$data['inputerror'][] = 'Contact';
$data['error_string'][] = 'contact is required';
$data['status'] = FALSE;
}
if($this->input->post('Comments') == '')
{
$data['inputerror'][] = 'Comments';
$data['error_string'][] = 'Comments is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
login_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Author: Jorge Torres
* Description: Login model class
*/
class Login_model extends CI_Model{
function __construct(){
parent::__construct();
}
public function validate(){
// grab user input
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
// Prep the query
$this->db->where('username', $username);
$this->db->where('password', $password);
// Run the query
$query = $this->db->get('users');
// Let's check if there are any results
if($query->num_rows() == 1)
{
// If there is a user, then create session data
$row = $query->row();
$data = array(
'userid' => $row->userid,
'fname' => $row->fname,
'lname' => $row->lname,
'username' => $row->username,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
// If the previous process did not validate
// then return false.
return false;
}
}
?>
login_view.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login Form</title>
<style type="text/css">
.content{
margin-left: 400px;
margin-top: 300px;
}
.btn{
width:242px;
height: 50px;
}
#label{
font-size: 24px;
font-weight: normal;
}
</style>
<link href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css')?>" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="content">
<h1>DC399 Callin Login Page</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('verifylogin'); ?>
<label id="label"for="username">Username:</label><br>
<input type="text" size="20" id="username"style="width: 239px; height: 40px; margin-right: 20px;"name="username"/>
<br/>
<label id="label" for="password">Password:</label><br>
<input type="password" size="20" id="passowrd" style="width: 239px; height: 40px; margin-right: 20px;"name="password"/>
<br/><br>
<input class="btn btn-success" type="submit" value="Login"/>
</form>
</div>
</div>
<script src="<?php echo base_url('assets/jquery/jquery-2.1.4.min.js')?>"></script>
<script src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js')?>"></script>
</body>
</html>
Use $this->form_validation->run() === FALSE instead, with 3 = signs.
You are sending the data to verifylogin/index and any moment are loading the rules to check and validate neither are checking from the database. That's the problem.