Search code examples
phpcodeigniternullvar-dump

Invalid argument supplied for foreach() due to var_dump is null


Yesterday when I var_dump($this->m_test->result_getGrades());it gave me an array[1356] now it returned null. Can anyone help me figure out why it's NULL? I'm still new in PHP and Codeigniter and its pretty stressful figuring out why I can't retrieve any data from my database.

I assume the reason why I have this error because ($this->m_test->result_getGrades()) is NULL

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/v_display.php

Line Number: 7

Also, What are the factors why I can't retrieve any data from my database? For future references

This is my code:

Controller c_test.php

function getGrades() {
       $data['query'] = $this->m_test->result_getGrades(); 
       $this->load->view('v_display', $data);
    }

Model m_test.php

function result_getGrades()
    {
          $this->db->select('grades.blockcode,subjectblocking.subjectcode,subjects.description,grades.final');
          $this->db->from('grades');
          $this->db->join('subjectblocking','grades.blockcode=subjectblocking.blockcode');
          $this->db->join('subjects','subjectblocking.subjectcode=subject.subjectcode');
          $this->db->where('2013-F019');
          $query=$this->db->get();          
    }

Views v_display.php

<?php foreach ($query as $row): ?>

               <?php echo $row->studentid;?><br>
               <?php echo $row->subjectcode;?><br>
               <?php echo $row->description;?><br>
               <?php echo $row->final;?><br>


         <?php endforeach; ?>

Thank you once again! :)


Solution

  • There are many faults in your result_getGrades() function :

    function result_getGrades()
    {
        $this->db->select('grades.blockcode,subjectblocking.subjectcode,subjects.description,grades.final');
        $this->db->from('grades');
        $this->db->join('subjectblocking','grades.blockcode=subjectblocking.blockcode');
        $this->db->join('subjects','subjectblocking.subjectcode = subjects.subjectcode');
        $this->db->where('your_field', '2013-F019');
    
        $query = $this->db->get()->result();
    
        return $query;        
    }
    

    There was :

    • add the return $query;

    • field name in your where clauses

    • subject to subjects in your join