• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Error: Trying to get property of non-object

#1
[eluser]alexandervj[/eluser]
I'm getting this error from my model. I'm pretty sure its because the function is looking in the database table for a row that doesn't exist. Is there a way to make it so that if the row its looking for doesn't exist it just returns $data['sent'] = 0? Here is my function in my model. It works great if the row its looking for is in the database

Code:
function getSent(){
        
        $this->db->where('submit_time', $this->uri->segment(3));  //
        $tempsent = $this->db->get('0_request_details');  // here is the problem - if the function doesnt find the row that matches the line above it doesnt know what to do.
        
        if($tempsent){
            
            $sent = $tempsent->row();
            $data['sent'] = $sent->is_sent;
            
        }
        
        return $data;
    
}

#2
[eluser]Tim Brownlaw[/eluser]
To make this more generic, it's a good idea to not hardcode the submit_time's source!
So I'd be passing it as a parameter. You might want to change where it comes from later...

Then before you call it, in this case the $submit_time is coming from $this->uri->segment(3), I'd be validating $this->uri->segment(3) exists and is the correct format / data type.

To be even more strict, I'd also be ensuring that $submit_time is indeed the correct format inside the function itself and maybe throwing an exception or return something to indicate it got "bad data". (which I've not included in the code below... that's something for you to look up!)

Code:
function getSent($submit_time) {
  $this->db->where('submit_time', $submit_time);
  $tempsent = $this->db->get('0_request_details');        
  if($tempsent !== FALSE AND $tempsent->num_rows() > 0) { // Did we get a valid result?
    $sent = $tempsent->row();
    $data['sent'] = $sent->is_sent;
  }
  else {  
   $data['sent'] = 0; // No Result found so return the default!
  }
  return $data;
}

So if you don't get a result back - you will get $data['sent'] = 0.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2017 MyBB Group.