转载:http://blog.csdn.net/pleasecallmewhy/article/details/8575955
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>
效果图 :