How to solve this CodeIgniter error message? "Notice: Trying to get property of non-object in CodeIgniter"

431 views Asked by At

I am testing the app I created for possible potential bugs and fixing some security holes into it. It came across my mind to check the database and table of the app exist and if it does it runs the code and if the tables does not exist, it will echo a warning message. However, whenever I am testing a feature, I am getting an error saying, Trying to get property 'project_name' of non-object. Here is the code in my model to which I am testing if the table and column exist:

public function get_project($id){
            if ($this->db->field_exists('id','projects') == FALSE) {

                $this->db->where('id', $id);

                $query = $this->db->get('projects');

                    if ($query->num_rows() > 0) {
                        return $query->row();   
                    }return false;
            }else{
                echo "Table and column does not exist!";
            }
        }

As you can see, the line where in I am testing if the field exist where the value is FALSE in order for me to display the error warning in the else statement. However, whenever I am doing this, I am getting an error saying Trying to get property 'project_name' of non-object in my views. Here is the code in my view:

    <h3>Project Name:<?php echo $project_data->project_name; ?></h3>
    <h3>Date Created:<?php echo $project_data->date_created; ?><h3>
    <h3>Description:</h3>
    <p class='projects-description'>
        <?php echo $project_data->project_body; ?>
    </p>
2

There are 2 answers

7
Ray A On

you have the wrong testing for the field if it is exist or not,

please change this line from:

if ($this->db->field_exists('id','projects') == FALSE) {

To

if ($this->db->field_exists('id','projects') != FALSE) {

then you will be good to go!

Edit, Surround the above code inside

if ($this->db->table_exists('yourtablename') )
{
  // table exists
}
else
{
  // table does not exist
}
0
Manish Yadav On

you have wrong if statement it is true or blank, please change this line :

      if ($this->db->field_exists('id','projects')==FALSE) {

use this line

       if ($this->db->field_exists('id','projects')) {

here ..

       public function get_project($id){

        if ($this->db->field_exists('id','projects')) { //its already check true 

            $this->db->where('id', $id);

            $query = $this->db->get('projects');

                if ($query->num_rows() > 0) {
                    return $query->row();   
                }return false;
        }else{
            echo "Table and column does not exist!";
        }
    }

}