news.php代碼如下:
<pre name="code" class="php"><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class News extends CI_Controller{
public function __construct()
{
parent::__construct();
#載入news_model,載入之後可以使用$this->news_model來操作
$this->load->model('news_model');
}
//顯示添加新聞的表單
public function add()
{
$this->load->view('add.html');
}
//完成新聞的添加
public function insert()
{
#獲取表單提交的數據
$data['title'] = $_POST['title'];
$data['author'] = $_POST['author'];
$data['content'] = $_POST['content'];
$data['add_time'] = time();
#調用news_model的方法即可
if($this->news_model->add_news($data)){
echo "添加成功";
}else{
echo "添加失敗";
}
}
//顯示新聞列表
public function index(){
#調用list_news方法得到數據
$data['news'] = $this->news_model->list_news();
#分配到視圖
$this->load->view('list.html',$data);
}
//編輯新聞
public function edit(){
}
//刪除新聞
public function delete(){
}
}
News_model.php代碼:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class News_model extends CI_Model{
const TBL = 'news';
//構造函數
public function __construct()
{
//調用父類構造函數,必不可少
parent::__construct();
//手動載入數據庫操作類
$this->load->database();
}
/**
*@access public
*@param $data array
*@return bool 成功返回true,失敗返回false
*/
public function add_news($data){
//使用AR完成插入操作
return $this->db->insert(self::TBL,$data);
}
/**
*@access public
*@return array 查詢結果
*/
public function list_news(){
$query = $this->db->get(self::TBL);
return $query->result_array();
}
public function edit_news(){
}
public function delete_news(){
$query = $this->db->delete(oid);
}
}
add.html代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
<title>添加新聞</title>
<style>
</style>
</head>
<body>
<form action="<?php echo site_url('news/insert')?>" method="POST"/>
<!--form action="news.php" method="post"-->
<fieldset>
<legend>添加新聞</legend>
<ul>
<li><label for="">標題</label><input type="text" name="title"/></li>
<li><label for="">作者</label><input type="text" name="author"/></li>
<li><label for="">正文</label><textarea name="content" id="" cols="100" rows="7"></textarea></li>
<li><label for=""> </label><input type="submit" name="btn" value="添加"/></li>
<input type="hidden" name="act" value="add" />
</ul>
</fieldset>
</form>
</body>
</html>
注意點:構造函數這裏__construct是兩個下劃線,method方法後最好是大寫,比如POST,GET等等。
第一個添加新聞的案例編碼結束後,總結CI的執行流程大致爲:
控制器:囊括了所有可能的操作函數或者方法
一般首先加載視圖,也就是HTML文件,頁面的操作由<form action="<?php echo site_url('news/insert')?>" method="POST"/></form>這樣一個表單操作來觸發後續流程,這裏觸發的操作就是一個insert的操作,這個insert的函數或者方法依然是控制器中news這個擴展類的函數,而由於insert涉及到了操作數據庫,所以首先必須將操作數據庫的model擴展類在控制器中首先加載進來,這樣insert函數就可以直接調用news_model中方法了。