Bước 1: Tạo cơ sở dữ liệu có trúc như sau và chèn thêm 2-3 bản ghi mẫu
CREATE TABLE tintuc (
id int(11) NOT NULL AUTO_INCREMENT,
tieude varchar(128) NOT NULL,
noidung text NOT NULL,
PRIMARY KEY (id)
);
Bước 2: Cấu hình lại file kết nối đến file database bằng cách truy cập vào file database.php trong đường dẫn application/config/
$db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => '', 'password' => '', 'database' => '', 'dbdriver' => 'mysqli', ....
- hostname: điền tên máy chủ.
- username: điền tên truy cập database
- password: điền mật khẩu truy cập database
- database: điền tên database
Bước 3: Truy cập đường dẫn application/models/ tạo file tintuc_model.php
<?php
class tintuc_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_news()
{
$query = $this->db->get('tintuc');
return $query->result_array();
}
}
- function __constuct() để kết nối đến database
- funtion get_tintuc() để lấy toàn bộ dữ liệu trong bảng tintuc
Bước 4: Tại đường dẫn application/controllers/ tạo fie tintuc.php
<?php
class tintuc extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('tintuc_model');
$this->load->helper('url_helper');
}
public function index()
{
$data['tin'] = $this->tintuc_model->get_news();
$this -> load -> view ( 'tintuc/index', $data );
}
}
- function index sẽ load thủ tục get_news() trong model và gửi đến file index
Bước 5: Tạo file index.php trong thư mục application/views/pages/
<?php foreach ($tin as $tin_item): ?>
<h3><?php echo $tin_item['tieude']; ?></h3>
<div class="main">
<?php echo $tin_item['noidung']; ?>
</div>
<?php endforeach; ?>
Bước 6: Cấu hình file routes.php trong thư mục application/config/ để hiển thị nội dung tin tức khi truy cập máy chủ
$route['default_controller'] = 'tintuc'; $route [ 'tintuc/(:any)' ] = 'tintuc/view/$1' ; $route [ 'tintuc' ] = 'tintuc' ;
- Giờ bạn có thể truy cập đường dẫn máychủ để xem hiển thị kết quả.




