$config['base_url'] = "http://localhost/ci/";
$db['default']['username'] = "gilang"; $db['default']['password'] = "chandrasa"; $db['default']['database'] = "ci_test"; $db['default']['dbdriver'] = "mysql";
You will see welcome page from CodeIgniter framework.
If you see this page, then you've finished your CodeIgniter installation.
After finishing the installation, lets go have some fun with CodeIgniter. We're building simple microblog.
CREATE TABLE `microblog` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `content` VARCHAR( 255 ) NOT NULL , `post_date` DATE NOT NULL );
Don't forget to set your database setting, and then set to autoload database setting in application/config/autoload.php
$autoload['libraries'] = array('database');
And set to autoload url helper.
$autoload['helper'] = array('url');
Create application/model/microblog_model.php, this model will interact with our microblog table. Microblog model has 2 functions, get_posts to get all post from database and add_post to set new post and save it to database.
<?php
class microblog_model extends Model {
function get_posts()
{
$this->db->order_by("post_date", "desc");
$query = $this->db->get('microblog');
return $query->result();
}
function add_post($post)
{
$this->db->set('post_date', 'NOW()', FALSE);
$this->db->insert('microblog', $post);
}
}
?>
We'll have 2 pages for this demo, index page for showing all post, and add page for adding new post. So, we create 2 functions under microblog controller.
<?php
class microblog extends Controller {
function __construct() {
parent::__construct();
$this->load->model('microblog_model');
}
function index()
{
$post_list = $this->microblog_model->get_posts();
$data = array(
'post_list' => $post_list
);
$this->load->view('microblog/index', $data);
}
function add()
{
if ($_POST) {
$micropost = $this->input->post('micropost');
$post = array(
'content' => $micropost,
);
$this->microblog_model->add_post($post);
redirect('microblog');
}
$this->load->view('microblog/add');
}
}
?>
Create microblog folder under application/views, and we create index.php and add.php
This view will show all posts from database.
<html>
<head>
<title>Microblog</title>
</head>
<body>
<a href="<?= site_url('microblog/add')?>">Add post</a>
<? if (isset($post_list)) : ?>
<? foreach ($post_list as $post) : ?>
<div class="post">
<p><?= $post->content ?></p>
<small><?= $post->post_date ?></small>
</div>
<? endforeach ?>
<? else: ?>
<div class="post">
<p>No posts.</p>
</div>
<? endif ?>
</body>
</html>
Add view, showing add form for new post.
<html>
<head>
<title>Microblog</title>
</head>
<body>
<form method="post" action="">
<label>your micropost :</label><br/>
<textarea name="micropost"></textarea><br/>
<input type="submit" value="send" />
</form>
</body>
</html>