Setup first MVC:
SQL:
CREATE TABLE IF NOT EXISTS `posts` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`content` text NOT NULL,
`created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` INT(4) NOT NULL,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
CREATE TABLE IF NOT EXISTS `posts` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` text NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` int(4) NOT NULL,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Create file: 'application/model/post.php':
<?php
class Post extends CI_Model {
function get_posts( $num = 20, $start = 0 ) {
$this->db->select()->from( 'posts' )->where( 'active',1 )->order_by( 'created', 'desc' )->limit( $num, $start );
$query = $this->db->get();
return $query->result_array();
}
} |
<?php
class Post extends CI_Model {
function get_posts( $num = 20, $start = 0 ) {
$this->db->select()->from( 'posts' )->where( 'active',1 )->order_by( 'created', 'desc' )->limit( $num, $start );
$query = $this->db->get();
return $query->result_array();
}
}
Create file: 'application/controllers/posts.php':
<?php
class Posts extends CI_Controller {
function index() {
$this->load->model( 'post' );
$data['posts'] = $this->post->get_posts();
$this->load->view( 'post_index', $data );
}
} |
<?php
class Posts extends CI_Controller {
function index() {
$this->load->model( 'post' );
$data['posts'] = $this->post->get_posts();
$this->load->view( 'post_index', $data );
}
}
Create file: 'application/views/post_index.php':
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>post index</title>
</head>
<body>
<?php
if( ! isset( $posts ) ) {
?>
<p>There are no posts.</p>
<?php
} else {
foreach( $posts as $post ) {
?>
<h3><a href="<?php echo base_url(); ?>posts/post/<?php echo $post['id']; ?>"><?php echo $post['title']; ?></a></h3>
<p><?php echo substr( strip_tags( $post['content'] ), 0, 200 ).'...'; ?></p>
<?php
}
}
?>
</body>
</html> |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>post index</title>
</head>
<body>
<?php
if( ! isset( $posts ) ) {
?>
<p>There are no posts.</p>
<?php
} else {
foreach( $posts as $post ) {
?>
<h3><a href="<?php echo base_url(); ?>posts/post/<?php echo $post['id']; ?>"><?php echo $post['title']; ?></a></h3>
<p><?php echo substr( strip_tags( $post['content'] ), 0, 200 ).'...'; ?></p>
<?php
}
}
?>
</body>
</html>
Now you should add some items to database and visit such link: http://localhost/codeigniter/index.php/posts