callback on code igniter always return false - php

i am currently making this part that can create something to input to database. i used callback function of code igniter to check availability of some item code of a non auto increment table.
i always get the message of the callback '{field} exists.' how do i fix this?
controllers
// CREATE /////////////////////////////////////////////////////////
public function create(){
$this->load->library('form_validation');
$this->form_validation->set_rules('JOB_CODE','Job Code','trim|required|min_length[2]|max_length[5]|callback_check_if_exists');
$this->form_validation->set_rules('JOB_NAME','Job Name','trim|required|max_length[30]');
if($this->form_validation->run() == FALSE){
$this->add_view();
}else{
$input = array(
'JOB_CODE' => $this->input->post('JOB_CODE'),
'JOB_NAME' => $this->input->post('JOB_NAME')
);
$this->Job_Titles_Model->insert($input);
}
}
/////////// FOR TABLES WITH NO AUTO INREMENT
public function check_if_exists($jobcode){
$this->load->model('Job_Titles_Model');
$availability = $this->Job_Titles_Model->check_if_exists($jobcode);
if($availability){
return TRUE;
}else{
return FALSE;
}
}
models
///// CREATE /////////////////////////////////////////////////////////
public function insert($input){
$insert = $this->db->insert('job_titles',$input);
}
/////////// FOR TABLES WITH NO AUTO INREMENT
public function check_if_exists($jobcode){ //CHECK IF JOBODE IS AVAILABLE
$sql = ('SELECT * FROM job_titles WHERE JOB_CODE = ?');
$data = array('JOB_CODE' => $this->input->post('JOB_CODE'));
if($result->num_rows() == 0){
return TRUE;
}else{
return FALSE;
}
}

Related

Login verification not working in CodeIgniter

Hello,
so I built a login system in CodeIgniter in which 3 verification's steps are/should be met with the database before being allowed to access to the specific pages.
The three steps values are: active, is_member and is_admin
This is the code that I made in my Users controller:
public function login(){
// Prohibit access if already logged in
$this->User_model->session_comprobate_member();
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]');
$this->form_validation->set_rules('password','Password','trim|required|min_length[4]');
if ($this->form_validation->run() == FALSE){
//Load View Into Template
$this->template->load('public','login','users/login');
} else {
// Get Post Data from Database
$username = $this->input->post('username');
$password = $this->input->post('password');
$enc_password = md5($password);
$data_user = $this->User_model->login($username, $enc_password);
if($data_user == true){
$user_id = $this->User_model->get_userid($username);
$users = $this->User_model->get_username($user_id);
if($users->active == 0){
// Create error
$this->session->set_flashdata('error', 'This account is banned or inactive');
// Redirect to page
redirect('dashboard/login');
}
if($users->is_admin == 0){
// Create error
$this->session->set_flashdata('error', 'You do not have permission to view this page');
// Redirect to page
redirect('dashboard/login');
}
if($users->is_member == 0){
// Create error
$this->session->set_flashdata('error', 'This account does not exists. Please try again.');
// Redirect to page
redirect('dashboard/login');
} else {
$sess_data = array(
'user_id' => $user_id,
'username' => $username,
'occupation' => 'occupation',
'is_member' => true,
'is_admin' => true,
'active' => true
);
// Set Session Data
$this->session->set_userdata($sess_data);
// Create Message
$this->session->set_flashdata('success', 'You are logged in');
// Redirect to pages
redirect('dashboard');
}
} else {
// Create Error
$this->session->set_flashdata('error', 'Invalid Login');
// Redirect to pages
redirect('dashboard/login');
}
}
}
Each of these values are set to TRUE(1) or FALSE(0) depending on the user account.
I have an account with the tree values equal to 1 so it should allow me to access; here is a picture:
What I want is to be allowed to access after the login verification has met the three values
but for some reason even after having the user with all set to TRUE if just keeps throwing me the first error that I created:
$this->session->set_flashdata('error', 'This account is banned or inactive');
Any idea how to fix it?
Thanks.
Here is my model:
public function get($id)
{
$this->db->where('id', $id);
$query = $this->db->get($this->table);
return $query->row();
}
public function login($username, $password)
{
$this->db->select('*');
$this->db->from($this->table);
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->row()->id;
} else {
return false;
}
}
//I need to work on these two
public function get_username($users) {
$this->db->select('id');
$this->db->from($this->table);
$this->db->where('username', $users);
return $this->db->get()->row;
}
public function get_userid($user_id) {
$this->db->select('id');
$this->db->from($this->table);
$this->db->where('id', $user_id);
return $this->db->get()->row();
}
///
//Check if admin
public function is_admin($id) {
$this->db->select('is_admin');
$this->db->from($this->table);
$this->db->where('id', $id);
$is_admin = $this->db->get()->row('is_admin');
if ($is_admin == 0) {
redirect('/');
} else {
redirect('admin');
}
}
//Check if member
public function is_member($id) {
$this->db->select('is_member');
$this->db->from($this->table);
$this->db->where('id', $id);
$is_member = $this->db->get()->row('is_member');
if ($is_member == 0) {
redirect('/');
} else {
redirect('dashboard/login');
}
}
//Check if active
public function is_active($id) {
$this->db->select('active');
$this->db->from($this->table);
$this->db->where('id', $id);
$is_active = $this->db->get()->row('active');
if ($is_active == 0) {
redirect('/');
} else {
redirect('dashboard/login');
}
}
Again thanks for the help.
assuming username is unique column in table:
Controller
// user login
if($data_user == true) {
// $username from $this->input->post('username');
// call model function
$user = $this->User_model->get_username($username);
// is active user ?
if($user['active'] == 0) {
// Create error
$this->session->set_flashdata('error', 'This account is banned or inactive');
// Redirect to page
redirect('dashboard/login');
}
// is admin ?
if($user['is_admin'] == 0) {
// Create error
$this->session->set_flashdata('error', 'You do not have permission to view this page');
// Redirect to page
redirect('dashboard/login');
}
// is member ?
if($user['is_member'] == 0) {
// Create error
$this->session->set_flashdata('error', 'This account does not exists. Please try again.');
// Redirect to page
redirect('dashboard/login');
} else {
$sess_data = array(
'user_id' => $user['id'],
'username' => $user['username'],
'occupation' => 'occupation',
'is_member' => true,
'is_admin' => true,
'active' => true
);
// Set Session Data
$this->session->set_userdata($sess_data);
// Create Message
$this->session->set_flashdata('success', 'You are logged in');
// Redirect to pages
redirect('dashboard');
}
} else {
// Create Error
$this->session->set_flashdata('error', 'Invalid Login');
// Redirect to pages
redirect('dashboard/login');
}
this model for get_username()
public function get_username($username) {
// select field we needed
$this->db->select('id', 'username', active, is_admin, is_member);
$this->db->from($this->table);
$this->db->where('username', $username);
$this->db->limit(1);
$query = $this->db->get();
// check is $query have a data ?
if ($query->num_rows() > 0) {
// return data
return $query->row_array();
} else {
// redirect login, because no data with that username
redirect('dashboard/login');
}
}
In your get_username() in model you are selecting only id and in controller you are checking values in active column. Add active column in get_username() selection.

Yii- a record can't be updated from a function called from beforesave() , if i return false from before save

While saving a user i am updating the state of a record in my preference table from beforesave() of user table by calling a licensingObject() method of my SbLicensingbehavior.
Now if I return true from the beforsave() function then preference table record gets updated.
If I return false then the preference table record is not updated in data base.
user model code:
public function behaviors()
{
return array(
'behaviour_model_download' => array(
'class' => 'application.components.SbLicensingBehavior'
)
);
}
public function beforeSave()
{
$error = $this->licensingObject('user_count','save');
if($error){
return true;
}
return true;
}
Licensing behavior code:
<?php
class SbLicensingBehavior extends CBehavior
{
/**
* This function will receive the variable as parameter who's current state need to be
* incremented or decremented based on operation parameter.
* value send as parameter will be used as amount by which we need to increment our
* current state variable, it will be usefull incase like we have a limitation on size
* of a repo.
*/
public function updateCurrentState($variable,$operation,$value = null)
{
$preferenceMode = Preference::model()->findByAttributes(array(
'variable' => $variable,
'type' => 'system_limit',
));
if(!$preferenceMode){
return 'not found';
}
$currentStateVariable = "current_state_".$variable;
$currentStatePreferenceModel = Preference::model()->findByAttributes(array(
'variable' => $currentStateVariable,
'type' => 'system_limit'
));
if ($operation == 'save'){
$currentStatePreferenceModel->value += ($value == null?1:$value);
if($preferenceMode->value < $currentStatePreferenceModel->value){
$error = $this->updateFlagState($variable,1);
return $error;
}
}
if(!$currentStatePreferenceModel->save()){
return 'Licensing variable can not be updated';
}
return $error;
}
/**
* This function updates the notification variable value.
*/
public function updateFlagState($variable,$value)
{
$prefrenceNotificationModel = Preference::model()->findByAttributes(array(
'variable' => 'notification_'.$variable,
'type' => 'system_limit'
));
if(!$prefrenceNotificationModel){
return 'Licensing variable can not be updated';
}
$prefrenceNotificationModel->value = $value;
$prefrenceNotificationModel->updated = time();
if(!$prefrenceNotificationModel->save()) {
return 'Licensing variable can not be updated';
}
return 'done';
}
public function licensingObject($variable,$operation=null,$value=null)
{
switch ($variable) {
case "user_count":
$error = $this->updateCurrentState($variable,$operation,$value);
return $error;
if($error == 'done'){
return "user count has exceded the licensing limit, user can not be created";
}
break;
default:
}
}
}
I am not getting what i am doing wrong.

Role base access control system for admin and super_admin

I am trying to get this result -> Use access control logic for two user types: administrators and super administrators.
Administrators will have read access to all records within the system however they will have edit/delete access to only those records that are created by them.
Super administrators will have read/edit/delete access to all records. In this case what should i use? if any one know how to give Roll back accessing control in simple manner in above case then please tell me how to do this?
after login from admin_login.php my page comes here...
this is my controller page..
listing.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Listing extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('student');
$this->load->helper('url');
$this->load->helper('form');
$s = $this->session->userdata('admin_id');
log_message('error', 'Some variable did not contain a value.');
}
public function index()
{
$s = $this->session->userdata('admin_id');
$this->load->model('student',$s);
//$data['result'] = $this->student->listing();
$students = $this->student->listing();/////new line delete [resulet]time 5:42 29/03/16
//$this->load->view('list_view',$data); //// change here time 5:52 29/03/16
$this->load->view('list_view',array('students'=>$students)); /////listing->list_view name change
}
public function delete($id)
{
$result = $this->student->delete_operation($id);
$s = $this->session->userdata('admin_id');// session data call.
//$data['result'] = $this->student->listing();
$students = $this->student->listing();///new line 30/03 1230pm// change for list_view
$this->load->view('list_view',array('students'=>$students));///same as above//change for list_view
//$this->load->view('list_view',$data); ////////////////////////listing->list_view name change
}
public function edit($id)
{
if($id)
{
$s = $this->session->userdata('admin_id');
$result = $this->student->edit_record($id);
$data['action'] = 'edit';
$data['student_id'] = $result[0]->student_id;
$data['student_name'] = $result[0]->student_name;
$data['student_email'] = $result[0]->student_email;
$data['student_address'] = $result[0]->student_address;
$data['subject'] = $result[0]->subject;
$data['marks'] = $result[0]->marks;
}
$this->load->view('edit_student',$data);
}
public function add_student()
{
//$s['user'] = $this->session->userdata('admin_id');//get session data // new line30/03/16
$data['student_id'] = '';
$data['student_name'] = '';
$data['student_email'] = '';
$data['student_address'] ='';
$data['subject'] = '';
$data['marks'] = '';
//$data['admin_id']=''; //new line 12:39 30/03/16
$this->load->view('edit_student',$data);
}
public function add()
{
$data = array(
'student_name' => $this->input->post('txt_name'),
'student_email' => $this->input->post('txt_email'),
'student_address' => $this->input->post('txt_address'),
'subject' => $this->input->post('subject'),
'marks' => $this->input->post('marks'),
'admin_id' => $this->input->post('admin_id')//new line 12:39 31/03
);
$result = $this->student->add_record($id,$data);
header('location:'.base_url().'index.php/listing');
}
}
Probably the best way would be to use some roles in your system, for instance you can use the Ion auth library:
http://benedmunds.com/ion_auth/
With this you can define user groups (e.g.: user,administrator,superadministrator)
you can check the in_group() part of the manual to see how it works.
An example function to let you get some idea how can you check the record deleting:
function hasDeleteRight($record_author_id, $logged_in_user_id) {
// if the user has administrator role we check if he is the author of the record he can delete it
if ($this->ion_auth->in_group('administrator', $logged_in_user_id)) {
if($record_author_id == $logged_in_user_id) {
return true;
}
// if the user has superadministrator role he anyway can delete the record
} elseif ($this->ion_auth->in_group('superadministrator', $logged_in_user_id)) {
return true;
}
// other users cannot delete the record
return false;
}
You still can use this example as base of functions.
usage in your code:
public function delete($id)
{
$logged_user_id = $this->session->userdata('admin_id');
if(!hasDeleteRight($id, $logged_user_id))
{
return false;
}
//....your delete record code
update:
permission check without ion auth, only with session data and separated login (not preferred way):
in the super admin login code you can put the permission into session:
function super_admin_login() {
//your log in code
if($login_success) {
$this->session->set_userdata('permission', 'superadministrator');
}
}
similar for normal administrator login:
function admin_login() {
//your log in code
if($login_success) {
$this->session->set_userdata('permission', 'administrator');
}
}
function hasDeleteRight($record_author_id, $logged_in_user_id) {
// if the user has administrator role we check if he is the author of the record he can delete it
if ($this->session->userdata('permission') == 'administrator') {
if($record_author_id == $logged_in_user_id) {
return true;
}
// if the user has superadministrator role he anyway can delete the record
} elseif ($this->session->userdata('permission') == 'superadministrator') {
return true;
}
// other users cannot delete the record
return false;
}

Form Validation Call Back Function Not Working

Here Is My COde I m checking username is already exist or not in datbase
when i validate and submit the form duplicate entry entered in database i want that if already exist it show validation error
My Controller
public function index()
{
if($this->input->post('submit')) {
$this->form_validation->set_rules('name', 'User Name', 'callback_checkuser');
$this->form_validation->set_rules('role', 'Role', 'trim|required');
$this->form_validation->set_rules('pass', 'Password', 'trim|required');
if($this->form_validation->run()==TRUE)
{
$user['u_name'] = $this->input->post('name');
$user['role'] = $this->input->post('role');
$user['password']= md5($this->input->post('pass'));
$u_id = $this->custom_model->add_user($user);
if($u_id){
$data['msg'] = 'Successfully Created!!!!';
}
}
}
$this->load->template('add_user', $data);
}
function checkuser($name) {
if($this->custom_model->check_name($name) == false) {
false;
}else {
$this->form_validation->set_message('checkuser', 'This user already exist');
return true;
}
}
Here is My Model
public function check_name($name) {
$sql = "SELECT * FROM users WHERE u_name='".$name."' ";
$query = $this->db->query($sql);
$res = $query->row_array();
if (is_array($res) && count($res) > 0){
return $res;
}
return false;
}
There is a return statement missing in the function checkuser, but more importantly, you should invert the value you return. According to the example in the docs, when you set a validation message because of a validation error, you should return false, and return true when the validation passes.
So add a return, and change the boolean values. BTW, you don't really need an else clause and the word "exist" needs an additional "s":
function checkuser($name) {
if ($this->custom_model->check_name($name) == false) {
return true; // the user does not yet exist, so all is OK
}
$this->form_validation->set_message('checkuser', 'This user already exists');
return false; // this is a duplicate user name: not OK
}
Use this:
$this->form_validation->set_rules('name', 'User Name', 'trim|required|is_unique[users.u_name]');// trim and required added too
Docs.

how to insert a value to a foreign key using session without overriding the other sessions in codeigniter?

I hope you're doing fine. Can somebody help me with my problem? I have 2 tables. The other one is for customers, it has an auto-increment value for customer_id. The other table is for orders, it has an auto-increment also for its orders_id and a foreign key from the other table (customers).
When I insert a new customer, if it is successful, I want the page to be redirected to the add new order page. In inserting new order, the customer_id field in my orders table should have the same value as the newly added customer. Adding customer and adding new order is of different function in my controller. I am having an error 1452 when inserting the new order, which means the value inserted for the foreign key customers_id in the orders table is different with the value in the other table (customers).
Now, I've got this solution using session. My problem is the other session for getting the last id is overriding the session for logging in.
Here's some code snippets from my controller:
Class MyController extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->c_id = 0;
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
if($session_data['username'] == 'administrator'){
$this->load->database('sample');
$this->load->model('samplemodel_model');
$this->load->library('form_validation');
} else {
redirect('home', 'refresh');
}
} else {
redirect('login', 'refresh');
}
}
public function index() {
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
//code for validation here
$customers = $this->samplemodel_model->get_entries('customers');
if($this->form_validation->run() == FALSE) {
//Field validation failed.
} else {
//Insert $data
//$data = array('xxxxxx');
//data is something like that
$this->create($data);
}
}
else
{
//If there's no session it will redirect to login page
}
}
//add new orders
public function addOrders() {
if($this->session->userdata('last_inserted_id')) //if I use this session, I can get the last inserted ID but the session data for the login will not be retrieved.
{
$session_data = $this->session->userdata('last_inserted_id');
$orders = $this->samplemodel_model->get_entries('orders');
if($this->form_validation->run() == FALSE) {
//Field validation failed.
} else {
//Insert data
$data = array('customer_id' => $session_data['customer_id'],
'order_type' => $this->input->post('order_type'));
$this->createItem($data);
}
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
//create customer
public function create($data) {
//Insert data
$customers = $this->samplemodel_model->get_entries('customers');
//$data = array(xxxxx);
//somethin' like that for data array
$this->load->samplemodel_model->create('customers', $data);
//***********************************************************//
// get and save last id inserted //
//***********************************************************//
//query the database
$result = $this->samplemodel_model->get_last_inserted($this->db->insert_id());
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array('customer_id' => $row->customer_id);
$this->session->set_userdata('last_inserted_id', $sess_array);
}
return TRUE;
}
else
{
echo "<script type='text/javascript'>alert('error');</script>";
return false;
}
session_start('last_inserted_id');
//********************************************************//
// end //
//********************************************************//
redirect('myController/addOrders', 'refresh');
}
public function createItem($data) {
//Insert data
$orders = $this->samplemodel_model->get_entries('orders');
$data = array('customer_id' => $session_data['customer_id'],
'order_type' => $this->input->post('order_type'));
$this->load->samplemodel_model->create('orders', $data);
//I'm not so sure if it is in this function that I should place the unset for the session 'last_inserted_id'
redirect('home', 'refresh');
}
}
And in my model, I inserted another function which helps me saving the last id inserted. Here's it:
public function get_last_inserted($id)
{
$this -> db -> select('customer_id');
$this -> db -> from('customers');
$this -> db -> where('customer_id', $id);
$this -> db -> limit(1);
$query = $this -> db -> get();
if($query -> num_rows() == 1)
{
return $query->result();
}
else
{
return false;
}
}
PLEEEASE! HELP :'( I would really appreciate if you have any other ideas. THANK YOU SOOOOO MUCH!
The issue is that you're redirecting, Each HTTP request is it's own process with it's own variables, and each request can't access the variables set in other requests.
Try passing the customer ID as a parameter to addOrders(), you can then use the codeigniter way of passing params around :
http://www.example.com/controller/method/paramter
Check the docs :
https://ellislab.com/codeigniter/user-guide/general/controllers.html
under the segment : Passing URI Segments to your Functions
Other possible solution : Store the customerID in the session, or in a user object you instantiate when you create a new user, but that's more dependent of the use case.

Categories