2013-01-19 40 views
0

我嘗試在模型上查詢,但它給出了一個錯誤。 如果我把查詢在控制器中工作正常。 這是我的控制器(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 */ 

這是我的模型(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 */ 
?> 

然後它吐出一個錯誤:

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

我在做一些錯誤的事情,我錯過了嗎?

回答

3

$this->db->query就夠了。您應該刪除$query = $this->db->get(); 因此,代碼將成爲

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; 

} 

編輯:如果你想要得到你應該使用$query->result()返回對象的數組或$query->result_array()返回數組的結果。 更多信息 - http://ellislab.com/codeigniter/user-guide/database/results.html

+0

謝謝!是工作! – user1993418

+0

如果我的答案已解決問題,請接受它 - http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – lam3r4370