CodeIgniter - checking data and receiving 'Trying to get property of non-object' - php

Im trying to test a pin number in the database compared to one entered by a user, whenever i run it i get a 'Trying to get property on non-object' error ... I cant seem to spot where im going wrong, could someone please help me out ... Its saying the error is on the $thepin = $pins->pin; line
The code i have in my controller is as follows:
function check_pin()
{
$pin = md5($this->input->post('oldpin'));
$email = $this->input->post('email');
$existingpin = $this->users->get_pin_by_email($email);
foreach($existingpin as $pins){
$thepin = $pins->pin;
}
if($pin != $thepin){
$this->form_validation->set_message('check_pin', 'The Old Pin Number does not match the existing one');
return FALSE;
} else {
return TRUE;
}
}
and the following is the code in my model
function get_pin_by_email($emailaddress)
{
$this->db->where('LOWER(email)=', strtolower($emailaddress));
$query = $this->db->get($this->table_name);
if ($query->num_rows() == 1) return $query->row();
return NULL;
}

The Controller code should be:-
function check_pin()
{
$pin = md5($this->input->post('oldpin'));
$email = $this->input->post('email');
$existingpin = $this->users->get_pin_by_email($email);
foreach($existingpin as $pins){
// Check for the NULL return
if ($pins != NULL && is_object($pins)) {
$thepin = $pins->pin;
}
}
if($pin != $thepin){
$this->form_validation->set_message('check_pin', 'The Old Pin Number does not match the existing one');
return FALSE;
} else {
return TRUE;
}
}
If you look closely in the model code, you will find that you are returning two data types - one is Object & another is NULL. So in your controller code, you should also check that accordingly.
Hope it helps.

Related

Trying to get property 'staff 'of non-object when test REST API from Postman

I'm trying to understand the reason of this error message from postman when test API.
When I am testing my REST API from postman, it gives me error
ErrorException (E_NOTICE)
Trying to get property 'staff' of non-object
I try to find the problem but i can't find it. I kept searching for this but couldn't find an answer that will make this clear.
Anyone can help me on this?
Thanks!
This my code snippet
public function updatestatus($request, $leave, $is_api=0)
{
$status = $request->get('status');
$user = $is_api? JWTAuth::parseToken()->authenticate():Auth::user();
// $user = Auth::user();
$staff= $user->ref_user;
$applying_staff = $leave->staff;
$applying_user = $applying_staff->main_user;
//Approved
if($status==2 && $leave->status==1)
{
$leave->status =2;
$leave->approved_by_staff_id = $staff->staff_id;
$leave->approved_date = new Carbon('today');
$leave->save();
if($user->centre_id)
Helper::ClearObjective(10,$user->centre_id);
dispatch(new EmailJob($applying_user->email,new LeaveNotification(route('staff.leave.show',$leave->id), $leave->statusStr)))
->onConnection('database')
->onQueue('emails');
return response()->json(['Success'=>'Success']);
//send email
}
// Rejected
else if($status==3 && $leave->status==1)
{
$leave->status =3;
$leave->status_rejected_reason = $request->get('reason',null);
$leave->save();
if($user->centre_id)
Helper::ClearObjective(10,$user->centre_id);
$leave_cat = LeaveCategory::find($leave->leave_type);
if($leave_cat->leave_status!=0)
{
$leave_ent = $applying_staff->leaves()->where('leave_type',$leave->leave_type)->first();
if($leave_ent)
{
$leave_ent->leave_remaining += $leave->leave_days;
$leave_ent->save();
}
}
dispatch(new EmailJob($applying_user->email,new LeaveNotification(route('staff.leave.show',$leave->id), $leave->statusStr, $leave->status_rejected_reason)))
->onConnection('database')
->onQueue('emails');
//send email
}
//Cancelled
else if(($status==4 && $leave->status==2) || ($status==4 && $leave->staff_id == $staff->staff_id))
{
$leave->status =4;
$leave->status_rejected_reason = $request->get('reason',null);
$leave->save();
$leave_cat = LeaveCategory::find($leave->leave_type);
if($leave_cat->leave_status!=0)
{
$leave_ent = $applying_staff->leaves()->where('leave_type',$leave->leave_type)->first();
if($leave_ent)
{
$leave_ent->leave_remaining += $leave->leave_days;
$leave_ent->save();
}
}
dispatch(new EmailJob($applying_user->email,new LeaveNotification(route('staff.leave.show',$leave->id), $leave->statusStr,$leave->status_rejected_reason)))
->onConnection('database')
->onQueue('emails');
//send email
}
// return reponse()->toJson(compact('leave'));
return $leave;
}
Calling API
public function update(Request $request)
{
return $this->leaveApplicationRepository->updatestatus($request,1);
}
your updatestatus() need 3 parameter and your update() function pass only 2 paramenter;
public function update(Request $request)
{
// please provide you leave data
$leave = "your data is here";
return $this->leaveApplicationRepository->updatestatus($request,$leave, 1);
}
From the context that I can see, it is trying to reference the staff variable in:
$applying_staff = $leave->staff;
The non-object message will mean that $leave itself is the problem. Since you are passing in 1 to the call:
return $this->leaveApplicationRepository->updatestatus($request,1);
the 1 becomes the $leave parameter, and that is not an object, hence the error.
Maybe you think that by passing in 1, it will find the correct model automatically? This is not the case. You need to load that model explicitly.

Trying to get property of non-object when username is incorrect using CodeIgniter

I am using password_verify to check the password is correct or not which is working perfectly. My issue is when the user entered the wrong username clicked on login button than I am getting the error that "Trying to get property of non-object".
Instated of error it should display the validation error message.
If I enter the correct username and wrong password than I am getting the proper validation error message(Password is invalid) but If I enter the wrong username and correct password then I am getting the error "Trying to get property of non-object".`
Would you help me out in this?
Controller
public function login_user()
{
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('user_email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('user_password', 'Password', 'trim|required|xss_clean|callback_check_password_database');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('login');
}
else
{
//redirect(base_url('Student_controller/index'),'refresh');
}
}
/*Checking the login details*/
function check_password_database($user_password)
{
$a_username=$this->input->post('user_email');
if (empty($a_username)) {
$this->form_validation->set_message('check_password_database','Email is Invalid');
}
else{
$password_fetch=$this->access_model->password_fetch($a_username);
if(password_verify($user_password, $password_fetch))
{
redirect('Student_controller/index','refresh');
}
else{
$this->form_validation->set_message('check_password_database','Password is Invalid');
return FALSE;
}
}
}
Model
public function password_fetch($username)
{
$query=$this->db->select('emp_password')
->from('employee_info')
->where('emp_email',$username)
->get();
$result = $query->row();
return $fetch_pass=$result->emp_password;
}
You are doing
return $fetch_pass = $result->emp_password;
without validating if $result is actually an object. If the user does not exist, the $result will not be an object. Consequently, trying to fetch emp_password when $result is not an object, will give you the error message Trying to get property of non-object.
Do this instead:
if (isset($row)) {
return $result->emp_password;
}
Further reference: https://www.codeigniter.com/userguide3/database/results.html
On a side note, an application should respond with a generic error message regardless of whether the user ID or password was incorrect. It should also give no indication to the status of an existing account.
Change your model
public function password_fetch($username)
{
$fetch_pass = false;
$query=$this->db->select('emp_password')
->from('employee_info')
->where('emp_email',$username)
->get();
$result = $query->row();
if (isset($row) && ($row > 0)) {
$fetch_pass=$result->emp_password;
}
return $fetch_pass;
}
You must be trying to access an array directly. Between $a_username and $password_fetch one must be a array which you are directly trying to access.
You must echo both of them to find how values are stored in them.Try printing them with echo $a_username;die; and similarly for the other.
If it is an array try printing echo "<pre>";print_r$(a_username);
Also initialize $fetch_pass="" in model;

Can't set error message in Code Igniter 3 when using callback function

I am writing a method that uses POST variables posted by AJAX to add a user to a certain course in the database, but I can't get the callback to work correctly:
public function enroll()
{
$package = array();
$this->load->library('form_validation');
$this->form_validation->set_rules('course', 'Vak', 'required|callback_not_enrolled');
$fields = array("course");
if ($this->form_validation->run($this) === FALSE) {
$errors = array();
$success = array();
foreach ($fields as $field) {
$error = form_error($field);
if ($error !== "") {
$errors[$field] = $error;
} else {
$success[$field] = True;
}
}
$package["field_errors"] = $errors;
$package["field_success"] = $success;
$package["success"] = False;
} else {
$package["database"] = $this->course_model->enroll_user($this->data["user"], $this->input->post("course"));
$package["success"] = True;
}
echo json_encode($package);
}
I wrote the callback not_enrolled to check if the user is not already enrolled to the database. Note that I can't use is_unique because I have to test the combined uniqueness of two fields (so just one or two separate ones don't do the trick) and the id of the user is not included in the form (because it's part of the Code Igniter session).
The callback function:
public function _not_enrolled($course)
{
$exists = ($this->user->is_enrolled($course, $this->data["user_id"]) != False);
if ($exists != False) {
$this->form_validation->set_message("not_enrolled", "Already enrolled");
return False;
} else {
return True;
}
}
And finally the method is_enrolled from the model:
public function is_enrolled($course, $user=False) {
if($user==False){
$user = $this->data["user_id"];
}
$this->db->select()->from("course_participant")->where("user_id", $user)->where("course_id", $course);
$query = $this->db->get();
return($query->num_rows()>0);
}
Through a call to var_dump($this->_not_enrolled($existing_course_id)); I know that both the callback function and the method from the model work, as it correctly returned true.
When I var_dump the $package array or validation_errors() I don't get any validation errors except that it says Unable to access an error message corresponding to your field name Vak(not_enrolled).
I tried removing the initial _ from the function name but that gives me a Server Status 500 error.
I have another setup exactly like this, albeit other database calls, with a callback using the same syntax. This method works perfectly.

Redirecting not working in codeigniter

So here's what I want to do. I want to check if the userid in segment(3) exist or else it will redirect somewhere instead of still loading the view with an error.
Here's the example url
http://localhost/ems/edit_user/edit_user_main/1001
Now if I try to edit the userid in segment(3) and intentionally put an invalid userid, it still loads the view and i don't know why
Here's my function
public function edit_user_main(){
$id = $this->uri->segment(3);
$check = $this->get_data->check_if_exist($id);
if($check) {
$data['title'] = 'Edit User';
$data['id'] = $this->session->userdata('usertoedit');
$this->load->model('accounts/get_data');
$item = $this->get_data->get_user($id);
$data['user'] = $item[0];
$data['main_content'] = 'edit_user/edit_user_main';
$this->load->view('includes/template', $data);
} else {
redirect('admin/adminuser');
}
}
Here's the model
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query) {
return TRUE;
} else {
return FALSE;
}
}
There is no problem with the fetching of data.
The problem is even if the userid doesn't exist, the view is still loading but with an error coz there's no data for that userID. It's not redirecting,
I tried using print_r and it working fine, the value of the $check is 1 when there's a valid userID.
Hope someone can help me with this. Thank you
With your function it will always return true because the statement
$this->db->get_where('accounts',array('user_id'=>$id));
will always execute,So you need to check query is returning any result row or not with the statement
$query->num_rows().
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query->num_rows() > 0){ //change made here
return TRUE;
}
else{
return FALSE;
}
}
Try this..
With the function it will always return true because the following statement
$this->db->get_where('accounts',array('user_id'=>$id));
will always be execute, So need to check query is returning any result row or not
$query->num_rows().
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query->num_rows() > 0){ //change made here
return TRUE;
}
else{
return FALSE;
}
}
And load heper as:-
$this->load->helper('url');
before the redirection

PHP Check Function

I have a check function:
function checkCandidateEmail($email)
{
$email = $_POST;
if($email)
{
$candemail = (SQL);
if(isset($candemail['email']))
{
return TRUE;
} else {
return FALSE;
}
return $canEmailCheck;
}
}
I have started to create a function but I am getting NULL
function checkCandidateEmail($email)
{
$email = $_POST; // being immediately overwritten - redundant argument.
if($email) // Since $email isn't an optional argument, you'll get a PHP warning if it is missing, making this check confusing.
{
$candemail = (SQL); // Evaluating a constant? this will be bool
if(isset($candemail['email'])) // Since $candemail is a bool and not an array, this will never return true
{
return TRUE;
} else {
return FALSE;
} // this entire if/else block can be simplified to this: return (isset($candemail['email']));
return $canEmailCheck; // this is an undefined variable and will never get returned anyway because of the above return statements.
}
}
Please, elaborate more on your questions next time. I am not sure what you attempt to compare, if the $_POST with the SQL query or the argument passed with the SQL query. I assume the former.
If the email from that SQL table row equals the submitted email, returns TRUE. Else, returns FALSE. Really simplified version. Now it also checks if the user provided an email:
function checkCandidateEmail()
{
if (!$_POST['email']) echo "Error, please provide an email";
else
{
$candemail = (SQL); // Return a row from a query
return $candemail['email'] == $_POST['email'];
}
}
If an argument is passed, compares that against the database. If none is passed, compares the submitted $_POST['email'] against the database.
function checkCandidateEmail($email=null)
{
$candemail = (SQL); // Return a row from a query
if (!$email) $email = $_POST['email'];
return $candemail['email'] == $email;
}
NOTE: In both cases you have to substitute SQL for the right string and function depending on your database.
NOTE 2: Make sure that your query returns an email, as this simple code does not check if both strings are empty.

Categories