Navid
Navid

Reputation: 495

passing data in model trough controller in codeigniter

I've heard about codeigniter couple of times so i was curious and thought why not. I took some tutorials and was very delighted to see how the framework worked. Now i've the following problem i want to passing the data i've made in my model trough my controller and showing this in my view but i always run to the folowing error: Fatal error: Call to a member function query() on a non-object in C:\wamp\www\codeigniterTest\application\models\leden_model.php on line 9. The funny thing about this error is, when i google on this issue a lot of forum topics is about this issue but nowhere i get the right answer. my code looks like this.

codegniter version 2.03

class Leden extends CI_Controller {

function __construct(){
    parent::__construct();
}

function index()
{
    $this->load->model('leden_model');
    $ledenModel = new Leden_model();
    $data = $ledenModel->allLeden();
    $this->load->view('leden_overzicht',$data);
}
}


<?php
class Leden_model extends CI_Model {

    function __construct(){
        parent::__construct();
    }

    function allLeden(){
        $query = $this->db->query("SELECT * FROM leden");
        foreach ($query->result_array() as $row)
        {
           echo $row['Naam'];
           echo $row['Achternaam'];
           echo $row['Email'];
        }

        return $query;
    }

}

?>

When i'm doing the query in my controller then i'm getting the results i want, why not in my model?

my question is what am i doing wrong?

Upvotes: 1

Views: 3346

Answers (2)

ciuser
ciuser

Reputation: 171

Leden_model.php

?php

class Leden_model extends CI_Model {

function __construct(){
    parent::__construct();
}

function allLeden()
{
    $data = array();
    $this->db->select();
    $query = $this->db->get('leden');

    if ($query->num_rows() > 0)
    {
        foreach ($query->result_array() as $row)
        {
            $data[] = $row;
        }
    }
    $query->free_result();
    return $data;
}

Leden_controller.php

?php

class Leden extends CI_Controller {

function __construct()
{
    parent::__construct();

    $this->load->model('leden_model');
}

function index() {

$data['leden_data'] = $this->ledenModel->allLeden();
$this->load->view('leden_overzicht',$data); } 

}

leden_overzicht.php

?php

if (count($leden_data)) {

foreach ($leden_data as $key => $list) {

echo $list['Naam'] . " " . $list['Achternaam'] . " " . $list['Email'] . "
";

} } else { echo "No data."; }

Upvotes: 3

ciuser
ciuser

Reputation: 171

did you load database? example:

$this->load->database();

Upvotes: 0

Related Questions