Boy Pasmo
Boy Pasmo

Reputation: 8471

can't do queries undefined property

I'm new to CI. And just wanted to know where did I go wrong. Seems that I can't connect to my database. So I tried loading the database in the controller, just to see if it can connect and I can do queries. I did configure the database.php and set everything up. But it displays as this.

A PHP Error was encountered

Severity: Notice

Message: Undefined property: Blog::$db

Filename: controllers/blog.php

contollers/blog.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Blog extends CI_Controller {

    public function index() {
        $this->load->model("blogmodel");
        $articles = $this->blogmodel->get_articles_list();

        echo $articles;
    }
}

blogmodel.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Blogmodel extends CI_Model {

    function get_articles_list() {
        $list = $this->db->query("SELECT * FROM foo");
        return $list;
    }
}

Hope you can help me. Thanks.

Upvotes: 0

Views: 855

Answers (1)

Kai Qing
Kai Qing

Reputation: 18833

So you have an answer to accept:

The initial issue was you were not autoloading the database library. In this file:

application/config/autoload.php

You would add the database to the list:

$autoload['libraries'] = array('database');

As for your string issue - get_article_list() is returning an object. You can use $articles->result() to iterate through the results, or use something like $articles->num_rows() to see how many results there were, etc.

So where you echo $articles, you may intend to echo something like this:

foreach($articles->result() AS $article)
{
    echo $article->title . "<br>";
}

Where $article->title is obviously replaced with an actual field from your article table.

Upvotes: 1

Related Questions