ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

Error: Trying to get property of non-object

October 22, 2014 3:45pm

Subscribe [2]
  • #1 / Oct 22, 2014 3:45pm

    alexandervj

    7 posts

    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

    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 / Oct 23, 2014 11:33am

    Tim Brownlaw

    189 posts

    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!)

    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.

     

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases