我尝试查询模型,但它会出错。 如果我把查询放在控制器中它工作正常。 这是我的控制器(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
我做错了什么,我错过了吗?
答案 0 :(得分: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