相關連結:
關於CodeIgniter的入門請參照這篇文章:[PHP]架構教程:CodeIgniter架構的簡易使用
使用的平台是SAE:[SAE]免費伺服器:新浪雲端服務器SAE的註冊與使用
BAE中的MySQL使用:[PHP]如何在百度(BAE)和新浪(SAE)的雲平台使用PHP串連MySQL並返回結果資料
1.首先是控制器部分,Blog.php作為Controller即控制器:
<?php header('Content-Type:text/html;charset=utf-8');class Blog extends CI_Controller {function __construct(){//繼承父類的構造方法,不寫報錯parent::__construct();//載入架構中的相關helper$this->load->helper('url');$this->load->helper('form');}function index(){//為即將跳轉的版面設定相關資料$data['title']="My Blog Title";$data['heading']="My Blog Heading";$data['todo']=array('eat','sleep','call');//串連資料庫並返回查詢結果$sql = "SELECT * FROM `Entries` LIMIT 0, 30 ";//初始化MySQL資料庫$mysql= new SaeMysql();$sqlData = $mysql->getData($sql);//將資料庫的結果傳入data中$data['query']=$sqlData;//使用變數$data向目標網頁傳入資料$this->load->view('blog_view',$data);}function comments(){//為即將跳轉的版面設定相關資料$data['title']="My Comment Title";$data['heading']="My Comment Heading";//串連資料庫並返回查詢結果$sql = "SELECT * FROM `Comments` where `entry_id`=".$this->uri->segment(3);//初始化MySQL資料庫$mysql= new SaeMysql();$sqlData = $mysql->getData($sql);//將資料庫的結果傳入data中$data['query']=$sqlData;//使用變數$data向目標網頁傳入資料$this->load->view('comment_view',$data);}function comment_insert(){//插入POST提交的評論資料到MySQL中$sql = "INSERT INTO `Comments` (`entry_id`, `body`, `author`) VALUES ('".$_POST['entry_id']."', '".$_POST['body']."', '".$_POST['author']."');"; //初始化MySQL資料庫$mysql= new SaeMysql();$mysql->runSql($sql);redirect('blog/comments/'.$_POST['entry_id']);}}?>
2.接下來是View即視圖部分,blog_view是部落格列表的視圖:
<html><head><title><?php echo $title?></title></head><body><h1><?php echo $heading?></h1><?php //輸出從資料庫中讀取到的文章列表foreach($query as $key=>$value): ?><h3><?=$value['title']?></h3></br><p><?=$value['body']?></p></br><p><?=anchor('blog/comments/'.$value['id'],'Comments')/*插入評論的超連結*/?></p><hr><?php endforeach; ?></body></html>
comment_view是評論列表的內容:
<html><head><title><?php echo $title?></title></head><body><h1><?php echo $heading?></h1><?php if(count($query)>0): /*確保有資料返回*/?><?php //輸出從資料庫中讀取到的文章列表foreach($query as $key=>$value): ?><p><?=$value['body']?></p></br><p><?=$value['author']?></p></br><hr><?php endforeach; ?><?php endif; ?><p><?=anchor('blog','Back to Blog')/*返回部落格頁面*/?></p><?/*提交表單,跳轉到blog的comment_insert方法*/?><?=form_open('blog/comment_insert');?><?=form_hidden('entry_id',$this->uri->segment(3));?><p><textarea name="body" rows ="10"></textarea></p><p><input type="text" name="author"/></p><p><input type="Submit" value="Submit"/></p></form></body></html>
: