You are on page 1of 43

Thomas Myer

Creating
a Blogging
Tool with

Codeigniter
Wiley Publishing, Inc.
Updates, source code, and Wrox technical support at www.wrox.com

Contents
Introducing CodeIgniter
Whats Model-View-Controller?
Why Bother with MVC?

Installing and Configuring CodeIgniter


The Root Folder
The system/Folder
The system/application Folder
Tweaking the Configuration

Getting Started
The Public-Facing Site
Creating the Template View
Creating the Home Page View
Creating the Category View
Creating the Blog Details View
Creating the Login Form
Verifying Logins
Creating the MAdmins Model
Creating the verifyUser() Function
A Small Note about Creating Your First User

Creating the Admin Dashboard


Creating the Dashboard Controller
Building the Admin Area
Creating the Rest of the Admin Functions

Summary
About Thomas Myer

2
2
4

5
6
7
7
8

10
12
14
16
19
20
22
23
24
24
25

25
26
28
34

38
39

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool


with Codeigniter
Lets imagine for a second that youre working on a team of marketers, writers, and designers, and
that the marketing manager requests that you create a blogging tool from scratch. It doesnt have
to be complex, but it cant be any of the off-the-shelf applications available for free on the Web (like
WordPress). It has to be small, efficient, and very fast. Most important, it needs to integrate seamlessly with an existing web site.
Oh, and one more thing: Could we have a working prototype up and running by 5 p.m. today?
You look at your watch and notice that it is 11:25 a.m. You do a quick calculation you have just
enough time to grab lunch and start cracking away at the project with CodeIgniter. No problem,
you think. A blog is pretty simple. Youve seen hundreds (if not thousands) of them in action, and
youve integrated all kinds of code with various models. With CodeIgniter by your side, you
should be able to kick out most of what you need in just a few hours.
You say yes, youll build it, as long as everyone understands that its a working prototype. With
that, you run off to get some lunch and sketch out some basic requirements.
Sound impossible? With CodeIgniter, it isnt. In this Wrox Blox, youll see how to put together a
very simple blogging application in an afternoon. The key here is simple. At the end of the
process, you wont have some kind of WordPress competitor. But you will have a very useful,
portable, and slick little blogging tool that you can add to any existing site (CodeIgniter or not).
Heres a quick run down of what youll end up with:

A public-facing home page that shows the last 10 blog posts

A way to show posts by category

A way to display a single post with comments (and a way for others to comment
on a post)

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


q

An administrative area that requires a username and password for access

An administrative area to manage users, posts, and categories

Now that you know what to build, its time to download CodeIgniter and get the general overview.

Introducing CodeIgniter
CodeIgniter was created by the good folks over at EllisLab, Inc. It is a Model-View-Controller (MVC)
framework with a very small footprint. In form and function, it is very similar to other MVC
frameworks, like Ruby on Rails. Like Ruby on Rails, it requires very little configuration to get started.
Ive been able to create prototype applications within hours of talking to a client, and then refined the
prototypes over the course of a few days.
Its this kind of prototyping power and flexibility, by the way, that will transform the way you work
with clients. It allows you to be responsive and collaborative in ways that youre probably not used to.
Unlike Ruby on Rails, CodeIgniter doesnt require you to adhere to a strict set of coding rules.
For example, you dont have to name your database tables a certain way, and your models another.
Youdont even have to have strictly formatted table fields which makes CodeIgniter an excellent
platform for recoding legacy applications.
Below are a few more great things about CodeIgniter:

There is a growing toolbox of helpers and libraries that help you do your job quickly.

You dont have to learn a complex templating language.

You dont need to work with large-scale monolithic libraries.

You can run your applications in PHP 4 or PHP 5 without too much hassle.

CodeIgniter applications run with exceptional performance.

This section doesnt get into too many more details right now. Youll start seeing the difference once you
start coding. For now, it might be useful to talk a little bit about MVC and why its important. Then
youll get to work.

Whats Model-View-Controller?
Model-View-Controller is a design pattern that allows developers to separate their code cleanly into
three categories:

Models help you maintain data.

Views display data from the model and user interface elements.

Controllers handle user events that interact with models and views.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


The important thing to remember is that MVC takes the user into account it begins with them. Its the
user who clicks a link, moves the mouse, or submits a form. Its the controller that monitors this activity
and takes the appropriate action (such as manipulating the model and updating the view).
Because of MVCs three-part separation, developers can create multiple views and controllers for any
given model without forcing changes in the model design. Similarly, multiple controllers can make use
of any model. This separation allows for easily maintained, portable, and organized applications.
For example, think about an MVC application that allows us to track eCommerce items in an online
store. You would have the following:

A model for product information

Multiple views to show single products, products in a list, products in search results, and so on

At least one controller that would organize those views into destinations, such as index()
(for home page), product_detail(), and search_results()

Drilling down further, an MVC eCommerce application might involve the following flow of events:

1.
2.

The user visits the stores home page.

3.
4.
5.
6.

The models data are then transmitted to the view for the home page.

7.

The cycle begins anew when the user takes another action, such as running a search or clicking a
link.

This simple event requires a controller action for the home page, which makes a quick call to the
model to retrieve the 10 most popular products based on recent sales.

The view (including the data retrieved by the model) is what the user sees in the browser.
The user clicks a link to see details on a particular product.
The underlying controller captures this user input (clicking the link), uses the model to retrieve
the product in question from the database, and then loads the appropriate view.

Another way of thinking about this breakdown of roles is to map it out as follows (see Figure 1):

User Input and Traffic Control = Controller

Data Interaction and Processing = Model

Output = View

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


user
displayed for

interacts with

view

controller

manipulates

updates

model
Figure 1: The Model-View-Controller framework in
action.

This three-part analogy is a much simpler way of looking at things. Some might argue that the approach
is much too simple. After all, its possible, some might argue, to create an MVC application without a
model, or to gang-press view code into the controller. Its not a good idea, but it can be done. For right
now, the simple analogy will hold.

Why Bother with MVC?


Although at first glance the MVC approach seems like a lot of work, it really isnt. When the developer
of the hypothetical MVC eCommerce application wants to change something about the home page, she
asks herself about the nature of the change. Doing so allows her to zero in on the part of the application
on which she needs to work. If the developer wants to:

Change the number of products that get retrieved (or even the order in which the products are
displayed), she updates the model.

Change the way the home page looks, she updates the view.

Add a new page to the application, she first adds a method to the controller and then builds out
any supporting views (to display content in the browser) and models (to gather data from a
database).

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


The beauty of the entire system lies in the fact that none of those hypothetical actions on any given part
of the MVC triumvirate affects the others. Its true that changing the model in some way (retrieving 15
products instead of 10) will change the view, but the developer didnt have to dig through three views
(or controllers) to make that change, then later discover another SQL call embedded in other files that
did the same thing. Theoretically, on large projects, you could have developers who focus only on Views,
Controllers, or Models, thus keeping clean lines of sight on deliverables and responsibilities.

Installing and Configuring CodeIgniter


To get your hands on CodeIgniter, point your browser to www.codeigniter.com and click the
Download CodeIgniter button, as illustrated in Figure 2.

Figure 2: CodeIgniter.com.
Once youve downloaded the Zip archive, double-click it to open it, and place the contents of the archive
in your favorite work area. Once youve done that, take a moment to tour CodeIgniter.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


As you will see, CodeIgniter has a certain folder structure (shown in Figure 3) that looks a bit daunting
at first, but believe me, youll become very familiar with it.

Figure 3: CodeIgniters folder structure.

The Root Folder


The root folder contains an index.php file (called the front controller it basically routes traffic into the
rest of the application), a system/ folder, and a user_guide/ folder. I wont cover the user_guide/ folder,
as it is merely a local copy of the online user guide found at www.codeigniter.com/user_guide/.
If you want to explore the documentation, you can do so at your leisure.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter

The system/Folder
The system/folder is where all the action happens. This folder contains all the CodeIgniter code of
consequence, organized into various folders:

Folder

Description

application

Contains the application youre building, which includes your Models, Views,
Controllers, and other code (like helpers and class extensions). In other words,
this folder is where youll do 99% of your work.

cache

Contains all cached pages for your application.

codeigniter

Where CodeIgniters core classes live. You have almost no reason to go in here.
All of your work occurs in the application folder.

database

Contains core database drivers and other database utilities. Again, theres no
good reason for you to be in this folder.

fonts

Contains font-related information and utilities. Again, theres no reason to


spend any time here.

helpers

Contains standard CodeIgniter helpers (such as Date, Cookie, and URL helpers).
Youll make frequent use of helpers in your CodeIgniter career, and can even
extend helpers thanks to improvements introduced in CodeIgniter version 1.6.

language

Contains language files. You can ignore it for now.

libraries

Contains standard CodeIgniter libraries (to help you with e-mail, calendars, file
uploads, and more). You can create your own libraries or extend (and even
replace) standard libraries, but those are saved in the application/libraries
directory to keep them separate from the standard CodeIgniter libraries.

logs

The folder to which CodeIgniter writes error and other logs. This needs to be
writable if you enable logging.

plugins

Contains plug-ins. Plug-ins and helpers are very similar, in that they both allow
developers to address an issue or create content (like forms, links, etc.) quickly.
The main difference between them is that plug-ins usually consist of one
function, while helpers often have many functions bundled inside them.

The system/application Folder


The most important folder, the one that deserves most of your attention, is the /system/application
folder (and all of its subfolders). Ninety-nine percent of your work will be done right in this folder, so it
deserves your attention. Learning what goes where now will reduce confusion later.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


The system/application folder is broken down into several folders as shown in the following table:

Folder

Description

config

Contains several important files that control your configuration options. There
are files that manage your database setup and other variables that CodeIgniter
needs to know (such as the base URL, which libraries and helpers to autoload,
etc.). The four most important files in this folder are config.php, database.php,
autoload.php, and routes.php.

controllers

Contains the controllers you create for your application.

errors

Comes with standard CodeIgniter error templates for 404 pages, PHP errors,
and others. You are free to modify these templates to make them fit the look and
feel of your application.

hooks

Contains any hooks you create for your application. Hooks are the best way to
extend the CodeIgniter core safely.

libraries

Contains custom libraries you create for your application.

models

Contains the models you create for your application.

views

Contains the views you create for your application.

In other words, the most important folders in the /system/application folder are controllers/, models/,
and views/. Youll spend practically all your development time working with the Models, Views, and
Controllers that you build.
The other very important folder is config/, which contains various important configuration files. Youll
want to open them in an editor for tweaking before starting any project. Most of the time, when you start
a new CodeIgniter project, youll start with the config/ folder.

Tweaking the Configuration


The two most important files in the /system/application/config folder are config.php and
database.php. Whenever you start a new CodeIgniter project, the first two files youll want to work
with are these.

config.php
The config.php file contains a series of configuration options (all of them stored in a PHP array called,
appropriately enough, $config) that CodeIgniter uses to keep track of your applications information
and settings.
The first configuration option you need to set inside of config.php is the base URL of your application.
You do that by setting the absolute URL (including the http:// part) for $config[base_url],
like so:
$config[base_url] = http://www.example.com/test/;

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


Once youve set this configuration option, you can recall it whenever you want using the CodeIgniter
base_url() function (a very handy thing to know). This one feature keeps you from having to rewrite
hard-coded URLs in your application when you migrate from development to test or from test to
production.
The second thing you need to do is set a value for your home page by editing the $config[index_
page] configuration option. CodeIgniter ships with a value of index.php for this option, which
means that index.php will appear in all of your URLs.
After youve set this option value, theres very little to do. For now, leave all the other values at their
default settings:
$config[uri_protocol] = AUTO;
$config[url_suffix] = ;
$config[language] = english;
$config[charset] = UTF-8;
$config[enable_hooks] = FALSE;
$config[subclass_prefix] = MY_;
$config[permitted_uri_chars] = a-z 0-9~%.:_-;
$config[enable_query_strings] = FALSE;
$config[controller_trigger] = c;
$config[function_trigger] = m;
$config[log_threshold] = 0;
$config[log_path] = ;
$config[log_date_format] = Y-m-d H:i:s;
$config[cache_path] = ;
$config[encryption_key] = enter_a_32_character_string_here;
$config[sess_cookie_name] = ci_session;
$config[sess_expiration] = 7200;
$config[sess_encrypt_cookie] = TRUE;
$config[sess_use_database] = FALSE;
$config[sess_table_name] = ci_sessions;
$config[sess_match_ip] = FALSE;
$config[sess_match_useragent] = TRUE;
$config[cookie_prefix] = ;
$config[cookie_domain] = ;
$config[cookie_path] = /;
$config[global_xss_filtering] = TRUE;
$config[compress_output] = FALSE;
$config[time_reference] = local;
$config[rewrite_short_tags] = FALSE

For more details on each of these configuration options, simply read the comments embedded in
/system/application/config/config.php. As you progress through the installation, there will be some
opportunities to talk about configuration options, and this Wrox Blox will bring up some points if its
appropriate.

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


database.php
The database.php file contains all the information required to connect to a database. Currently,
CodeIgniter supports mysql, mysqli, postgres, odbc, and mssql connections. To connect to your database,
simply enter valid information for your hostname, username, password, database name, and database driver.
Each of these is stored in the $db array under the default group, which means you could have
numerous connection groups, each with their own unique name. For example, you could have one set of
connection variables for your development environment and another for your production environment.
As long as youve set the $active_group variable correctly, your application will stay connected.
$active_record = TRUE;
$active_group = default;
$db[default][hostname]
$db[default][username]
$db[default][password]
$db[default][database]
$db[default][dbdriver]
$db[default][dbprefix]
$db[default][pconnect]
$db[default][db_debug]
$db[default][cache_on]
$db[default][cachedir]
$db[default][char_set]
$db[default][dbcollat]

=
=
=
=
=
=
=
=
=
=
=
=

your-host-name;
your-db_username;
your-db_password;
your-db_name;
mysql;
;
TRUE;
TRUE;
FALSE;
;
utf8;
utf8_general_ci;

Other Files
There are other important files in the config/ directory, namely, routes.php and autoload.php. You dont
need to know anything about routes.php right now, but you will want to autoload a few helpers and
libraries before you get started.
Youll want to autoload the Database and Session libraries, so that you dont have to call those libraries
every time you want to query the database or work with CodeIgniter sessions. On the helpers side,
youll be using the URL, Form, and Text helpers constantly, so they might as well be loaded.
$autoload[libraries] = array(database,session);
$autoload[helper] = array(url,form,text,typography);

There is one more task to be done before leaving the autoload.php file: autoloading models. In the days
prior to CodeIgniter 1.6, you had to load a model manually every time you used it in your controller.
Not anymore! You can autoload them and use the model functions at any point.
Although you dont have any models built yet, at various points in this application, youll be building
models and then immediately autoloading them in the autoload.php file.

Getting Star ted


Now that CodeIgniter is installed and configured, youre ready to begin. Take a quick look at the
requirements list before you get too deep. The list includes the following:

10

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


q

A public-facing home page that shows the last 10 blog posts

A way to show posts by category

A way to display a single post with comments (and a way for others to comment on a post)

An administrative area that requires a username and password for access

An administrative area that allows for management of users, posts, and categories

You will translate these requirements into CodeIgniter terms. Eighty percent of this application will be
some kind of administrative dashboard that will be password-protected. The other 20 percent is a series
of public-facing display pages that contain blog posts. You will need to build two sets of controllers for
CodeIgniter:

The first set, which you will call Blog, will contain a handful of functions.

The second group contains multiple controllers, one for the main dashboard and the others for
posts, categories, and users. This set of controllers will be organized under a folder called admin/
in your controllers directory. There will be more about this later, but for now, just know that you
can organize your files into convenient folders.

You will need one model for each database table. Because you will need to track users, posts, categories,
and comments, you need a model for each of those. For the time being, you also need database tables for
each of these models. You will build those database tables as you go.
Here are the database tables you need. First, the categories table:
CREATE TABLE `categories` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL default ,
`shortdesc` varchar(255) NOT NULL default ,
`longdesc` text NOT NULL,
`status` enum(active,inactive) NOT NULL default active,
`sortorder` int(3) NOT NULL default 0,
`parentid` int(11) NOT NULL default 0,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;

Next comes the posts table:


CREATE TABLE `posts` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(255) collate utf8_unicode_ci NOT NULL,
`tags` varchar(255) collate utf8_unicode_ci NOT NULL,
`status` enum(draft,published) collate utf8_unicode_ci NOT NULL,
`body` text collate utf8_unicode_ci NOT NULL,
`category_id` int(11) NOT NULL,
`pubdate` datetime NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;

11

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


Next, the comments table:
CREATE TABLE `comments` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) collate utf8_unicode_ci NOT NULL,
`email` varchar(255) collate utf8_unicode_ci NOT NULL,
`body` varchar(255) collate utf8_unicode_ci NOT NULL,
`post_id` int(11) NOT NULL,
`pubdate` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;

And finally, the users table:


CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(16) NOT NULL default ,
`email` varchar(255) NOT NULL default ,
`status` enum(active,inactive) NOT NULL default active,
`password` varchar(128) NOT NULL default ,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`,`email`)
) ENGINE=MyISAM;

You will also have about a dozen views. Most of them will be for our administrative views, but a few
will be used on the public-facing side of the web application.
Now that you have all of that roughed in, lets create the first controller next.

The Public-Facing Site


The first thing youre going to build is the public area. This is where users go when they want to read
blog posts. You will need some kind of home page, a category home page, a post view page, and some
way to log in to the administrative dashboard. Follow these steps:

1.

Create the controller. Simply create a welcome.php file in /system/applications/controllers/


and put the following basic information in it:

<?php
class Blog extends Controller {
function Blog(){
parent::Controller();
session_start();
}
}//end controller class
?>

2.

Note that when you create a controller, you have to follow a few basic rules. The name of the class
is always capitalized, and it must match the name of the file. Therefore, you have the class Blog
in the blog.php file. Furthermore, you need a constructor of the same name inside your class. The
example above is PHP 4. If you were working in PHP 5, your constructor would look as follows:

12

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


<?php
class Blog extends Controller {
function __construct(){
parent::Controller();
session_start();
}
}//end controller class
?>

Notice that in both examples, youre initializing PHP Sessions with session_start(). Youll see why youre
using PHP Sessions as you continue working with the application. CodeIgniter comes with its own Sessions,
but those are cookie-based and therefore accessible to the client. They can be encrypted, of course, but this
fact doesnt mean that you should completely trust them. Later on, when you build the part of the application
that allows users to log in to the administrative panels, you want a more secure system of determining
successful login than a client-side cookie. PHP Sessions offers that, as the data are stored server-side.

3.

Once you have your constructor in place, all you have to do is add some functions. You will
need functions for every single destination in the controller. In this case, you will need a
destination for the home page, traditionally handled by an index() function.

Here are the basic functions that we want in our controller:


function index(){
//home page code here
}
function category(){
//category page code here
}
function post(){
//post detail page code here
}

Your index() function is very basic it just needs to display some navigation items and a certain
number of blog posts. This content isnt placed in the controller function, but is instead handled in a
view, which youll get to below. As you can see, we are using some models to call up data for the view to
display:
function index(){
$data[posts] = array(); //we will replace soon!
$data[cats] = array(); //we will replace soon!
$data[title] = Welcome;
$data[main] = public_home;
$this->load->vars($data);
$this->load->view(template);
}

Notice that you are saving information in a $data array (like the variables: title and main), and then
loading that array with $this->load->vars($data). All youre doing here is making the $data array
available to a view called Template.

13

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


The Template view (which will be saved in the /system/application/views folder as the template.php
file) is going to be a generic template that you can use throughout the administrative dashboard. The
template contains a hole in the center of it (a PHP doughnut, if you will) in which you can include
whatever other template you want. In this case, whatever value is saved in $data[main] will be used
to call up the template that fills that hole.
In the case of the first very simple index() function of the Blog controller, the public_home template
will contain the results of some data youre going to pull out of the database. For now, you want to keep
that data manual. Youll hook it up to your model later.

Creating the Template View


Before building that form, lets create the template.php file. This example uses one of the default
templates from Dreamweaver CS3 just for speed.
<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<html xmlns=http://www.w3.org/1999/xhtml>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8 />
<title><?php echo $title; ?></title>
<link href=<?php echo base_url();?>includes/css/main.css
rel=stylesheet type=text/css />
<script type=text/javascript>
//<![CDATA[
base_url = <?php echo base_url();?>;
//]]>
</script>
<!--[if IE 5]>
<style type=text/css>
/* place css box model fixes for IE 5* in this conditional comment */
.twoColFixLtHdr #sidebar1 { width: 230px; }
</style>
<![endif]--><!--[if IE]>
<style type=text/css>
/* place css fixes for all versions of IE in this conditional comment */
.twoColFixLtHdr #sidebar1 { padding-top: 30px; }
.twoColFixLtHdr #mainContent { zoom: 1; }
/* the above proprietary zoom property gives IE
the hasLayout it needs to avoid several bugs */
</style>
<![endif]--></head>
<body class=twoColFixLtHdr>
<div id=container>
<div id=header>
<h1><?php echo $title;?></h1>
<!-- end #header --></div>
<div id=sidebar1>

14

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


<?php $this->load->view(nav); ?>
<!-- end #sidebar1 --></div>
<div id=mainContent>
<?php $this->load->view($main);?>
<!-- end #mainContent --></div>
<!-- This clearing element should immediately follow the
#mainContent div in order to force the #container div
to contain all child floats --><br class=clearfloat />
<div id=footer>
<p>Copyright 2008 Your Company Inc | <?php echo anchor(blog/login, admin);?></p>
<!-- end #footer --></div>
<!-- end #container --></div>
</body>
</html>

Remember to save this file in the /system/application/views/ folder!


This template.php file is very simple, but you need to look at a few things before you go any further.
First, please notice that it refers to a CSS file that lives under an includes/ folder and various
subdirectories under that. CodeIgniter doesnt come with a designated storage place for all the images,
CSS files, JavaScript files, and other goodies that you need to build a web application. The best thing to
do with these assets is to create a folder off the root (at the same level as the system/ folder) and store
everything in there, out of the way.
All of the files you will need, by the way, are included in the zip file that you download with this Wrox
Blox. This zip file includes all the files referred to under the top-level includes/ folder.
The other thing you should notice is the sections marked $this->load->view(). They are reprinted in
the following example:
<div id=container>
<div id=header>
<h1><?php echo $title;?></h1>
<!-- end #header --></div>
<div id=sidebar1>
<?php $this->load->view(nav); ?>
<!-- end #sidebar1 --></div>
<div id=mainContent>
<?php $this->load->view($main);?>
<!-- end #mainContent --></div>

You can nest your views using the $this->load->view() command, as long as you feed it the name of
a view in your application. Sometimes you manually set the name of a view (like you did with nav), and
at other times, you can dynamically load a view with a PHP variable. Notice that youre doing just that
by feeding in the variable $main in the second instance.

15

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


Why $main? Wasnt the variable called $data[main] in the controller? Yes, but once $data is loaded
into the view, you access the values by using the keys of that array. This makes it pretty handy when
youre trying to remember what to access. It also makes it possible to pass all manner of data arrays into
a view without any trouble at all.
In this case, the $main stands for main content. You could use another semantically valid name, like
$content or $fill_in_the_donut_hole, but you get the idea. You now have a template you can use
for any non-logged-in view you may need.

Creating the Home Page View


So now you know that you need a home page view called public_home. Thats what the controller is going to
load. Specifically, you need to grab some data and then feed them to the view. For now, you have an empty
array for the posts and another empty array for the navigation. This is good enough for you to get started.
As soon as you have the views nailed down, you can go back and create your models. First, lets tackle
the side navigation. All you want is a link back to the home page and a link to each category. Heres
what the nav view would look like:
<?php echo anchor(blog/index,home);?><br/>
<h3>Categories</h3>
<?php
if (count($cats)){
foreach ($cats as $id => $name){
echo anchor(blog/category/$id,$name).<br/>;
}
}
?>

As you can see, all you need is for $data[cats] in your Blog controller to contain a simple array. The
keys of this array would be category IDs, and the values would be category names. Keep that in mind
while you work on the public_home template view.
The public_home view is very simple. Its basically expecting an array from the Blog controller. If it finds
one, it iterates over the array and prints out the title of the blog posting and the first 200 words.
<?php
if (count($posts)){
foreach ($posts as $key => $list){
echo <h2>.$list[title].</h2>\n;
echo auto_typography(word_limiter($list[body], 200));
echo anchor(blog/post/.$list[id],read more >>);
}
echo <br/><br/>;
}
?>

16

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


Notice the use of the auto_typography() and word_limiter() functions. These are both examples of
CodeIgniter helpers. To use them, you have to make sure that youve autoloaded them, or load the
helpers right before you do call them. To autoload, make the appropriate entries in the system/
application/config/autoload.php file. See the Other Files section above in this Wrox Blox as a
reference. Luckily, they have been autoloaded, so youre free to move on to your models.
Also notice that youre not displaying the full blog posts here on this view, but providing a link to
another page that shows details. More on this in a bit.
Models in CodeIgniter allow you to maintain a relationship with a data source. Most of the time, that
data source is a database table, but it could be a text file, cookie, session, or anything else for that matter.
At the moment, you need two basic models. The first allows you to talk to the categories table, and the
second allows you to talk to the posts table.
All models follow the same set of rules:

1.
2.
3.

They must have a name that doesnt conflict with a controller.


The name of the class is usually capitalized and matches the file name.
They live in the /system/application/models/ directory.

You should call the categories model MCats, and the posts model MPosts. Other developers have their
own naming conventions, preferring to use model_x or x_model for their model names, but the simple
Mx model is short and tells you right away that youre dealing with a model. As you work with this
application, youll be adding plenty of functions to each model, but for now, all you need is a few
functions to get you going.
In the MCats model, you need an easy way to pull out a simple array of categories so you can build a
navigation element on the public-facing web site. Before you build that, you need to create a model:
<?php
class MCats extends Model{
function MCats(){
parent::Model();
}
}//end class
?>

So far, so good, right? Just like with controllers, your model name must be identical to its filename, and
you have to instantiate the model as you would any other PHP class.
Before you do anything, remember to add your models to the autoload.php file (might as well add the
one for users, posts, and comments while youre at it!):
$autoload[model] = array(MCats,MPosts,MAdmins,MComments);

Now that theyre autoloaded, youre free to use functions from them without having to call them
beforehand.

17

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


Next, create a function called getTopCategories(). This function will retrieve all the top-level
categories from the categories table:
function getTopCategories(){
$this->db->where(parentid,0);
$Q = $this->db->get(categories);
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[$row[id]] = $row[name];
}
}
$Q->free_result();
return $data;
}

Now all you have to do is go back to our Blog controller and insert this function into the right space:
function index(){
$data[posts] = array();
$data[cats] = $this->MCats->getTopCategories();
$data[title] = Welcome;
$data[main] = public_home;
$this->load->vars($data);
$this->load->view(template);
}

Next, you need a simple function that will retrieve a certain number of posts for the home page. You
dont want to hardcode the number of posts in the model function, so youll pass in a limit. Heres what
the model function would look like:
<?php
class MPosts extends Model{
function MPosts(){
parent::Model();
}
function getLivePosts($limit){
$data = array();
$this->db->limit($limit);
$this->db->where(status, published);
$this->db->order_by(pubdate,desc);
$Q = $this->db->get(posts);
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
}
?>

18

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


Notice that were using the passed-in $limit variable to limit how many records we retrieve. Were
further limiting ourselves to just published posts (using the where() function) and ordering the result
set by pubdate descending. Now were free to go back and add this function into the Blog controller,
stipulating that we want 10 posts:
function index(){
$data[posts] = $this->MPosts->getLivePosts(10);
$data[cats] = $this->MCats->getTopCategories();
$data[title] = Welcome;
$data[main] = public_home;
$this->load->vars($data);
$this->load->view(template);
}

Creating the Category View


You now need a similar approach to a category page. In other words, if a visitor clicks a category in the
side navigation (like news or rants), they should end up on a destination page that shows them all
the posts assigned to that category.
In your Blog controller, youd have a category() function:
function category($id){
$data[category] = $this->MCats->getCategory($id);
$data[posts] = $this->MPosts->getAllPostsByCategory($id);
$data[cats] = $this->MCats->getTopCategories();
$data[title] = $data[category][name];
$data[main] = public_home;
$this->load->vars($data);
$this->load->view(template);
}

Its very similar to the index() function. It assumes that were going to pass in some kind of category ID
(which we will refer to as simply $id in this context). It then uses that $id to fetch the category via a
getCategory() function, and all posts assigned to a category via a getAllPostsByCategory() function.
First, lets build the getCategory() function in the MCats model:
function getCategory($id){
$data = array();
$this->db->where(id,$id);
$this->db->limit(1);
$Q = $this->db->get(categories);
if ($Q->num_rows() > 0){
$data = $Q->row_array();
}
$Q->free_result();
return $data;
}

This function is very simple. It retrieves one record from the categories table that matches the ID you
pass in, returning an array.

19

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


Heres the getAllPostsByCategory() function of the MPosts model:
function getAllPostsByCategory($catid){
$data = array();
$this->db->where(category_id,$catid);
$this->db->where(status, published);
$Q = $this->db->get(posts);
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result();
return $data;
}

You pass in a $catid and use it to filter which posts you return, making sure that you also only grab
those posts with a status of published. Make sure that you return an array, because in the end, youre
passing all of this information to the public_home view, which youve already used for your home page.

Creating the Blog Details View


At some point, you need to show an individual blog posting (and any comments that have been made
about that posting). In the controller, a function called post() has been set aside. Lets revisit that now:
function post($id){
$data[post] = $this->MPosts->getPost($id);
$data[comments] = $this->MComments->getComments($id);
$data[cats] = $this->MCats->getTopCategories();
$data[title] = $data[post][title];
$data[main] = public_post;
$this->load->vars($data);
$this->load->view(template);
}

Youre passing in an $id variable that will map to the post ID. Youll use that here in much the same way
you used the category ID when you viewed posts by category. It looks like you need to add one more
function to the MPosts model [getPost()] and create a model called MComments.
Lets add the getPost() function to the MPosts model first:
function getPost($id){
$data = array();
$this->db->where(id,$id);
$this->db->limit(1);
$Q = $this->db->get(posts);
if ($Q->num_rows() > 0){
$data = $Q->row_array();
}
$Q->free_result();
return $data;
}

20

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


No surprises here. You pass in an $id and use that to grab one record from the posts table, then return
that record as an array.
On to building the MComments model. You need a getComments() function that will retrieve all the
comments related to a certain post. Youll also need an addComment() function, which youll be adding
below. Lets build that all out now:
<?php
class MComments extends Model{
function MComments(){
parent::Model();
}
function getComments($postid){
$data = array();
$this->db->where(post_id,$postid);
$Q = $this->db->get(comments);
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
function addComment(){
$now = date(Y-m-d H:i:s);
$data = array(
name => $this->input->post(name),
email => $this->input->post(email),
body => strip_tags(substr$this->input->post(body),0,255)),
post_id => $this->input->post(post_id),
pubdate => $now
);
$this->db->insert(comments, $data);
}
}
?>

Now that you have the models under control, you should create a simple view called public_post. This
view will consist of the blog posting and any comments that are associated with it, followed by a simple
form that will allow users to post their own comments.
<?php
echo auto_typography($post[body]);
?>
<h3>Comments</h3>
<?php
if (count($comments)){

21

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


foreach ($comments as $key => $list){
echo <b>Comment by .$list[name].:</b><br/>\n;
echo auto_typography($list[body]);
}
echo <br/>;
}
?>
<p><b>Add your own comment:</b></p>
<?php
echo form_open(blog/addcomment);
echo form_label(your name,name) .<br/>;
$data = array(name=>name,id=>name,size=>25);
echo form_input($data) .</p>;
echo form_label(your email,email) .<br/>;
$data = array(name=>email,id=>email,size=>25);
echo form_input($data) .</p>;
echo form_label(your comment,comment) .<br/>;
$data = array(name=>body,id=>comment,rows=>5, cols=>30);
echo form_textarea($data) .</p>;
echo form_hidden(post_id,$post[id]);
echo form_submit(submit,add comment);
echo form_close();
?>

Whenever you get the chance, you should let CodeIgniter help you as much as possible (as youre doing
in this Wrox Blox). Youre using auto_typography() to help lay out the content for the posting and
comments. Youre also using helpers like form_open(), form_label(), form_input(),
form_hidden(), and form_submit() to help you build a very fast and simple comment form.
Notice the form_open() function points to blog/addcomment. This means that you need a new function
in your Blog controller, one called addcomment(). This function has a very simple job: insert the comment
from the form into the database and then redirect the user back to the blog posting they were on.
The way to do this is very simple: call the model function you want to do the job. In this case, you want
the addComment() function of the MComments model.
function addcomment(){
if ($this->input->post(body)){
$this->MComments->addComment();
}
redirect(blog/post/.$this->input->post(post_id), refresh);
}

Creating the Login Form


We now need to discuss a Login form so that blog administrators can get into the dashboard. In the Blog
controller, you need to add a login() function:

22

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


function login(){
$data[cats] = $this->MCats->getTopCategories();
$data[title] = Login to the Dashboard;
$data[main] = public_login;
$this->load->vars($data);
$this->load->view(template);
}

This is simple enough, and the public_login view is even simpler:


<?php
$udata = array(name=>username,id=>u,size=>15);
$pdata = array(name=>password,id=>p,size=>15);
echo
echo
echo
echo
echo
echo
echo
?>

form_open(blog/verify);
form_label(username,u) .<br/>;
form_input($udata) . </p>;
form_label(password,p) .<br/>;
form_password($pdata) . </p>;
form_submit(submit,login);
form_close();

To open a form, use form_open() and pass in the URI to which the form posts. This is equivalent to the
action attribute of a form. In your case, you want this simple form to post to blog/verify, which means
you will need to add a new function.
Notice that you then use form_input() and form_password() to create a text field followed by a
password field. Also notice that each of these has a short array containing necessary values (like the field
name, DOM ID, and size) that gets passed to that field. Also notice the use of form_label(), a handy
shortcut for your labels (which are a good accessibility thing to have on your forms).
Finally, you create a submit button with form_submit() and close the form with form_close().
Although you may now be wondering why you would go to all this trouble, after only a short while,
youll wonder how you got along without this helper.

Verifying Logins
At this point, you have a Login form that posts back to blog/verify, which means that you need to add a
verify() function. If there are POST data, the function needs to take the values from the form, encrypt
the password using some simple method, and then check to see whether there are any users in the
database that match the values from the form. The encrypting and checking can be done inside
the model to keep things simple.
Heres a complete version of the verify() function:
function verify(){
$this->load->library(encrypt);
if ($this->input->post(username)){
$u = $this->input->post(username);
$pw = $this->input->post(password);
$row = $this->MAdmins->verifyUser($u,$pw);

23

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


if (count($row)){
$_SESSION[userid] = $row[id];
redirect(admin/dashboard,refresh);
}else{
redirect(blog/login,refresh);
}
}else{
redirect(blog/login,refresh);
}
}

The first thing you do now is load the encrypt library. This library is only used during login, so there is
no need to autoload it. Once loaded, it will be used by the model youre going to create to communicate
with the database table that will store administrative users.
The second thing you do is use $this->input->post() to check to see whether there is a value in a
field called username. If there is a value, then you grab the username and password values and hand this
information off to the MAdmins model (which you havent built yet) and specifically, the verifyUser()
function of that model.
What you need to receive is an array of data. If you do get back an array, you can populate a PHP session
variable called userid and then redirect the user to the admin/dashboard controller (youll be building
that shortly, as well). If you dont get back a data array, you simply redirect the user to the Login form so
they can try to log in again.
So heres what you need to do before youre done with the login area:

1.
2.

Create the MAdmins model.


Create the verifyUser() function inside that model.

Creating the MAdmins Model


Here is a basic, bare-bones model for MAdmins, stored in madmins.php:
<?php
class MAdmins extends Model{
function MAdmins(){
parent::Model();
}
}//end class
?>

Creating the verifyUser() Function


Now that you have the basic MAdmins model in place, you need to create the verifyUser() function.
This function will receive two arguments, a username and a password. It needs to encrypt the password
before running the query (as youre only going to save encrypted passwords in the system). It then
returns an array of data (whether empty or not) to the calling controller:

24

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


function verifyUser($u,$pw){
$this->db->select(id);
$this->db->where(username,$u);
$this->db->where(password, md5($pw));
$this->db->where(status, active);
$this->db->limit(1);
$Q = $this->db->get(ms_admins);
if ($Q->num_rows() > 0){
$row = $Q->row_array();
return $row;
}else{
return array();
}
}

If you recall, the controller verify() function that is calling verifyUser() is expecting a row
containing an ID, so that it can set a PHP Session value. It will accept an empty array, but that causes
the controller to redirect back to the login page.

A Small Note about Creating Your First User


Youll notice that youre only storing encrypted passwords in the database table. Later, youll be asked to
log in before you can see the admin dashboard, which you wont be able to do because there is no user in
the system!
To get around that little problem, generate your first user by hand, using phpMyAdmin or some other
database admin tool. To generate a proper password, use PHP to echo a string wrapped with md5(),
then store that string in your database.
For example, <?php echo md5 (password);?>. This should generate an md5 hash of the string
password, which, once stored in the database, will allow you to log in with that password.

Creating the Admin Dashboard


Now that the login area is fully created, you have been introduced to Controllers, Models, and Views
and can easily create the rest of the application. The rest of the application will involve building out the
administrative dashboard, with separate controllers for categories, pages, files, and users (remember,
you need to manage those as well!).
To keep things organized, youre going to create a folder called admin/ inside the /system/application/
controllers/ folder, and youll store all your controllers in there. You will need to build the following
controllers:

Dashboard This is the home area for your administrative area, and includes all publication
functions.

Posts To manage posts.

Categories To manage folders or categories in the site.

Admins To manage admin users.

25

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


Along the way, youll create models (and in one case, youll expand what youve done with the
MAdmins model) and views to support what you need. Because of time and space constraints, this Wrox
Blox doesnt go into great detail on each part of the application, but you will have enough information
that you can easily duplicate the finished application. Youll also have access to all the code in order to
create your own microsite manager.
Rest assured that once youve built one set of Models, Views, and Controllers in an administrative
dashboard, its very easy to repeat the process whenever you need more screens.

Creating the Dashboard Controller


The Dashboard controller needs two very simple functions:
index() This contains all the code you need to display the home page of the admin

dashboard.
logout() Allows users to log out.

Heres what the top of our Dashboard controller looks like (remember, it is stored in the /system/
application/controllers/admin folder):
<?php
class Dashboard extends Controller {
function Dashboard(){
parent::Controller();
session_start();
if ($_SESSION[userid] < 1){
redirect(blog/login,refresh);
}
}
}//end class

The controller starts typically enough, with the right naming conventions, and includes a very short
check to make sure that the Session variable called userid has been set. If it has a value less than 1, then
the user is redirected to the Welcome controller, and specifically to the Login form. Youre going to add
this little bit of code to every single controller in the admin/ folder to keep out any unauthorized users.
Once that little bit of business is done, you can build the index() function:
function index(){
$data[title] = Dashboard Home;
$data[main] = admin_home;
$this->load->vars($data);
$this->load->view(dashboard);
}

Youre doing essentially the same thing you did before, on the Login screen, except youre loading a
Dashboard view instead of the Template view.

26

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


The Dashboard view is very simple, and looks like this:
<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>
<html xmlns=http://www.w3.org/1999/xhtml xml:lang=en lang=en>
<head>
<meta http-equiv=content-type content=text/html; charset=utf-8 />
<title><?php echo $title; ?></title>
<link href=<?= base_url();?>includes/css/admin.css
rel=stylesheet type=text/css />
<script type=text/javascript>
//<![CDATA[
base_url = <?= base_url();?>;
//]]>
</script>
<?php echo $tinymce;?>
</head>
<body>
<div id=wrapper>
<div id=header>
<?php $this->load->view(admin_header);?>
</div>
<div id=main>
<?php $this->load->view($main);?>
</div>
<div id=footer>
<?php $this->load->view(admin_footer);?>
</div>
</div>
</body>
</html>

This Dashboard template, in turn, loads an admin_header, an admin_footer, and whatever value has
been loaded into $data[main] from the controller (in this case, admin_home).
Here is the admin_header view:
<div id=globalnav>
<ul>
<li><?php echo anchor(admin/dashboard/index,home);?></li>
<li><?php echo anchor(admin/categories/,categories);?></li>
<li><?php echo anchor(admin/posts/, posts);?></li>
<li><?php echo anchor(admin/admins/, users);?></li>
<li><?php echo anchor(admin/dashboard/logout/, logout);?></li>
</ul>
</div>

Essentially, this is the main navigation tool that goes across the top of the admin dashboard. Once youve
built all the necessary controllers and views, all of this will start working like a charm. For now, take a
look at the use of the anchor() shortcut function. This function is part of the URL helper. It builds links
for you, and accepts two arguments, the link destination and the link text.

27

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


Whats so great about the anchor() function? It automatically adds the base URL to any internal links
so you dont have to keep track of it. This one little benefit will keep you coming back to the anchor()
tag over and over again.
Heres the admin_footer view:
Copyright &#169; <?php echo date(Y); ?> Your Company Name

This one line of HTML and PHP will put a copyright notice on the bottom of each page.
Finally, heres the admin_home view:
<ul>
<li><b><?php
.</b></li>
<li><b><?php
<li><b><?php
<li><b><?php
</ul>

echo anchor(admin/categories/,Manage Categories);?>


echo anchor(admin/posts/,Manage Posts);?>.</b></li>
echo anchor(admin/admins/,Manage Users);?>.</b></li>
echo anchor(admin/dashboard/logout/,Logout);?>.</b></li>

It is basically the same list of links seen in the main navigation. You could, if you wanted, add more
information in there, like a listing of the last five postings made on the blog.
Before you move on to the other controllers, finish the Dashboard controller. You still need the logout()
and build_site() functions. Heres the logout() function, which basically unsets the PHP Session
variable userID and redirects the user to the login screen:
function logout(){
unset($_SESSION[userid]);
redirect(welcome/index,refresh);
}

Now that youve got the Dashboard figured out, create the other controllers you need, starting with the
Admin area first.

Building the Admin Area


The admin area already has a model (MAdmins), so all you have to do is create a controller that will
refer to it, add any other functions you may need, and then build your views.

Creating the Admins Controller


Generally speaking, you need just three or four main functions within any given admin-type controller
to make things work smoothly:

An index() function allows users to see data within the database table at a glance.

A create() function allows users to create new data in the table.

An edit() function allows users to edit existing data in a table.

A delete() function allows users to remove (or deactivate) data in a table.

28

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


All of our administrative controllers will follow this basic pattern. The following code is the Admins
controller, with each section above inserted into the code. The first part is the header, which should look
extremely familiar to you by now:
<?php
class Admins extends Controller {
function Admins(){
parent::Controller();
session_start();
if ($_SESSION[userid] < 1){
redirect(welcome/index,refresh);
}
}

The index() function loads the admin_admins_home view and requires the creation of a model
function called getAllUsers(). As you can guess, this function retrieves all users from the database:
function index(){
$data[title] = Manage Users;
$data[main] = admin_admins_home;
$data[admins] = $this->MAdmins->getAllUsers();
$data[tinymce] = ;
$this->load->vars($data);
$this->load->view(dashboard);
}

The create() function is very simple. You want to create a dual-purpose function here, similar to your
login screen. If there are POST data, run a function called addUser() and redirect the user to the
index() function. If not, show the admin_admins_create view:
function create(){
$this->load->library(encrypt);
if ($this->input->post(username)){
$this->MAdmins->addUser();
redirect(admin/admins/index,refresh);
}else{
$data[title] = Create User;
$data[main] = admin_admins_create;
$data[tinymce] = ;
$this->load->vars($data);
$this->load->view(dashboard);
}
}

Similarly, the edit() function also looks for POST data. If it finds any, it runs the updateUser()
function and redirects the user to the index() function. If it doesnt, it loads the admin_admins_edit
view. Notice that it also runs the getUser() model function, which youll use to populate the form
fields.

29

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


function edit($id=0){
$this->load->library(encrypt);
if ($this->input->post(username)){
$this->MAdmins->updateUser();
redirect(admin/admins/index,refresh);
}else{
$data[title] = Edit User;
$data[main] = admin_admins_edit;
$data[admin] = $this->MAdmins->getUser($id);
$data[tinymce] = ;
$this->load->vars($data);
$this->load->view(dashboard);
}
}

Finally, theres the delete() function, which will pass in a user ID via a link and run the deleteUser()
model function:
function delete($id){
$this->MAdmins->deleteUser($id);
redirect(admin/admins/index,refresh);
}
}
?>

Expanding the MAdmins Model


You now have to add several functions to the MAdmins model: getAllUsers(), getUser(),
addUser(), updateUser(), and deleteUser(). Its probably a good idea to work on them now before
you start doing anything with the views, which will be simple enough.
The easiest function to understand is getUser(). All you have to do is feed the function an ID and it
will return all the data associated with the record:
function getUser($id){
$data = array();
$this->db->where(id,$id);
$this->db->limit(1);
$Q = $this->db->get(users);
if ($Q->num_rows() > 0){
$data = $Q->row_array();
}
$Q->free_result();
return $data;
}

The getAllUsers() function is similarly easy to understand. It returns all rows in the designated table
(in this case, ms_admins):
function getAllUsers(){
$data = array();
$Q = $this->db->get(users);

30

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result();
return $data;
}

The addUser() function accepts an incoming array of POST data and then uses $this->db->insert()
to place those data in the right table:
function addUser(){
$data = array(username => $this->input->post(username),
email => $this->input->post(email),
status => $this->input->post(status),
password => md5($this->input->post(password))
);
$this->db->insert(users,$data);
}

The updateUser() function also accepts an incoming array of POST data and then updates the table
using $this->db->update(). Notice that tucked away inside the POST data is some kind of ID field.
You should make sure to put that inside the view to keep things working correctly.
function updateUser(){
$data = array(username => $this->input->post(username),
email => $ this->input->post(email),
status => $ this->input->post(status),
password => md5($this->input->post(password))
);
$this->db->where(id,$ this->input->post(id));
$this->db->update(users,$data);
}

The deleteUser() function accepts an ID and then sets the status of that record to inactive. Im not a
big believer in actually deleting items from the database, so thats why Ive opted for a deactivation instead
of deletion. Because of that, youre using $this->db->update() instead of $this->db->delete():
function deleteUser($id){
$data = array(status => inactive);
$this->db->where(id, $id);
$this->db->update(users, $data);
}

Creating the Views


Now that the Controller and Model functions are in place, all you need to build are the views. You need
three views: a main index view, a Create form, and an Edit form. Once you have all three in place, you
can tie it all together with the rest of the application to make things work correctly.

31

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


The admin_admins_home view is just a simple table that displays all the available records from the
database table. Remember that the controller calls the model function getAllUsers(), and that function
returns an array and saves it in $data[admins]. Therefore, you will need to loop through $admins in
the view:
<h1><?php echo $title;?></h1>
<p><?php echo anchor(admin/admins/create, Create new user);?>
if (count($admins)){
echo <table border=1 cellspacing=0 cellpadding=3 width=400>\n;
echo <tr valign=top>\n;
echo <th>ID</th>\n<th>Username</th><th>Status</th><th>Actions</th>\n;
echo </tr>\n;
foreach ($admins as $key => $list){
echo <tr valign=top>\n;
echo <td>.$list[id].</td>\n;
echo <td>.$list[username].</td>\n;
echo <td align=center>.$list[status].</td>\n;
echo <td align=center>;
echo anchor(admin/admins/edit/.$list[id],edit);
echo | ;
echo anchor(admin/admins/delete/.$list[id],delete);
echo </td>\n;
echo </tr>\n;
}
echo </table>;
}
?>

Notice that you can easily create a new user with the link along the top, and edit or delete any existing
record once it loads up in the table. When youre done, your user area will look a little like the illustration in Figure 4.

Figure 4: User home page.


The admin_admins_create view is just a simple form. It should allow the user to enter a username, password, and other information:
<h1><?php echo $title;?></h1>
<?php
echo form_open(admin/admins/create);
echo form_label(username,u);

32

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


$data = array(name=>username,id=>uname,size=>25);
echo form_input($data) .</p>;
echo form_label(email,email);
$data = array(name=>email,id=>email,size=>50);
echo form_input($data) .</p>;
echo form_label(password,pw);
$data = array(name=>password,id=>pw,size=>25);
echo form_password($data) .</p>;
echo form_label(status,status);
$options = array(active => active, inactive => inactive);
echo form_dropdown(status,$options) .</p>;
echo form_submit(submit,create admin);
echo form_close();
?>

Notice that youve introduced another element here called form_dropdown(), a handy shortcut that
allows the easy creation of dropdowns. All you have to do is create an array of options and then pass it
in to form_dropdown() to create your values. This array can be set manually, or it can be generated
from a query.
For all intents and purposes, the admin_admins_edit view contains the same exact form, except youre
loading values into each field. Remember that the controller function edit() has run the getUser()
model function to pull in the corresponding record for a given user ID. Those data were stored in
$data[admin], so you can access them via $admin.
<h1><?php echo $title;?></h1>
<?php
echo form_open(admin/admins/create);
echo form_label(username,u);
$data = array(name=>username,id=>uname,size=>25,
value=>$admin[username]);
echo form_input($data) .</p>;
echo form_label(email,email);
$data = array(name=>email,id=>email,size=>50,
value=>$admin[email]);
echo form_input($data) .</p>;
echo form_label(password,pw);
$data = array(name=>password,id=>pw,size=>25,
value=>);
echo form_password($data) .</p>;
echo form_label(status,status);
$options = array(active => active, inactive => inactive);
echo form_dropdown(status,$options,$admin[status]) .</p>;
echo form_submit(submit,update admin);
echo form_close();
?>

33

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter

Creating the Rest of the Admin Functions


Now that the Admins controller is in place, its time to create Models, Views, and Controllers for categories,
pages, and uploads. Each of these controllers follows the exact same pattern youve seen with the Admins
area, so I wont spend a lot of time on each section. I especially wont spend a lot of time on the views, as
you can inspect them easily enough when you look at the companion code for this Wrox Blox.

Categories
First, lets talk about categories. Categories, for the purposes of this application, are defined as generic
containers (like folders) that can hold pages. When you create the site building function for the
Dashboard controller, youll organize all the output into their proper categories, using the category
names as folder names.
The categories area has a very simple controller. Looking at it, you will notice that almost the same thing
is going on in this controller as went on in the Admins controller. The only difference is, youre calling
different views.
Heres the Categories controller:
<?php
class Categories extends Controller {
function Categories(){
parent::Controller();
session_start();
if ($_SESSION[userid] < 1){
redirect(welcome/index,refresh);
}
}
function index(){
$data[title] = Manage Categories;
$data[main] = admin_cat_home;
$data[categories] = $this->MCats->getAllCategories();
$this->load->vars($data);
$this->load->view(dashboard);
}
function create(){
if ($this->input->post(name)){
$this->MCats->addCategory();
redirect(admin/categories/index,refresh);
}else{
$data[title] = Create Category;
$data[main] = admin_cat_create;
$data[categories] = $this->MCats->getTopCategories();
$this->load->vars($data);
$this->load->view(dashboard);
}
}
function edit($id=0){

34

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


if ($this->input->post(name)){
$this->MCats->updateCategory();
redirect(admin/categories/index,refresh);
}else{
$data[title] = Edit Category;
$data[main] = admin_cat_edit;
$data[category] = $this->MCats->getCategory($id);
$data[categories] = $this->MCats->getTopCategories();
$this->load->vars($data);
$this->load->view(dashboard);
}
}
function delete($id){
$this->MCats->deleteCategory($id);
redirect(admin/categories/index,refresh);
}
}//end class
?>

As you can see, the same patterns emerge. The controller calls model functions, sets variables, and loads
those variables into a particular view. In your case, youre building administrative panels, so the view
wont vary much. Theyll either be a listing of available records or a form that allows you to create new
records or edit existing records.
Youve already created a few functions in the MCats model as you worked on the public side of the site;
now its time to add a few more, so you can continue working on the admin side:
<?php
class MCats extends Model{
function MCats(){
parent::Model();
}
function getCategory($id){
$data = array();
$options = array(id => $id);
$Q = $this->db->getwhere(categories,$options,1);
if ($Q->num_rows() > 0){
$data = $Q->row_array();
}
$Q->free_result();
return $data;
}
function getAllCategories(){
$data = array();
$Q = $this->db->get(categories);
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){

35

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


$data[] = $row;
}
}
$Q->free_result();
return $data;
}
function addCategory(){
$data = array(
name => str_replace( , _,$this->input->post(name)),
shortdesc => $this->input->post(shortdesc),
longdesc => $this->input->post(longdesc),
status => $this->input->post(status),
sortorder => $this->input->post(sortorder),
parentid => $this->input->post(parentid)
);
$this->db->insert(categories, $data);
}
function updateCategory(){
$data = array(
name => str_replace( , _,$this->input->post(name)),
shortdesc => $this->input->post(shortdesc),
longdesc => $this->input->post(longdesc),
status => $this->input->post(status),
sortorder => $this->input->post(sortorder),
parentid => $this->input->post(parentid)
);
$this->db->where(id, $this->input->post(id));
$this->db->update(categories, $data);
}
function deleteCategory($id){
$data = array(status => inactive);
$this->db->where(id, $id);
$this->db->update(categories, $data);
}
}
function getTopCategories(){
$data[0] = root;
$this->db->where(parentid,0);
$Q = $this->db->get(categories);
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[$row[id]] = $row[name];
}
}
$Q->free_result();
return $data;
}
?>

36

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


Posts
The Posts controller and model (MPosts) are essentially identical to Categories, except that the schemata
related to pages has a few more fields. I wont go into all the detail of the Controller and Model (as you
can investigate yourself using the code).
Here are the primary functions of the Posts controller:
<?php
class Posts extends Controller {
function Posts(){
parent::Controller();
session_start();
if ($_SESSION[userid] < 1){
redirect(blog/login,refresh);
}
}
function index(){
$data[title] = Manage Posts;
$data[main] = admin_posts_home;
$data[posts] = $this->MPosts->getAllPosts();
$data[cats] = $this->MCats->getTopCategories();
$this->load->vars($data);
$this->load->view(dashboard);
}

function create(){
if ($this->input->post(title)){
$this->MPosts->addPost();
redirect(admin/posts/index,refresh);
}else{
$data[title] = Create Post;
$data[main] = admin_posts_create;
$data[cats] = $this->MCats->getCategoriesDropDown();
$this->load->vars($data);
$this->load->view(dashboard);
}
}
function edit($id=0){
if ($this->input->post(title)){
$this->MPosts->updatePost();
$this->session->set_flashdata(message,Post updated);
redirect(admin/posts/index,refresh);
}else{
//$id = $this->uri->segment(4);
$data[title] = Edit Post;
$data[main] = admin_posts_edit;

37

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


$data[post] = $this->MPosts->getPost($id);
$data[cats] = $this->MCats->getCategoriesDropDown();
$this->load->vars($data);
$this->load->view(dashboard);
}
}
function delete($id){
$this->MPosts->deletePost($id);
$this->session->set_flashdata(message,Post deleted);
redirect(admin/posts/index,refresh);
}

}//end class
?>

Summar y
Now that you have an administrative area up and running, create a few categories and start publishing
posts. What youll see is a growing list of categories in your navigation and a growing list of Blog posts,
as illustrated in Figure 5. It isnt the prettiest thing in the world, but youve met your end of the deal: a
working blog application prototype in a matter of hours!

Figure 5: Your Blog home Page.


By now, what you have is a compact, portable blogging application written in CodeIgniter that you can
use as a stand-alone publishing tool or integrated blog controller in another CodeIgniter application.
It can even be installed in its own subfolder of a non-CodeIgniter site very easily.

38

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter

About Thomas Myer


Thomas Myer is a technical book author, consultant, and web developer. In 2001, he founded Triple Dog
Dare Media in Austin, Texas. Triple Dog Dare Media focuses its attention on helping companies create
CodeIgniter-based applications like content management, portals, and eCommerce systems.
Thomas Myer is the author of No Nonsense XML Web Development with PHP (Sitepoint, 2004) and Lead
Generation on the Web (OReilly, 2007). His new book, Professional CodeIgniter from WROX, hit the
bookstores in July 2008. He has also authored dozens of technical and business articles for IBM
DeveloperWorks, Amazon Web Services, AOL, Darwin Magazine, and others.

39

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Creating a Blogging Tool with Codeigniter


Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256

www.wiley.com
Copyright 2008 by Wiley Publishing, Inc., Indianapolis, Indiana
ISBN: 978-0-470-41338-8
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of
the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA
01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal
Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or
online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including
without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or
promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is
sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional
services. If professional assistance is required, the services of a competent professional person should be sought. Neither
the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Website is
referred to in this work as a citation and/or a potential source of further information does not mean that the author or the
publisher endorses the information the organization or Website may provide or recommendations it may make. Further,
readers should be aware that Internet Websites listed in this work may have changed or disappeared between when this
work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the
United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are
trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other
countries, and may not be used without written permission. CodeIgniter is a registered trademark of EllisLab, Inc. All
other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or
vendor mentioned in this Wrox Blox.
This PDF should be viewed with Acrobat Reader 6.0 and later, Acrobat Professional 6.0 and later, or Adobe Digital Editions.
Usage Rights for Wiley Wrox Blox. Any Wiley Wrox Blox you purchase from this site will come with certain restrictions
that allow Wiley to protect the copyrights of its products. After you purchase and download this title, you:





Are entitled to three downloads


Are entitled to make a backup copy of the file for your own use
Are entitled to print the Wrox Blox for your own use
Are entitled to make annotations and comments in the Wrox Blox file for your own use
May not lend, sell or give the Wrox Blox to another user
May not place the Wrox Blox file on a network or any file sharing service for use by anyone other than yourself or
allow anyone other than yourself to access it
May not copy the Wrox Blox file other than as allowed above
May not copy, redistribute, or modify any portion of the Wrox Blox contents in any way without prior permission
from Wiley
If you have any questions about these restrictions, you may contact Customer Care at (877) 762-2974 (8 a.m. - 5 p.m. EST,
Monday Friday). If you have any issues related to Technical Support, please contact us at 800-762-2974 (United States
only) or 317-572-3994 (International) 8 a.m. 8 p.m. EST, Monday - Friday).
Acquisitions Editor Director
Jenny Watson
Development Editor
Maureen Spears
Technical Editor
Ed Finkler
Production Editor
Daniel Scribner

Copy Editor
Cate Caffrey
Editorial Manager
Mary Beth Wakefield
Production Manager
Tim Tate

Vice President and Executive Group Publisher


Richard Swadley
Vice President and Executive Publisher
Joseph B. Wikert
Proofreader
Nancy Carrasco

Wrox Blox0 Creating a Blogging Tool with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

Ready for more?


Build onto the knowledge that you just gained from this Wrox Blox.
Professional CodeIgniter is available now!

odeIgniter is lighting up the PHP development


space, and this book shows programmers how to
join the action
CodeIgniter is an MVC (model-view-controller)
framework for PHP that is generating a lot of buzz,
because it allows developers to save time by reusing
existing code instead of writing it from scratch; although
similar to Ruby on Rails, CodeIgniter is popular as a way
to build Rails-like code without learning a new
programming language
Walks readers through the steps of building several
types of applications with CodeIgniter, including blogs,
forums, and content management; also provides
problem-solving techniques and tips on everyday issues
not typically covered in reference manuals for
programmers
Covers a range of topics helpful to developers of all
stripes, from novice programmers to code gurus; topics
include an overview of agile methodologies and
approaches, the MVC approach, helpers and libraries,
model and schema for products, and Ajax and
Scriptaculous

Professional CodeIgniter
By THOMAS MYER
978-0-470-28245-8 Paper 304 pages
Wrox Blox0 Creating
a Blogging
with CodeIgniter By Myer - ISBN0 97804704133881 Prepared for CHRISTOPHER RINGWALD/ email0
Visit
us at Tool
www.wrox.com
callananclare@aol.com Order number0 40397143 Copyright 2009/ Wiley Publishing Inc. This PDF is exclusively for your use in accordance
with the WroxBlox Terms of Service. No part of it may be reproduced or transmitted in any form by any means without prior written
permission from the publisher. Redistribution or other use that violates the Wrox Blox Terms of Service or otherwise violates the U.S.
copyright laws is strictly prohibited.

You might also like