user1993418
user1993418

Reputation: 1

I can't query database on model

I try to query on model but it gives an error. If I put the query in controller it works fine. This is my controller(Home.php):

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

class Home extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->helper('form');
        $this->load->helper('asset');
        $this->load->database();
        $this->load->library('table');
    }

    public function index()
    {   
        $this->load->model('News');
        $resultNews = $this->News->queryNews();
        $data['resultNews'] = $resultNews;
        $this->load->view('front/index',$data);

    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

This is my model(News.php) :

<?php
if( !defined('BASEPATH')) exit('No direct script access allowed');
class News extends CI_Model {

    function __construct(){
        parent::__construct();
        $this->load->database();
    }

    function queryNews(){
        $this->db->query("SELECT * FROM  `news` WHERE news_show_date >= CURDATE() ORDER BY news_show_date DESC LIMIT 0 , 2");
        $query = $this->db->get();
        return  $query;

    }   
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
?>

And then it's spitting out an error:

A Database Error Occurred
Error Number: 1096
No tables used
SELECT *
Filename: C:\AppServ\www\hijet\system\database\DB_driver.php
Line Number: 330

Am I doing something that is wrong and I am missing it?

Upvotes: 0

Views: 432

Answers (1)

user370306
user370306

Reputation:

$this->db->query is enough. You should remove $query = $this->db->get(); So the code will become

    function queryNews(){
    $query = $this->db->query("SELECT * FROM  `news` WHERE news_show_date >= CURDATE() ORDER BY news_show_date DESC LIMIT 0 , 2");
    return  $query;

}

EDIT: If you want to get the results you should use $query->result() which returns an array of objects or $query->result_array() which returns an array. More info here - http://ellislab.com/codeigniter/user-guide/database/results.html

Upvotes: 3

Related Questions