Getting started with CodeIgniter
CodeIgniter is a PHP framework build by EllisLab the creator of Expression Engine. In this tutorial I will cover the basics while creating a simple guest book application. First of all you need the latest version of CodeIgniter, so grab the latest release and upload the files to the root from your website. CodeIgniter uses the Model View Controller (MVC) architectural pattern which gives you the flexibility when it comes to reusing, altering and upgrading code. If you navigate through the CodeIgniter files, go to the application folder (System -> Application) where you will see 3 sub folders with the names: models, controllers and views. A controller will control what the users can see on his screen and a model is used to run various functions. The view is simply a template.
CodeIgniter guest book tutorial
The example controller I will use next is called “welcome.php”. To change the default controller we need to change the file named routes.php which is located inside config folder. Scroll down to the bottom of the file and you will find:
$route['default_controller'] = "welcome";
Change “welcome” to “guestbook” because we will rename the controller later to “guestbook.php”. But first open the file database.php config file (System -> Application -> Config -> database.php) and update the settings for your database.
$db['default']['hostname'] = "localhost"; $db['default']['username'] = "root"; $db['default']['password'] = ""; $db['default']['database'] = "guestbook"; $db['default']['dbdriver'] = "mysql";
Now create an empty file and save it in the controllers folder with the name “guestbook.php”. In this PHP file we create a PHP class named “Guestbook” which extends the main class “Controller”.
<?php class Guestbook extends Controller { }
In our construct function we need to tell our class the parent class controller is used. We create also our first function named “index”.
class Guestbook extends Controller { function __construct() { parent::Controller(); } function index() { echo "Hello World"; } }
If you launch your test site you should see “Hello World” on the screen. Re-open the controller file, remove the “hello world” example code and save the file. 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;
For the model create a new file inside the models folder (System -> Application -> Models) and name it “guestbook_model.php”. Inside the file create the Guestbook_model class which extends the parent model class. Just like the controller we created before.
class Guestbook_model extends Model { function __construct() { parent::Model(); } }
We only need two functions for our model: one to post entries and one to read them from the database. To use the various available libraries in CodeIgniter, we need to load them first. A good place to load our database, is the construct function.
class Guestbook_model extends Model { function __construct() { parent::Model(); $this->load->database(); } }
Instead of loading the library in each individual model we can load them using the autoload feature. Open the file autoload.php (System -> Application -> Config -> autoload.php) and add the to the array name libraries.
$autoload['libraries'] = array();
You need to place the names of each library you like to load to use.
$autoload['libraries'] = array('database');
Go back to the model and we will build the first “view” function.
function view() { $sql = "SELECT * FROM ". $this->table ." ORDER BY comment_id DESC"; }
First we need define the variable named “table”. This variable gives us freedom to change the table name later without the need to change our PHP code. The function will use some SQL statement to query our database for the guestbook entries and returns the 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 a function to add new entries into database.
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 ); }
The code above is straight forward, we escape the data using htmlspecialchars to prevent XSS attacks and insert the data into the comments table. Now we’re done with the model and we can continue to get the controller working. CodeIgniter doesn’t provide the direct access to $_POST and $_GET vars for security reasons. This why we process them first using the native input class:
$this->input->post("post_name");
In our controller we create an input object for our post data and let CodeIgniter check what the user has submitted as a comment.
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 ); } } }
Next we need to grab the entries using our view function in the guestbook model and pass the data to the 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, First I create an array called data which holds a single one default value “false”. Whenever the comment form is submitted, the data will be checked and added to the database. The function will set the value for the data array element name “posted” to “true”. We can use the flag to return a thank you message in our script. After that we read the data by calling the function view from our guestbook model and returns the data in an array format. Now we call the load view function and tell CodeIgniter to open the template with the name guestbook.php. The array with the name $data is passed to the template. Finally we need to create the template. Create an empty file inside the views folder (System -> Application -> Views) and name it guestbook.php. Place all your HTML code into this template file. CodeIgniter will parse the template and will pass the $data array to different places inside the template. 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 echo '<ul>'; foreach( $entries as $entry ) { echo '<li><strong>Posted by <a href="#">'.$entry['name'].'</a></strong><p>'.$entry['comment'].'</p></li> } echo '</ul>'; ?>
Finally we need to add a simple form to post new guestbook entries. I’ve added an IF statement to check if an entry has been successfully submitted. If the entry was submitted a thank you message will show up at the top of the guest book.
<!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 ) echo '<h3>Thanks for your entry</h3>'; ?> <?php echo '<ul>'; foreach( $entries as $entry ) { echo '<li><strong>Posted by <a href="#">'.$entry['name'].'</a></strong><p>'.$entry['comment'].'</p></li> } echo '</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>
I hope this PHP tutorial is a good starting point if you consider to use CodeIgniter for your PHP projects.
Published in: PHP Scripts