CodeIgniter 入门实践(新闻系统)

CodeIgniter 入门实践(新闻系统)


DATE: 2017-10-11 13:10:58

参考官方手册,最终修改内容作一总结。

加载静态内容

application/controllers目录下新建pages.php文件。

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Pages extends CI_Controller {
    public function view($page = 'home')
    {
        if ( ! file_exists(APPPATH.'views/pages/'.$page.'.php'))
        {
            // Whoops, we don't have a page for that!
            show_404();
        }
        $data['title'] = ucfirst($page); // Capitalize the first letter
        $this->load->view('templates/header', $data);
        $this->load->view('pages/'.$page, $data);
        $this->load->view('templates/footer', $data);
    }
}

views目录下新建目录pages和templates。

目录:views/pages/
文件:about.php home.php (这两个文件内容随意,暂不Care)

目录:views/templates/
文件:header.php footer.php

header.php

<html>
    <head>
        <title>CodeIgniter Tutorial</title>
    </head>
    <body>
        <h1><?php echo $title; ?></h1>

footer.php

        <em>&copy; 2015</em>
    </body>
</html>

浏览器输入地址:

http://localhost/index.php/pages/view

这里写图片描述

在文件application/config/routes.php中增加路由规则

$route['default_controller'] = 'pages/view';
$route['(:any)'] = 'pages/view/$1';

效果如图
这里写图片描述

读取新闻条目

application/models/ 目录下新建文件 News model.php ,写入代码:

<?php
class News_model extends CI_Model {
    public function __construct()
    {
        $this->load->database();
    }
    
    public function get_news($slug = FALSE)
    {
        if ($slug === FALSE)
        {
            $query = $this->db->get('news');
            return $query->result_array();
        }
        $query = $this->db->get_where('news', array('slug' => $slug));
        return $query->row_array();
    }
}

连接数据库

CREATE TABLE news (
    id int(11) NOT NULL AUTO_INCREMENT,
    title varchar(128) NOT NULL,
    slug varchar(128) NOT NULL,
    text text NOT NULL,
    PRIMARY KEY (id),
    KEY slug (slug)
);

application/controllers/目录下创建News.php
加入代码

<?php
class News extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->model('news_model');
        $this->load->helper('url_helper');
    }
    public function index()
    {
        $data['news'] = $this->news_model->get_news();
        $data['title'] = 'News archive';
        $this->load->view('templates/header', $data);
        $this->load->view('news/index', $data);
        $this->load->view('templates/footer');
    }
    public function view($slug = NULL)
    {
        $data['news_item'] = $this->news_model->get_news($slug);
        if (empty($data['news_item']))
        {
            show_404();
        }
        $data['title'] = $data['news_item']['title'];
        $this->load->view('templates/header', $data);
        $this->load->view('news/view', $data);
        $this->load->view('templates/footer');
    }
}

application/views/目录下新建news/index.php 文件,代码如下:

<h2><?php echo $title; ?></h2>
<?php foreach ($news as $news_item): ?>
<h3><?php echo $news_item['title']; ?></h3>
<div class="main">
    <?php echo $news_item['text']; ?>
</div>
<p><a href="<?php echo site_url('news/'.$news_item['slug']); ?>">View article</a></p>
<?php endforeach; ?>

在目录application/views/news/下创建文件view.php,写入代码

<?php
echo '<h2>'.$news_item['title'].'</h2>';
echo $news_item['text'];

在文件application/config/routes.php中增加路由规则

$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';

出错

404 Page Not Found
The page you requested was not found.

调整路由表文件application/config/routes.php

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['default_controller'] = 'pages/view';
$route['(:any)'] = 'pages/view/$1';

错误变为:

A PHP Error was encountered

Severity: Warning

Message: mysqli::real_connect(): (HY000/1045): Access denied for user ''@'localhost' (using password: NO)

Filename: mysqli/mysqli_driver.php

Line Number: 201

Backtrace:

File: D:\wamp64\www\application\models\News_model.php
Line: 5
Function: database

File: D:\wamp64\www\application\controllers\News.php
Line: 6
Function: model

File: D:\wamp64\www\index.php
Line: 315
Function: require_once

A Database Error Occurred

Unable to connect to your database server using the provided settings.

Filename: D:/wamp64/www/system/database/DB_driver.php

Line Number: 436

数据库的问题。那么,创建数据库和数据表。操作记录如下:

mysql> create database blog;
Query OK, 1 row affected (0.00 sec)

mysql> use blog
Database changed
mysql> CREATE TABLE news (
    -> id int(11) NOT NULL AUTO_INCREMENT,
    -> title varchar(128) NOT NULL,
    -> slug varchar(128) NOT NULL,
    -> text text NOT NULL,
    -> PRIMARY KEY (id),
    -> KEY slug (slug)
    -> );
Query OK, 0 rows affected (0.02 sec)

配置后,问题并没有解决。
修改数据库配置文件 /application/config/database.php,配置参数:

    'dsn'    => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '@yixzm',
    'database' => 'blog',
    'dbdriver' => 'mysqli',

效果如图
这里写图片描述

创建新闻条目,即写数据

在文件 application/views/news/create.php 中创建一个新视
图。

<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create'); ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>

application/controllers/News.php中,增加function。

    public function create()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');
        $data['title'] = 'Create a news item';
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('text', 'Text', 'required');
        if ($this->form_validation->run() === FALSE)
        {
            $this->load->view('templates/header', $data);
            $this->load->view('news/create');
            $this->load->view('templates/footer');
        }
        else
        {
            $this->news_model->set_news();
            $this->load->view('news/success');
        }
    }

application/models/News model.php增加代码

    public function set_news()
    {
        $this->load->helper('url');
        $slug = url_title($this->input->post('title'), 'dash', TRUE);
        $data = array(
            'title' => $this->input->post('title'),
            'slug' => $slug,
            'text' => $this->input->post('text')
            );
        return $this->db->insert('news', $data);
    }

调整路由表文件application/config/routes.php

$route['news/create'] = 'news/create';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';

打开创建页面,写入信息
这里写图片描述

提交报错:

An Error Was Encountered Unable to load the requested file:
news/success.php

/applications/views/news/目录下创建success.php,用于反馈用户信息提交成功。
返news界面(/http://localhost/index.php/news/),可以看到效果:
这里写图片描述

至此,小新闻系统测试成功。耶!

版权声明

弈心博客


本文首发site_name,转载请附上博文链接!