# application/config/autoload.php
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('model1', 'model2');
|
*/
$autoload['model'] = array();
$this->load->model('Model_name', '', TRUE);
$this->load->model('Model_name');
$this->Model_name->function();
$config['hostname'] = "localhost";
$config['username'] = "myusername";
$config['password'] = "mypassword";
$config['database'] = "mydatabase";
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$this->load->model('Model_name', '', $config);
# application/model/BlogModel.php
class BlogModel extends CI_Model {
var $title = '';
var $content = '';
var $date = '';
function __construct()
{
// 呼叫模型(Model)的建構函數
parent::__construct();
}
function get_last_ten_entries()
{
$query = $this->db->get('entries',10);
return $query->result();
}
function insert_entry()
{
$this->title = $_POST['title']; // 請看一下下面的注意事項
$this->content = $_POST['content'];
$this->date = time();
$this->db->insert('entries', $this);
}
function update_entry()
{
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->date = time();
$this->db->update('entries', $this,array('id' => $_POST['id']));
}
}
因應簡化直接使用$_POST變數,一般不是這樣使用。
# application/controller/Blog.php
class Blog_controller extends CI_Controller {
function blog()
{
$this->load->model('BlogModel', 'Blog');
$data['query'] = $this->Blog->get_last_ten_entries();
$this->load->view('blog',$data);
}
}
$data['query'] query這個key改為result會比較適當