chowwy
chowwy

Reputation: 1126

simple codeigniter query + results display won't display

I'm trying to display data from my database in a Codeigniter view. Seems like it should be simple, but it's just not working.

I'm getting 2 errors: undefined variable ($movielist, in the view) and invalid argument for php foreach, also in the view.

Any idea how I can get this to work? Code below.

Controller

function displayMovies() {

$this->load->model('movie_list_model');

$data['movielist'] = $this->movie_list_model->getList();

$this->load->view('movielist_view', $data);
}

Model

function getList() {

        $query = $this->db->query('SELECT firstname, lastname, favorite_movie FROM movies');
        return $query->result();


        if ($query->num_rows() > 0) {

        foreach ($query->result_array() as $row)
        {
             echo $row['firstname'];
             echo $row['lastname'];
             echo $row['favorite_movie'];
        }   
    }

View

      <?php foreach($movielist as $mlist)
        {
            echo  $mlist->firstname . '<br />'; 
            echo  $mlist->lastname . '<br />'; 
            echo  $mlist->favorite_movie; 
        }
      ?>

Upvotes: 0

Views: 3198

Answers (1)

Seabass
Seabass

Reputation: 1983

If( the query doesn't find any rows, it will return null, resulting in the undefined error in your view. The invalid argument error is because you can't iterate through null.

A safety would be including something like this in your view:

if($movielist)
{
    /* foreach() {} */
}

Also, your model should only return data (not echo it).

function getList() {
    $query = $this->db->query('SELECT firstname, lastname, favorite_movie FROM movies');
    return $query->result(); /* returns an object */
    // Alternatively:
    // return $query->result_array(); /* returns an array */
}

I also recommend using Active record:

function getList() {
    $this->db->select('firstname');
    $this->db->select('lastname');
    $this->db->select('favorite_movie');

    $query = $this->get('movies');
    return $query->result();
}

Good luck!

Upvotes: 1

Related Questions