Simple CRUD Operation in Codeigniter? - php

I'm doing simple CRUD operation in Codeigniter.
This is My Controller:
public function areaEdit($area_id)
{
$this->global['pageTitle'] = 'Area Edit';
$data['areaEdit'] = $this->um->areaEdit($area_id);
$this->loadViews("utilities/area/areaEdit", $this->global, $data , NULL);
}
public function updateArea($area_id='area_id')
{
$area_name = $this->input->post('area_name');
$area_abbr = $this->input->post('area_abbr');
$this->form_validation->set_rules('area_name', 'Area Name', 'trim|required');
$this->form_validation->set_rules('area_abbr', 'Area Abbrevation', 'trim');
if ($this->form_validation->run() == FALSE) {
$this->areaEdit($area_id);
} else {
$area_name = ucwords(ucfirst($this->security->xss_clean($area_name)));
$area_abbr = ucwords(ucfirst($this->security->xss_clean($area_abbr)));
$data = array('area_name' => $area_name, 'area_abbr' => $area_abbr);
$result = $this->um->updateArea($data, $area_id);
if ($result) {
$this->session->set_flashdata('success', '<b>'.$area_name.'</b> updated successfully on '.date('d/m/Y H:i:s'));
} else {
$this->session->set_flashdata('error', 'Something wrong! Please try again.');
}
redirect(base_url('utilities/areaList'));
}
}
public function deleteArea($area_id='area_id')
{
$result = $this->um->deleteArea($data, $area_id);
if ($result) {
$this->session->set_flashdata('success', '<b>'.$area_name.'</b> deleted successfully on '.date('d/m/Y H:i:s'));
} else {
$this->session->set_flashdata('error', 'Something wrong! Please try again.');
}
redirect(base_url('utilities/areaList'));
}
And this is My Model is:
public function areaEdit($area_id)
{
$this->db->select("*");
$this->db->from("tbl_area");
$this->db->where("area_id", $area_id);
$query = $this->db->get();
return $query->row();
}
public function updateArea($data, $area_id)
{
$this->db->where("$area_id", $area_id);
$this->db->update("tbl_area", $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
public function deleteArea($area_id='area_id')
{
$this->db->where("area_id", $area_id);
$this->db->delete("tbl_area");
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
When I'm running this script, it gives me an error, it goes in else condition in controller for update function and delete function.
I'm not getting that where I'm making mistake ?
Any kind of help is welcome, thanks in advance.

Hope this will help you :
Mismatch arguments : you are passing two parameters from controller but there is only one argument in model's deleteArea();
Should be like this :
public function deleteArea($area_id='area_id')
{
$result = $this->um->deleteArea($area_id);
if ($result) {
$this->session->set_flashdata('success', '<b>'.$area_name.'</b> deleted successfully on '.date('d/m/Y H:i:s'));
} else {
$this->session->set_flashdata('error', 'Something wrong! Please try again.');
}
redirect(base_url('utilities/areaList'));
}

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.

codeigniter how to display data base query result as a message in the view and how to redirect same function?

my model looks:
public function addMobileAction()
{
$mobile = $this->input->POST('mobile',TRUE);
$qry = 'SELECT * FROM mobile
WHERE mobile='.$this->db->escape($mobile);
$query =$this->db->query($qry);
$value=$query->num_rows();
if($value == 0)
{
$mobile_id=$this->db->select('mobile_id')->order_by('mobile_id','desc')->limit(1)->get('mobile')->row('mobile_id');
$mid=$mobile_id+1;
$sql = "INSERT INTO mobile (mobile,mobile_id)
VALUES(".$this->db->escape($mobile).",".$this->db->escape($mid).")";
$this->db->query($sql);
return "Registered Sucessfully! Your Id is: ".$mid;
}
else
{
$mobile_id=$this->db->select('mobile_id')->where('mobile', $mobile)->get('mobile')->row('mobile_id');
return "Already Registered! Your Id: ".$mobile_id;
}
}
my controller is
public function addMobileProcess()
{
if(($this->session->userdata('username')!=""))
{
$this->load->library('form_validation');
$this->form_validation->set_rules('mobile', 'mobile', 'xss_clean|min_length[10]|required');
if($this->form_validation->run() == FALSE)
{
$this->home();
}
else
{
$result= $this->ContentModel->addMobileAction();
$datasucess['mobileid']=$result;
$data['sucess'] = $this->load->view('sucess', $datasucess, TRUE);
$this->load->view('index',$data);
}
}
else
{
$this->load->view('login');
}
}
my need is I have to take both return values from the model and display as a message in view based on the condition checked on the model, here the view is the same view where data get posted.
That means after the data submission I have to redirect to function that call the view and I have to display "Already Registered! Your Id: ".$mobile_id; if the mobile number is already registered and "Registered Sucessfully! Your Id is: ".$mid; if the mobile number is new.
How is the redirection to be done? what all modification that I have to done. I am new to this kind of situation.Thanking all in advance.
public function addMobileAction()
{
$mobile = $this->input->POST('mobile',TRUE);
$qry = 'SELECT * FROM mobile
WHERE mobile='.$this->db->escape($mobile);
$query =$this->db->query($qry);
$value=$query->num_rows();
if($value == 0)
{
$mobile_id=$this->db->select('mobile_id')->order_by('mobile_id','desc')->limit(1)->get('mobile')->row('mobile_id');
$mid=$mobile_id+1;
$sql = "INSERT INTO mobile (mobile,mobile_id)
VALUES(".$this->db->escape($mobile).",".$this->db->escape($mid).")";
$this->db->query($sql);
return TRUE;
}
else
{
$mobile_id=$this->db->select('mobile_id')->where('mobile', $mobile)->get('mobile')->row('mobile_id');
return "Already Registered! Your Id: ".$mobile_id;
}
}
//Controller
public function addMobileProcess()
{
if(($this->session->userdata('username')!=""))
{
$this->load->library('form_validation');
$this->form_validation->set_rules('mobile', 'mobile', 'xss_clean|min_length[10]|required');
if($this->form_validation->run() == FALSE)
{
$this->home();
}
else
{
$result= $this->ContentModel->addMobileAction();
//check if result is true or not and perform conditions as per the condition
}
}
else
{
$this->load->view('login');
}
}

callback on code igniter always return false

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;
}
}

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.

Model always executing else clause when using WHERE clause

I have a problem with the function of the mode. When I put the right admin name and admin password, it doesn't work. Instead, it gives me the last error message ("You don't have..."), but if I comment out the second WHERE clause in my model, then it works as intended.
Model:
function validate_admin()
{
$this->db->where('adminname',$this->input->post('adminname'));
//$this->db->where('adminpassword',md5($this->input->post('adminpassword')));
$query = $this->db->get('admin');
if($query->num_rows() == 1)
{
return TRUE;
}
}
Controller:
function validate_admin_credentials()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('adminname','Username','trim|required');
$this->form_validation->set_rules('adminpassword','Password','trim|required');
if($this->form_validation->run() == FALSE)
{
$data['main_content']='login_failed';
$this->load->view('includes/template',$data);
}
else
{
$this->load->model('admin_model');
if($this->admin_model->validate_admin())
{
$data = array(
'adminname' => $this->input->post('adminname'),
'adminpassword' => $this->input->post('adminpassword'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('/site/admin_panel');
}
else
{
echo "You don't have administration privileges";
}
}
}
How can I resolve this issue?
If you completely sure about password you can try this code:
$this->db->where('adminpassword', md5($this->input->post('adminpassword', TRUE)));
Edit: edited, sorry for my poor english
You can try it.
Model
$adminpassword = md5($this->input->post('adminpassword'));
$data = array('adminname' => $this->input->post('adminname'),
'adminpassword' => $adminpassword);
$query = $this->db->get_where('admin', $data);
return $query->num_rows();
Controller
if($this->admin_model->validate_admin() > 0)

Categories