开发者

Unable to load database table contents with ActiveRecord

I'm new to CodeIgniter and am having trouble loading the contents of a simple database table (named 'entries') with the ActiveRecord syntax--I'm getting a blank page.

Here is my controller:

class Blog extends CI_Controller {
    function Blog() {
        parent::__construct();
    }

    function all() {
        $this->load->model('Entries');
        $data['rows'] = $this->Entries->load_all();
        $this->load->view('view_all', $data);
    }
}

Model:

class Entries extends CI_Model {
    function __construct() {
        parent::__construct();
        $this->load->database();
    }

    function load_all() {
        $query => $this->db->get('entries');
        return $query->result();
    }
}

View:

<ol>
    <? foreach($rows as $row): ?>
        <li><?= $row->title ?></li>
    <? endfor开发者_Go百科each; ?>
</ol>

NOTE: I can get it to work if I change the load_all() function in my model to:

function load_all() {
    $sql = "SELECT * FROM entries";
    $query = $this->db->query($sql);
    return $query->result_array();
}

And my view to:

<ol>
    <? foreach($rows as $row): ?>
        <li><?= $row['title'] ?></li>
    <? endforeach; ?>
</ol>

Any thoughts why the ActiveRecord syntax isn't working?

FYI: CodeIgniter 2.0, MySQL, PHP 5.3.2. Oh and the $active_record setting in config/database.php is TRUE.

Thanks.


In your load_all() function you have a misplaced '=>' after $query. It should be a '='

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

Then you can return your $query object.

return $query->result();

On another note, you don't need to use capital letters when calling your model. Even though the model name may be capitalized, the object function call is allowed to be lowercase. Your code won't break if you use capital, you just don't need to.


I think you need to tell your view that the query result needs to be extracted:

<ol>
    <? foreach($rows->result() as $row): ?>
        <li><?= $row->title ?></li>
    <? endforeach; ?>
</ol>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜