
CodeIgniter is a framework build by EllisLab the creators of Expression Engine. In this tutorial i will cover the basics of CodeIgniter and to do that we will be building a simple guestbook. First of all you'll be needing the latest version of CodeIgniter so grab the latest release from http://codeigniter.com/downloads/ and then move the files to your localhost or web server.
CodeIgniter uses the Model View Controller architectural pattern which gives you great flexibility when it comes to reusing, altering and upgrading code. If you navigate through the CodeIgniter files to the application folder (System -> Application) then you will see 3 sub folders for models, controllers and views.
The controllers will control what the users see on the screen and it will use the model to run various functions. The view is simply a template. The controller which will be used by default is called "welcome.php", to change the default controller we simple need to goto the config folder and open routes.php, right down at the bottom of the file you will see:
$route['default_controller'] = "welcome";
Change "welcome" to "guestbook" because we will make a controller called "guestbook.php" soon but first open up the database.php config file (System -> Application -> Config -> database.php) and simply update the setting to match your database.
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "guestbook";
$db['default']['dbdriver'] = "mysql";
Now create a blank document and save it in the controllers folder and name it "guestbook.php". In our blank document we're to create a class called "Guestbook" which extends "Controller"
<?php
class Guestbook extends Controller {
}
In our construct function we need to tell it that it's parent is controller and then the default function that CodeIgniter will look for is "index"
class Guestbook extends Controller {
function __construct() {
parent::Controller();
}
function index() {
echo "Hello World";
}
}
If you launch your site you should see "Hello World". So now we need to build the structure for our class, In our controller we only need 1 function called index. CodeIgniter will look for a function called index if no function is specified via the URL.
class Guestbook extends Controller {
function __construct() {
parent::Controller();
}
function index() {
}
}
Next we're going to create our database and model. The database need just one table with just 4 fields comment_id (int 11), name (varchar 255), url (varchar 255) and comment (text). Import this SQL statement via phpMyAdmin or any other MySQL tool.
CREATE TABLE guestbook.comments (
comment_id INT( 11 ) NULL AUTO_INCREMENT ,
name VARCHAR( 255 ) NOT NULL ,
url VARCHAR( 255 ) NOT NULL ,
comment TEXT NOT NULL ,
PRIMARY KEY ( comment_id )
) ENGINE = MYISAM
Now for the model, Just like the controller create a blank document in the models folder (System -> Application -> Models) and name it "guestbook_model.php" now we need to create our Guestbook_model class and extend the parent model class, Just like the controller we made earlyer.
class Guestbook_model extends Model {
function __construct() {
parent::Model();
}
}
Now to structure our model. We only need two functions, one to post entries and one to get them from the database. To use the various libraries available with CodeIgniter we first need to load them, A good place to do this is in our construct function.
class Guestbook_model extends Model {
function __construct() {
parent::Model();
$this->load->database();
}
}
Alternatively instead of loading the library in each individual model we can open autoload.php (System -> Application -> Config -> autoload.php) the first array we come across is the one which we want.
$autoload['libraries'] = array();
You need to put the names of each of the libraries you want in the array as single entites.
$autoload['libraries'] = array('database');
Now back to our model we're going to build our view function first.
function view() {
$sql = "SELECT * FROM ". $this->table ." ORDER BY comment_id DESC";
}
To start with we are going to define a variable "table" encase at a later stage we need to change the table name aswell as that we need to query our database for the guestbook entries and then return our data.
function view() {
$sql = "SELECT * FROM ". $this->table ." ORDER BY comment_id DESC";
$query = $this->db->query( $sql );
return $query->result_array();
}
Now we need to write our function to add new entries to the database. Again this function will be very simple, Just a straight forward insert query.
function insert( $data = array() ) {
$data["name"] = $this->db->escape_str($data["name"]);
$data["url"] = $this->db->escape_str($data["url"]);
$data["comment"] = $this->db->escape_str($data["comment"]);
$data["name"] = htmlspecialchars( $data["name"] );
$data["url"] = htmlspecialchars( $data["url"] );
$data["comment"] = htmlspecialchars( $data["comment"] );
$sql = "INSERT INTO ". $this->table ." (comment_id,name,url,comment) VALUES ('null','". $data["name"] ."','". $data["url"] ."','". $data["comment"] ."')";
return $this->db->query( $sql );
}
You should be able to follow that code quite easily, it's just escaping the data and using htmlspecialchars to prevent XSS attacks and then inserting it into our comments table. Now we're done with the model and we can move on to getting our controller working.
class Guestbook extends Controller {
function __construct() {
parent::Controller();
}
function index() {
echo "Hello World";
}
}
Thats what we had with our controller, Now obviously we don't actually want it to output "Hello World" so we can go ahead and delete that and start building it up properly. CodeIgniter by default unsets $_POST and $_GET data but it will process it first and send it to the input class for security. So to access post data we will need to use the input class.
$this->input->post("post_name");
So on our controller we want to first check to see if the user has tried to submit a comment and process that first.
class Guestbook extends Controller {
//...
function index() {
if( $this->input->post("submit") ) {
$data = array(
"name" => $this->input->post("name"),
"url" => $this->input->post("url"),
"comment" => $this->input->post("comment")
);
$this->Guestbook_model->insert( $data );
}
}
}
Once again nothing complex going on here, Just putting all data which will be posted by the user into an array and then passing it to the guestbook model.
Next we need to grab all entries using our view function in the guestbook model and then pass the data to a template file.
class Guestbook extends Controller {
// ...
function index() {
$data = array();
$data["posted"] = false;
if( $this->input->post("submit") ) {
$data = array(
"name" => $this->input->post("name"),
"url" => $this->input->post("url"),
"comment" => $this->input->post("comment")
);
if( $this->Guestbook_model->insert( $data ) ) {
$data["posted"] = true;
}
}
$data["entries"] = $this->Guestbook_model->view();
$this->load->view("guestbook.php", $data);
}
}
Now we've got a bit more code to deal with, Firstly i've defined an array called data and it has one entity "posted" which value currently stands at false. Now when it submits the new comment to be added to the database it will see if the model return true and if it does then it will set "posted" to true, this is so we can have a thank you message on the script. After that we get the data which the function view in the guestbook model returns and adding it to the data array. After that using the load view function we are telling Code Igniter to open a template called guestbook.php and pass our data array to it.
Finally we need to create the template. Create a blank document in the views file (System -> Application -> Views) and name it guestbook.php, in the document add all the usual html bits and bobs.
The way CodeIgniter works is when a view is loaded and an array is passed to the view it will split the array up so you have to use the array key to use that data. For example if you passed this array -
$data["test"] = "Hello";
to the view file then you could echo the array value by using $test -
echo $test; // Would output "Hello"
So we are going to loop through our database results and echo them in an unordered list.
-
<?php foreach( $entries as $entry ) { ?>
<li><strong>Posted by <a href="#"><?php echo $entry["name"]; ?></a></strong>
<p><?php echo $entry["comment"]; ?></p>
</li>
<?php } // end foreach ?>
</ul>
This is a straight forward foreach loop looping through each of the array entities and echoing the comment as a list item.
<!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=iso-8859-1" />
<title>TutDepot Guestbook Demonstration</title>
</head>
<body>
<?php if( $posted == true ): ?>
<h3>Thanks for your entry</h3>
<?php endif; ?>
<ul>
<?php foreach( $entries as $entry ) { ?>
<li><strong>Posted by <a href="#"><?php echo $entry["name"]; ?></a></strong>
<p><?php echo $entry["comment"]; ?></p>
</li>
<?php } // end foreach ?>
</ul>
<form method="post" action="">
<fieldset>
<legend>Submit a comment</legend>
<input type="text" name="name"> <lable>Name</label>
<input type="text" name="url"> <label>Url</label>
<textarea name="comment"></textarea> <label>Comment</label>
<input type="submit" name="submit" value="submit">
</fieldset>
</form>
</body>
</html>
Finally we need to add a simple form for users to post guestbook entries, This form is just going to post to the page its currently on and then in our controller it will pick up the post data and send it to the model. I've also added a if statement to check if an entry has been successfully posted and if so it will add a thank you message to the top of the guestbook and that's it for this tutorial. I hope it has helped you and has given you a good starting point for working with CodeIgniter.