Вы находитесь на странице: 1из 104

Introduction to the CodeIgniter PHP Framework (Page 1 of 4 ) Building web applications with PHP is a pretty simple process.

As a PHP developer, you can develop practically anything, including database abstraction layers, form validation programs, file upload applications, and so forth. The list goes on and on. Once you've mastered the foundations of the object-oriented paradigm and learned how to implement certain common design patterns in real-world conditions, you should be armed with a useful toolkit comprised of all sorts of classes and functions that can be used any number of times. Although you may not be aware of this fact, your toolkit can be considered a general PHP development framework. The end result of your own efforts and skills as programmer. However, there are certain situations when the capabilities offered by your own framework simply arent good enough to fit the requirements of a particular application. In a case like this, you can either upgrade your framework, which will probably require coding additional classes and functions, or you can pick up a third-party software from the numerous packages available on the web today. If you choose the latter, then youll be confronted with another challenge that will keep your mind spinning in circles. Should I pick up a full-featured framework like Zend, or should I work with a more approachable solution, like CakePHP or WACT? Actually, the answer to that question depends strongly on what type of project youre going to develop and how much time you want to spend configuring and learning how to use a particular framework. For instance, Zend is great for building enterprise-level PHP applications, but it's likely that youll find it pretty overwhelming to work with at first. On the other hand, CakePHP can be much easier to set up and use, even though theyre not loaded with all the features offered by Zend. However, in the last few months, a small framework has gained popularity with many PHP programmers due to its ultra-fast learning curve and easy configuration. Actually, Im talking about CodeIgniter (http://codeigniter.com), a solid piece of software written by Rick Ellis in PHP 4. It permits users to develop small and middle-scale PHP applications in minutes (literally) with minimal setup. In addition, CodeIgniter is built around the Model-View-Controller pattern, which allows you to easily separate data from application logic and visual presentation. Introduction to the CodeIgniter PHP Framework - Start using CodeIgniter (Page 2 of 4 ) Obviously, the first step that you should take before using Code Igniter is installing its source files into your test web server. To do so, simply point your browser to the following url: http://codeigniter.com/downloads/. Download the ZIP file that contains these files. Once you've accomplished this, unzip the package and upload its folders and files to a chosen directory of your web server. In my personal case, I saved it to a /codeigniter/ directory under the servers root, but you may want to select a different location. Finally, navigate to the application/config/config.php file, then open it with your code editor and configure the following array settings, as shown below:

|-------------------------------------------------------------------------| Base Site URL |-------------------------------------------------------------------------$config['base_url'] = "http://127.0.0.1/codeigniter/"; |-------------------------------------------------------------------------| Index File |-------------------------------------------------------------------------$config['index_page'] = "index.php"; |-------------------------------------------------------------------------| Default Language |-------------------------------------------------------------------------$config['language'] = "english"; |-------------------------------------------------------------------------| Default Character Set |-------------------------------------------------------------------------$config['charset'] = "UTF-8"; |-------------------------------------------------------------------------| Cache Directory Path |-------------------------------------------------------------------------$config['cache_path'] = 'http://127.0.0.1/codeigniter/cache/'; |-------------------------------------------------------------------------| Session Variables |-------------------------------------------------------------------------$config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_encrypt_cookie'] = FALSE; $config['sess_use_database'] = FALSE; $config['sess_table_name'] = 'ci_sessions'; $config['sess_match_ip'] = FALSE; $config['sess_match_useragent'] = TRUE; $config['sess_time_to_update'] = 300; |-------------------------------------------------------------------------| Global XSS Filtering |-------------------------------------------------------------------------$config['global_xss_filtering'] = FALSE; |-------------------------------------------------------------------------| Output Compression |-------------------------------------------------------------------------$config['compress_output'] = TRUE;

|-------------------------------------------------------------------------| Rewrite PHP Short Tags |-------------------------------------------------------------------------$config['rewrite_short_tags'] = FALSE;

As you can see, the above settings provide Code Igniter with crucial information about your web applications, including the base url of your site, the default language and character set, and the index file that will be utilized. Also, its possible to specify whether any output generated by an application should be filtered to prevent XSS attacks, and whether it should be cached and compressed previously. Finally, theres a number of simple options that tell Code Igniter how to handle session data. They are actually fairly easy to configure. Although, you should pay special attention to the following entries:

$config['sess_use_database'] = FALSE; $config['sess_table_name'] = 'ci_sessions';

If a value of TRUE is assigned to the first array element, then Code Igniter will store all of your session data in a MySQL database table, whose name will be specified in the second entry. In this case, a FALSE value has been assigned to the first setting, meaning that session data will be saved to a temporary directory in the web server. Lastly, its possible to configure whether the use of short PHP tags will be enabled within view files. This is something that will be discussed in more detail when I develop some sample applications for you. For now, Ill keep this option disabled. So far, so good. I showed how to configure the main entries of Code Igniters config.php file. Of course, when you edit the file in question, youll see that it contains a few additional settings. However, to keep things rather simple, Im going to use only the ones discussed above. Now that the config.php file has been properly setup, its time to move on and learn how to configure an additional file, which is located at /config/database.php and is used by Code Igniter when working with MySQL databases. To see how this database file will be edited, please click on the link below and read the following section. Introduction to the CodeIgniter PHP Framework - Activating support for MySQL databases (Page 3 of 4 ) As I said previously, the last file that youll need to edit is the one located at /config/database.php. Open it and assign the correct values to the following settings:

$active_group = "default"; $active_record = TRUE; $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'] = = = = = = = = = = = = "localhost"; "root"; "mypassword"; "mydatabase"; "mysql"; ""; TRUE; TRUE; FALSE; ""; "utf8"; "utf8_general_ci";

As you can see, all of the above entries are self explanatory, since theyre used by Code Igniter to connect to MySQL and select a particular database, which youve probably done hundreds of times before. However, in this case its possible to work with several sets of connection values. Suppose for a moment that you need to use multiple development environments with a shared web server. In that case you might want to create a connection group for each of these environments in the following way:

$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']

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

"localhost"; "root"; "mypassword"; "mydatabase"; "mysql"; ""; TRUE; FALSE; FALSE; ""; "utf8"; "utf8_general_ci";

$db['production']['hostname'] = "localhost"; $db[' production']['username'] = "root"; $db[' production']['password'] = "myotherpassword"; $db[' production']['database'] = "myotherdatabase"; $db[' production']['dbdriver'] = "mysql"; $db[' production']['dbprefix'] = ""; $db[' production']['pconnect'] = TRUE; $db[' production']['db_debug'] = FALSE; $db[' production']['cache_on'] = FALSE; $db[' production']['cachedir'] = ""; $db[' production']['char_set'] = "utf8"; $db[' production']['dbcollat'] = "utf8_general_ci";

See how easy it is to set up two sets of MySQL connections for different development environments? I hope you do! Finally, the active_record entry should be activated when accessing MySQL database tables using the homonymous pattern. Actually, Code Igniter comes bundled with a bunch of methods that allow you to handle MySQL data via the active record approach. However, this topic will be covered in upcoming tutorials of this series, therefore, this option will be left enabled. So far, these are all the array entries that youll need to edit in the database.php file in order to activate the support for MySQL databases. At this stage, everything has been properly setup to start developing object-oriented applications with Code Igniter! In the section to come Ill be showing you how to build a simple PHP program that uses the Model-View-Controller pattern in order to display a trivial message on the browser. To learn how this initial sample application will be developed, click on the link below and keep reading. Introduction to the CodeIgniter PHP Framework - Developing the first application with Code Igniter (Page 4 of 4 ) As I mentioned in the introduction, Code Igniter uses the Model-View-Controller pattern to build web applications. This comes in handy for separating business and application logic from the visual presentation. Thus, since I plan to develop a simple application that will display a simple message on the screen, the first thing that Im going to do is define the corresponding controller class. To do this, Ill create a class called HelloWorld, which will be saved to the /system/application/controllers/ folder as helloworld.php." The signature of this sample class looks like this:

<?php class HelloWorld extends Controller{ function HelloWorld(){ // load controller parent parent::Controller(); } function index(){ $data['title']='My first application created with Code Igniter'; $data['message']='Hello world!'; // load 'helloworld' view $this->load->view('helloworld',$data); } } ?>

Now that you know how the HelloWorld controller class looks, its necessary to dissect it in different parts and explain the functionality. In the first place, you should notice that each time a new controller is created, it must extend the default controller provided by Code Igniter. Therefore, this sample class is defined as a subclass of this controller.

Then, this sample class loads the parents constructor and then defines a brand new method called index(). This method has a special meaning for Code Igniter, since it will be called automatically whenever it finds it was implemented by a specific controller. Still with me? Great! Then, its time to analyze what this method actually does. As you can see, it defines the data that will be passed in to the view file to be displayed later on. This data is first stored on a simple $data array, and second transferred to a view template, called helloworld.php. Each time a view file needs to be loaded, Code Igniter uses a Loader class, which is included by default by each new controller created. So, in this case the below expression:

$this->load->view('helloworld',$data);

simply loads the corresponding view file and passes the data that will be printed on the browser to it. Pretty intuitive, right? Now that you've hopefully grasped how the previous HelloWorld controller class works, Im sure that youll want to see how the respective helloworld.php view file looks. Below I included the definition of the file in question, which should be saved to the /system/application/views/ folder:

<html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $message?></h1> </body> </html>

As shown above, the structure of the helloworld.php view file is extremely simple. It only contains a couple of echo PHP statements, which are used to display the data passed by the controller. Also, you should recall that this data was stored on a $data array, so its respective keys are automatically turned into variables within the view template. So far, so good. At this point, you hopefully understand how the controller passes certain data in the form of an array to a view file to be echoed to the browser. However, its possible that youre wondering how to test the previous HelloWorld controller with Code Igniter. Code Igniter uses a special routing process that permits you to invoke a specific controller by using an URL. The first URL segment is the name of the controller that will be loaded by a certain application, then the second segment corresponds to the name of a method of the controller that will be invoked. The third segment is an optional argument taken by this method.

This explanation might sound pretty confusing to you. However, the following code sample should dissipate any possible doubts you might have. To call the previous HelloWord controller, Id type the following URL:

http://localhost/codeigniter/index.php/helloworld/

As you can see, the first URL segment calls the HelloWorld controller, and automatically executes its index() method, which displays the view file previously created. Try it for yourself and youll see the classic Hello World message printed on your screen. In addition, to clarify how Code Igniters routing process works, say that I changed the definition of the HelloWorld controller class and now it looks like this:

class HelloWorld extends Controller{ function HelloWorld(){ // load controller parent parent::Controller(); } function display(){ $data['title']='My first application created with Code Igniter'; $data['message']='Hello world!'; // load 'helloworld' view $this->load->view('helloworld',$data); } }

In this case, the URL that should be used to call the display() method of the controller would be:

http://localhost/codeigniter/index.php/helloworld/display/

Pretty easy to grasp, right? By using this routing method, Code Igniter assures that all of the URLs generated by a PHP application will look clear and be search engine-friendly as well. And with this final hands-on example, Im finishing this first tutorial of this series. As you saw before, I provided you with concrete material that hopefully will help you start mastering the basic features of Code Igniter. You have a lot of fun ahead! Final thoughts In this first chapter of the series, I walked you through the core concepts that surround the use of the Code Igniter PHP framework. You hopefully learned how to correctly setup its

configuration files, and how to create a simple web application comprised of a single controller and a view file. Im only scratching the surface when it comes to discussing the vast set of handy features that come bundled with Code Igniter. Therefore, in the next article, Ill be covering the use of models and the utilization of some of its core classes. Dont miss the upcoming tutorial! Building a Database-Driven Application with the Code Igniter PHP Framework (Page 1 of 4 ) Introduction Now that you have been introduced to the main subject of this series, its time to recall the concepts deployed in the preceding tutorial, in case you havent had the chance to read it yet. During that article, I discussed a few basic topics you will need to understand to start using Code Igniter, ranging from how to correctly set up its configuration files and understanding its URL routing mechanism, to developing a sample web application, which made use of the Model-View-Controller approach. Put in a simple way, the application was tasked with displaying a trivial message on screen, a process that was performed by way of two source files. The first one was defined as the applications controller, and the second one was simply a template file, also known as a view within the context of the MVC pattern. Essentially, the relationship established between these two sample files can be outlined as follows: the controller precisely controls the flow of the application and passes a bunch of data to be embedded into an HTML file to the view, which is finally displayed on screen. Thats all. However, this initial sample application was pretty primitive, actually. Therefore, in this second part of the series, Im going to teach you how to use some core classes bundled with Code Igniter, this time for building a MySQL-driven program, which will first fetch some data from a MySQL database table, and then print this information on the browser. As youll see in the next few lines, developing this PHP application will require us to define a model class, apart from building the respective controller and view files. Thus, dont waste more time in preliminaries and begin reading now! Building a Database-Driven Application with the Code Igniter PHP Framework Retrieving user-related data from a MySQL table (Page 2 of 4 ) As I anticipated in the beginning, the first step involved in the development of this MySQLdriven application will require defining a model class. In crude terms, this class will act as a simple interface for retrieving user-related data from a sample users MySQL table. To clarify a bit more how this class is going to work, please take a look at its signature, which is listed below:

class Users extends Model{ function Users(){ // call the Model constructor

parent::Model(); // load database class and connect to MySQL $this->load->database(); } function getAllUsers(){ $query=$this->db->get('users'); if($query->num_rows()>0){ // return result set as an associative array return $query->result_array(); } } function getUsersWhere($field,$param){ $this->db->where($field,$param); $query=$this->db->get('users'); // return result set as an associative array return $query->result_array(); } // get total number of users function getNumUsers(){ return $this->db->count_all('users'); } }

As shown above, the previous Users class extends the model that comes included with Code Igniter, and has been provided with a set of intuitive methods that come in useful for retrieving some rows from a users database table. As you can see, the class in question is capable of fetching one row at a time and multiple records as well, and additionally has the ability to count the number of rows contained within a result set. However, the most interesting facet of this model class is the way that it implements all of its methods. In this particular case, the constructor first loads the database class bundled with Code Igniter via a loader object, and then connects to MySQL using the set of parameters specified in the database.php file that you learned in the previous article. From this point onward, the model uses some methods provided by the aforementioned database class to fetch user data from the corresponding users MySQL table. Of course, Im not going to list the complete API corresponding to the Code Igniter database class, since you can visit its web site for a full reference on them. But heres a brief description of the methods used by the previous Users model:

$this->db->get('table_name'): get all the rows from the specified MySQL table $this->db->where($field,$param): performs a where query against the specified MySQL table $this->db->count_all('table_name'): count all the rows in the specified MySQL table $query->result_array(): returns a result set as a multidimensional array $query->num_rows(): counts the number of row returned in a result set

As you can see, the built-in Code Igniter database class includes a group of straightforward methods, which can be used to perform the most common database-related tasks, such as fetching and counting rows, handling data sets, and so forth. As I stated before, however, you should read Code Igniters user guide for further information about how these methods work. Well, at this point I showed you how to create a simple Users model class that can be utilized for retrieving and counting rows from sample MySQL table. Before I forget, you should save the model to the /system/application/models/ folder of Code Igniter, so it can load it correctly later on. Provided that you grasped the logic that drives this class, the next thing that Im going to teach you will be how to build a controller class. This class will perform a few useful tasks, such as retrieving information from the table by using the models API, and embedding this data straight into a view file. To learn how this controller class will be built, please jump forward and read the following section. Building a Database-Driven Application with the Code Igniter PHP Framework Defining a controller class (Page 3 of 4 ) In the section that you just read, I demonstrated how to build a model class, which came in helpful for retrieving data from a users MySQL table. Its time to build the corresponding controller, which will use the API of the model to directly access this user-related data. Please examine the signature of this brand new controller class, which looks like this:

class Users extends Controller{ function Users (){ // load controller parent parent::Controller(); // load 'Users' model $this->load->model('Users'); } function index(){ // store data for being displayed on view file $data['users']=$this->Users->getUsers(); $data['numusers']=$this->Users->getNumUsers(); $data['title']='Displaying user data'; $data['header']='User List'; // load 'users_view' view $this->load->view('users_view',$data); } }

As shown above, I created the previous user controller class by extending the default controller that comes bundled with Code Igniter. Again, dont forget to save this file to the /system/application/controllers/ folder of Code Igniter for later use. Besides, there are some important details that you should notice with reference to the way that this class has been defined. First, note how the controller uses the corresponding loader class for loading the user model defined in the prior section.

See how easy it is to instruct a controller to load a particular model? I guess you do! The required syntax for performing this task is the following:

$this->load->model('model_name');

Simple and intuitive, right? Now that you have learned how to include a determined model from within a controller class, its time to pay attention to the implementation of the index() method, which actually is very interesting. As you can see, it uses the models API to fetch all the rows of the pertinent users database table, along with the number of records contained in the table in question. In addition, its very important to stress here the notation used for accessing the models API. Heres an example of how to do this:

$data['users']=$this->Users->getUsers();

In this case, since the model has been named Users, Code Igniter automatically creates an object that can be referenced as $this->Users. Naturally, if theres a model called Blog, it should be called within the controller as $this->Blog. Thats not too difficult to understand, right? Now, returning to the implementation of the index() method, it finishes its execution by defining some additional parameters, which are first stored in the $data array, and then passed to the corresponding view file for display purposes. Also, an additional explanation is in order here: please, notice how the controller reuses the loader object for loading the view and populating it with user-related data. So far, so good. At this stage, I showed you how to build a controller class, which uses the models API, to fetch some rows from a sample users MySQL table, and to embed this data into a view file. Nonetheless, if youre like me, then at this moment youre wondering how this view file actually looks. Well, in response to that question, in the following section Ill be creating this view, completing the development of this MySQL-driven application. Please, click on the link below and keep reading. Were almost done! Building a Database-Driven Application with the Code Igniter PHP Framework Outputting user-related data with Code Igniter (Page 4 of 4 ) Before I proceed to demonstrate how to build a simple view file for displaying the contents of the corresponding users MySQL table, first its necessary to define the structure of the table in question and to populate it with data about some fictional users.

Therefore, based on this requirement, heres how this sample table would look:

As shown above, this MySQL table is composed of four basic fields, named id, firstname, lastname, and email respectively, which also have been populated with data about some hypothetical users (yes, I can dream of Jennifer Aniston being a user of my application, can't I?). Now that this sample table has been created and filled with basic information, its time to define the view file that will display this data on screen. Take a look at it, please:

<html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $header;?></h1> <ul> <?php foreach($users as $user):?> <li> <p><?php echo 'Full Name: '.$user['firstname'].' '.$user['lastname'].' Email: '.$user['email'];?></p> </li> <?php endforeach;?> </ul> <p><?php echo 'Total number of users :'.$numusers;?></p> </body> </html>

As shown above, the view file is indeed extremely simple to grasp. In this specific case, the contents of the $data array defined by the controller are automatically turned into PHP variables, and their values are echoed to the browser in the form of an HTML page. Also, its worthwhile to note how user data is traversed with a foreach loop, which has been interspersed into the HTML markup.

Finally, you must save the view file to the /system/application/views/ folder, and test it by typing the following URL on your browser:

http://localhost/codeigniter/index.php/users/

Thats all, trust me. Try out this example with your own web server and youll see that it works like a charm. So, are you starting to realize how easy it is to build a database-driven application with Code Igniter? I hope you are! And if you still arent convinced about the great functionality of this PHP framework, then use all the code samples included in this tutorial, and start coding your own programs. Fun is already guaranteed! Final thoughts In this second part of the series, you hopefully learned how to develop a basic MySQL-driven application with Code Igniter. As you saw for yourself, the process in actually straightforward and permits to implement very easily the MVC pattern. In the next article, Im going to teach you how to paginate database records with Code Igniter, so now that you know what to expect from this tutorial, you dont have any excuses to miss it! Page 1 of 4 ) Introduction Building PHP applications using a third-party framework can be a time-consuming process, particularly in those cases where the software chosen requires installing and configuring a large number of source files, as well as dealing with a long and difficult learning curve. Luckily, not all PHP frameworks are created in the same painful way. A good example of this is Code Igniter, a solid piece of software written in PHP 4 that allows you to develop full-featured web applications by means of a friendly API, and by taking advantage of the functionality provided by the Model-View-Controller pattern. Therefore, if youre interested in learning how to use the powerful tools that come packaged with Code Igniter and start creating full-blown database-driven applications in a very short time, then you should start reading this group of articles now! And speaking of articles, youll surely recall that in the previous one, I explained how to develop a simple MySQL-based web application, which was capable of fetching a few rows straight from a database table and displaying their contents on the browser. However, even though the functionality of this introductory application was fairly limited, its worth mentioning that this example was built by utilizing the MVC pattern. This means that it was comprised of three modules, that is a model class, then the corresponding controller and finally a simple view for embedding these database rows into a basic HTML page.

As you may guess, however, Code Igniter comes bundled with a robust set of core classes, which can be used to perform all sorts of clever tasks, such as working with databases, performing file uploads, validating user-supplied data, and so forth. So, in this third chapter of this series, Im going to show you how to improve the MySQLdriven application developed in the preceding tutorial, since itll be provided with the capacity for paging database records, via the pager class included with Code Igniter. Now, its time to get rid of the boring theory and see how easy is to build a pagination system with Code Igniter. Lets jump in! Paginating Database Records with the Code Igniter PHP Framework - Retrieving user-related data from a MySQL table (Page 2 of 4 ) Since my plan consists basically of demonstrating how to build a basic PHP application, capable of paging a few database rows, Im going to use the same sample users MySQL table that was created in the previous article. As youll recall, the table was populated with data about some fictional users. Its structure looked like this:

Now that youre familiar with the above MySQL table, its time to build a model class that permits us to access its rows in a painless fashion. So take a look at the following User model class, which accomplishes this task. Here it is: class Users extends Model{ function Users(){ // call the Model constructor parent::Model(); // load database class and connect to MySQL $this->load->database(); } function getAllUsers(){ $query=$this->db->get('users'); if($query->num_rows()>0){ // return result set as an associative array return $query->result_array(); } }

function getUsersWhere($field,$param){ $this->db->where($field,$param); $query=$this->db->get('users'); // return result set as an associative array return $query->result_array(); } // get 5 rows at a time function getUsers($row){ $query=$this->db->get('users',5,$row); if($query->num_rows()>0){ // return result set as an associative array return $query->result_array(); } } // get total number of users function getNumUsers(){ return $this->db->count_all('users'); } } If you read the preceding tutorial of the series, its possible that you find the above model class pretty familiar. As you can see, it presents a group of methods that can be used for fetching both single and multiple rows from the pertinent users MySQL table, as well for counting the number of records contained within a given result set. Also, its worthwhile to clarify again that this model implements all of its methods thanks to the functionality of the database class included with Code Igniter, which is loaded by the corresponding constructor. However, you should pay close attention to the signature of a brand new method, called getUsers(). It permits the program to fetch five rows at time. Im going to take advantage of its functionality to build a simple, yet effective, paging system. Now that you hopefully grasped how the previous model class does its thing, please save it to the system/application/models/ folder and jump forward to see how to define the other building block of this MySQL-driven application. In this case, Im talking about the corresponding controller class, which not only will be capable of embedding database contents into a view file, but will also implement the aforementioned paging mechanism. To learn how this controller class will be constructed, please click on the link that appears below and keep reading. Paginating Database Records with the Code Igniter PHP Framework - Paging database records with Code Igniter (Page 3 of 4 ) Indeed, the philosophy that drives Code Igniter allows us to simplify the development of complex applications. And paginating database records certainly isnt an exception, since the framework includes a solid pager class, which can be easily customized to suit the requirement of a huge number of projects. In this particular case, where its necessary to create a user controller class that uses the methods of the model coded previously, the pager class of Code Igniter fits perfectly into this schema. Below I built a brand new controller that exploits the functionality of this pager class to paginate rows fetched from the prior users MySQL table. Heres the code for this class:

class Users extends Controller{ function Users(){ // load controller parent parent::Controller(); // load 'Users' model $this->load->model('Users'); } function display($row=0){ // load pagination library $this->load->library('pagination'); // set pagination parameters $config['base_url']='http://127.0.0.1/codeigniter/index.php/users/display/'; $config['total_rows']=$this->Users->getNumUsers(); $config['per_page']='5'; $this->pagination->initialize($config); // store data for being displayed on view file $data['users']=$this->Users->getUsers($row); $data['title']='Displaying user data'; $data['header']='User List'; $data['links']=$this->pagination->create_links(); // load 'testview' view $this->load->view('users_view',$data); } } As illustrated above, the User controller class looks pretty similar to the one built in the previous tutorial. However, there's an important difference that Id like to point out here, since it implements a new method called display(). As you can see, the method in question first includes, via the corresponding loader object, the pagination class. Then, it initializes some of its parameters, such as the base URL of the paging links, the total number of rows that will be spawned, and finally the number of records that will be displayed per page. Once the pagination class has been correctly set up, its used for creating the paging links via its create_links() method. Lastly, the display() method retrieves the paginated rows from the corresponding users MySQL table, which are directly embedded along with the pertinent links into a view file. And before I forget, please save the user controller class to the Code Igniter system/application/controllers/ folder. However, if youre anything like me, you wonder how the view file will be created, right? Thus, in the last section of this tutorial Im going to show you how to define this file, in this way finishing the development of this MySQL-driven application aimed at demonstrating how to paginate database rows with Code Igniter. What are you waiting for? Jump forward and read the next section! Paginating Database Records with the Code Igniter PHP Framework - Completing the development of the sample MySQL-driven application (Page 4 of 4 ) In the section that you just read, you learned how to use the pagination class included with Code Igniter to display a few paginated rows, which were retrieved from the corresponding users MySQL table, defined earlier.

In this case, though, the term display isnt totally correct, since its necessary to build a view file first, which will actually print this data on the browser. Taking into account this concept, below I listed the signature of the file in question, so you can grasp quickly how it works. Take a look at it, please: <html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $header;?></h1> <ul> <?php foreach($users as $user):?> <li> <p><?php echo 'Full Name: '.$user['firstname'].' '.$user['lastname'].' Email: '.$user['email'];?></p> </li> <?php endforeach;?> </ul> <p><?php echo $links;?></p> </body> </html> If you examine in detail the above view file, youll have to agree with me that it looks really simple! As show before, the file includes a few echo statements, which are used to display the paged rows and for showing the respective page links. Asides from listing for you the prior view file, I also included below a couple of illustrative images, which show how the paginated records are displayed on the browser. Here they are:

See how simple it is to paginate database rows with Code Igniter? I bet you do! Indeed, the whole process is reduced to defining a controller that uses its pagination class, and then creating a view file that displays the paged rows. Thats all. And now that I mentioned a view file, dont forget to save the previous one to the Code Igniter /system/application/views/ folder, so you can test the complete database-driven application by typing the following URL:

http://127.0.0.1/codeigniter/index.php/users/display

With this final example, Im wrapping up this tutorial on paginating database records. As usual with many of my articles on PHP development, feel free to tweak all of the code samples shown in this article, so you can acquire a more solid background in using Code Igniter. Final thoughts In this third chapter of the series, I demonstrated how easy it is to develop a MySQL-based web application that implements an effective paging mechanism with the Code Igniter PHP framework. Undoubtedly, this particular example demonstrates that a framework can be friendly and powerful at the same time. In the next installment, Ill be showing you how to use Code Igniters validation class along with some helper functions to validate web forms. Dont miss the next article! Validating Web Forms with the Code Igniter PHP Framework (Page 1 of 4 )

Introduction As you know, not all the PHP frameworks available nowadays on the web have been created in the same way. This is particularly relevant when you need to choose one of them with which to start developing several web applications. For example, Zend is a solid piece of software, best suited to building enterprise-level PHP programs. This means that some of its features can be pretty overwhelming for developers taking their first steps into the huge terrain of object-object programming. However, among the numerous PHP frameworks that present a friendly learning curve, theres one that stands from the rest, not only for its remarkable capabilities for developing complex applications in a short time, but for its minimal setup requirements. Of course, as you might have guessed, Im talking about Code Igniter (http://codeigniter.com), a software package created with PHP 4 that allows you to build database-driven PHP programs within minutes! No, really. In the previous tutorial of this series, I demonstrated how to use this framework to develop a simple MySQL-driven application. It was tasked with pulling a few database records from a simple table to be displayed later on the browser. In addition, its worth mentioning that the application in question had the capacity for paging these records across several web documents, thanks to the assistance of the pagination class that comes bundled with Code Igniter. Now that I have quickly summarized the topics that were discussed in the last tutorial, its time to continue exploring the many other useful features offered by Code Igniter. Therefore, in the course of the next few lines, Im going to show you how to use the validation class included with this framework to develop a PHP program that can be used to check data submitted through some web forms. Once again, youll have opportunity to see for yourself how easy it is to validate online forms with Code Igniter. Lets get started! Validating Web Forms with the Code Igniter PHP Framework - Validating usersupplied data using the MVC pattern (Page 2 of 4 ) As I mentioned in the introduction, validating web forms with Code Igniter is actually a nobrainer process that can be tackled by any developer with an intermediate background in the Model-View-Controller pattern. To be frank, the whole validation procedure is reduced to creating a controller class that checks to see if the data collected with an online form is valid or not, and then shows one of two different views, according to the result of this checking process. Obviously, the first view will display a successful web page, while the second one will show an error message along with the corresponding web form. Quite simple to understand, right? However, the best way to grasp how to validate online forms with Code Igniter is simply by showing some functional code. Period. Thus, based on this concept, below I listed the signature of a brand new controller class which performs all the validation steps described previously. Here it is:

class Validator extends Controller { function Validator(){ // load controller parent parent::Controller(); // load 'url' helper $this->load->helper('url'); // load 'form' helper $this->load->helper('form'); // load 'validation' class $this->load->library('validation'); } function index(){ // set validation rules $rules['firstname']="required"; $rules['lastname']="required"; $rules['email']="required"; $this->validation->set_rules($rules); // check if form has been submitted properly if ($this->validation->run()==FALSE){ // redisplay web form $this->load->view('form_view'); } // display success web page else{ $this->load->view('success_view'); } } }

Its hard to believe, but the above Validator controller class is almost all the PHP code required to validate a web form. In this specific case, the controller begins loading all of the classes that itll need to perform a basic validation on a sample contact form. The form is composed of some typical fields, such as the users first and last names, and the email address. As you can see, the class includes a couple of helper functions, called url and form respectively. Not surprisingly, these functions are used by Code Igniter to generate dynamic URLs and form parts too. However, these functions will be utilized at a later time, when rendering the corresponding views. Thus, for the moment, pay attention to the following line of code: $this->load->library('validation'); As with other examples developed earlier, this expression is used to include the validation class, which naturally is utilized to check whether or not the fields of the sample web form have been filled with data. This process can be more clearly understood if you examine the code snippet below:

// set validation rules $rules['firstname']="required"; $rules['lastname']="required"; $rules['email']="required"; $this->validation->set_rules($rules);

In this concrete situation, the set of checking rules assigned to the validation class are pretty simple actually, since theyll only verify if the text boxes of the web form arent empty. Thats all. However, its perfectly possible to specify more strict validation rules, but this topic will be covered in detail in upcoming articles of the series. Once the controller determines if the web form has been submitted correctly (or not), itll redisplay the form, including an error message, or itll show a success web page, depending on the result of this validation process. I told you that validating online forms with Code Igniter was really easy! And before I forget, please save this file to the Code Igniter /system/application/controllers/ folder as validator.php. Now that you have hopefully grasped how the previous Validator class works, its time to see how to create the view file that redisplays the web form when it contains one or more empty fields. To see how this file will be built, please jump ahead and read the following section. Validating Web Forms with the Code Igniter PHP Framework - Displaying error messages when validating an online form (Page 3 of 4 ) In the previous section, you learned how to use a controller class to determine what course of action to take, either when the form in question has been submitted correctly, or when it fails to pass the validation process. Now Im going to show you how to create the view file that displays the pertinent online form, and incidentally, it also shows an error message as a result of the data checking process. That being explained, please examine the code below to see how this error view file looks. <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Entering user data</title> <head> <body> <h1>Entering user data</h1> <?php echo $this->validation->error_string;?> <?php echo form_open('validator');?> <p>First Name <input type="text" name="firstname" value="" size="50" /></p> <p>Last Name <input type="text" name="lastname" value="" size="50" /></p> <p>Email <input type="text" name="email" value="" size="50" /></p> <p><input type="submit" value="Send Data" /></p> </form> </body> </html> As shown above, the previous view file is quite simple to follow. As you can see, its comprised of a basic online form that contains three text boxes for collecting the users first and last names, and the corresponding email address. However, you should notice two important things regarding the way that the above contact form is created. First, a PHP statement has been included at the beginning of it. As you may guess, this is the error message that will be generated by the Code Igniter validation class when the web form fails to pass the validation process.

Finally, the view file uses the form helper function loaded previously by the controller to create a <form> opening tag that points exactly to the controllers location. Naturally, its possible to build this tag manually, but using the helper makes sure that the correct URL will always be assigned to the action attribute of the online form. So far. So good. At this stage, I taught you how to build a simple view file for showing a basic error message when validating a specific web form. In addition, the view will redisplay the form in question if any of its fields has been left empty, so users can repopulate the offending fields with the correct data and resubmit it. So, now that you hopefully learned how the previous view file does its thing, save it to the Code Igniter /system/application/views/ folder, and move on to see how to create the view that displays a primitive successful web page when the pertinent web form is submitted correctly. To learn the full details for how this brand new view file will be built, please jump ahead to read the next section. Validating Web Forms with the Code Igniter PHP Framework - Building a confirmation view file (Page 4 of 4 ) Building a successful web page that shows a confirmation message to the user when the previous contact web form has been submitted correctly is an extremely simple process. You'll surely grasp it in a snap. Below I listed the complete signature for this successful view, so you can see clearly how it works. Here it is: <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>User data submitted successfully!</title> </head> <body> <h1>User data submitted successfully!</h1> <p><?php echo anchor('validator','Go and submit the form again');?></p> </form> </body> </html> That was really simple to code and read, wasnt it? In this particular case, the above view file will display a typical confirmation message once the pertaining web form has been submitted correctly. Of course, the only detail to stress here is the use of the URL helper function loaded previously by the corresponding controller, which dynamically generates an anchor tag that points to the controllers location, in case a user wants to submit the online form again. Finally, save this new view file to the Code Igniter /system/application/views/ folder, as you did with in the example developed in the previous section, and test the application by typing into your browsers address field the following URL: http://localhost/codeigniter/index.php/validator/ Youll be amazed at how sweetly the previous example works!

At this point I explained how to build a basic web application that uses the validation class bundled with Code Igniter to check whether or not the fields of a sample web form have been filled. Indeed, you shouldnt have major problems understanding how this application works, but naturally you can fill some gaps on this topic by examining all of the code samples included in this tutorial. Final thoughts In this fourth episode of the series, you hopefully learned how to employ the validation class that comes included with Code Igniter to perform a basic validation on a simple online contact form. In the forthcoming article, Im going to show you how to perform strict validation on the data entered into a sample web form. So, now that youve been warned of the topics that will be discussed in the next tutorial, you dont have any excuses to miss it! Performing Strict Validation with the Code Igniter PHP Framework (Page 1 of 4 ) Introduction Code reusability is a well-known and powerful concept that provides PHP programmers with the capacity for developing complex web applications without having to reinvent the wheel. Naturally, in the area dominated by third-party frameworks this concept is really king, since the main goal of a development framework is to accelerate the creation of PHP programs through a set of classes and functions that can be reused any number of times. Of course, when it comes to picking a particular PHP framework for rapid application development, theres plenty of options available, and naturally each of them has its own pros and cons. However, before you start scratching your head over which package to choose, you should take a look at Code Igniter (http://codeigniter.com), a piece a software written in PHP 4 that lets you build full-blown PHP applications by using the Model-View-Controller pattern, and best of all, by means of a friendly programming interface. And speaking of friendly things, youll possibly recall that in the previous installment of the series, I explained how to use Code Igniters validation class to perform a basic checking process on a simple web form. Essentially, the entire validation procedure was reduced to creating a controller class capable of verifying if each field of the form in question was left empty or not. Thats all. In addition, based on the result of this process, the controller would either display a simple confirmation web page, or in the worst case, it would redisplay the sample web form, along with an error message indicating which fields should be populated correctly. But, as I mentioned before, the checking process performed on this online form was pretty simplistic. In this fifth chapter of the series, Im going to demonstrate how to use Code Igniters validation class to validate the data collected through a typical HTML form much more strictly, something that can be very useful for filtering user-supplied information. Now, its time to jump forward and learn in a few easy steps how to perform strict validation on input data with Code Igniter. Lets get started! Performing Strict Validation with the Code Igniter PHP Framework - Performing strict validation on user-provided data with Code Igniter (Page 2 of 4 )

As I anticipated in the introduction, the validation class that comes included with Code Igniter permits us to apply severe checking rules for the data entered into a specific online form. However, as with each application developed with this framework, its necessary to build a controller class that actually performs this validation process. Then, if the form fails to pass the checking procedure, the controller will redisplay it, along with a descriptive error message. Otherwise, a confirmation web page will be shown instead. Fairly easy to follow, right? Now that you have grasped the logic that will be implemented by the pertinent controller class, let me show you how it looks. Here it is:

class Validator extends Controller { function Validator(){ // load controller parent parent::Controller(); // load 'url' helper $this->load->helper('url'); // load 'form' helper $this->load->helper('form'); // load 'validation' class $this->load->library('validation'); } function index(){ // set validation rules $rules['firstname']="required|min_length[6]|max_length[15]"; $rules['lastname']="required|min_length[6]|max_length[15]"; $rules['email']="required|valid_email"; $this->validation->set_rules($rules); // set values for repopulating fields $fields['firstname']='First Name'; $fields['lastname']= 'Last Name'; $fields['email']='Email Address'; $this->validation->set_fields($fields); // check if user form has been submitted properly if ($this->validation->run()==FALSE){ // redisplay user form and repopulate fields $this->load->view('webform_view'); } // display success web page else{ $this->load->view('success_view'); } } }

Regardless of its short signature, the above Validator controller class does many useful things that need to be explained in more detail. First, the constructor loads the corresponding validation class, and the url and form helpers that you learned about in previous tutorials. As you can see, understanding how this process is achieved is pretty simple. But the most interesting things happen when the index() method is called. As shown before, it first sets specifically the validation rules that will be applied to each field of the sample web form, via its set_rules() method, and additionally, specifies the group of values that will be used to repopulate the HTML form, if its submitted incorrectly.

Finally, using the previously defined validation rules, the web form is properly checked, and in accordance with the result of this operation, the controller either will redisplay the online form with its fields repopulated, or itll simply show a confirmation web page. At this point, are you starting to realize how easy it is to perform strict validation on a selected web form by using Code Igniter? I guess you are! However, if youre anything like me, then Im sure youll want to see how each of the respective views are created, right? So, save the previous controller class to the /system/application/controllers/ folder as validator.php. In this way you can test it with your own web server. Assuming that youve already done this, click on the link that appears below and keep reading. Performing Strict Validation with the Code Igniter PHP Framework - Repopulating a web form with Code Igniter (Page 3 of 4 ) To be frank, creating the view file responsible for displaying all the errors that might occur when validating the sample web form, and for repopulating its fields when applicable, is a straightforward process that youll grasp very quickly. However, to clarify how this view is going to work, please examine its corresponding signature, which is shown below:

<!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Entering user data</title> <head> <body> <h1>Entering user data</h1> <?php echo $this->validation->error_string;?> <?php echo form_open('validator');?> <p>First Name <input type="text" name="firstname" value="<?php echo $this>validation->firstname;?>" size="50" /></p> <p>Last Name <input type="text" name="lastname" value="<?php echo $this>validation->lastname;?>" size="50" /></p> <p>Email <input type="text" name="email" value="<?php echo $this->validation>email;?>" size="50" /></p> <p><input type="submit" value="Send Data" /></p> </form> </body> </html>

Definitely, that wasnt rocket science, was it? As shown before, the above view file is responsible for displaying a simple contact form, which not surprisingly is composed of three text boxes, which come in handy for entering typical data, such as the users first and last names, and an email address as well. Nevertheless, if you have a closer look at the view file in question, then youll see that on top of it, the Code Igniter validation class is used to display all of the errors that might arise when validating the web form. Other than that, there are a few additional PHP statements

interspersed with the structural markup, which are used to repopulate the forms fields and to generate dynamically the URL for its action attribute. Now you have learned how to build a simple view file that not only will be capable of displaying on screen all of the error messages that occurred when validating the sample HTML form, but will refill its fields with the data entered previously by a user. Therefore, save this file to the Code Igniter /system/application/views/folder as webform_view.php and once youve done this, please jump forward and read the following section. In that part, Ill explain how to build the remaining view file, which will be responsible for showing a confirmation message, after the web form has been submitted successfully. Performing Strict Validation with the Code Igniter PHP Framework - Completing the form validation application (Page 4 of 4 ) In the prior section, I demonstrated how simple it is to check data entered into a sample online form by means of the validation class that comes with Code Igniter. As you saw earlier, its perfectly possible to repopulate its fields, too, by adding only a few lines of PHP code. Nonetheless, to finish developing this HTML form validation application, its necessary to generate yet another view file. This file will be tasked with displaying on the browser a simple confirmation message once the pertinent form has been submitted successfully. So, with this in mind, below I included the definition of this brand new file:

<!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>User data submitted successfully!</title> </head> <body> <h1>User data submitted successfully!</h1> <p><?php echo anchor('validator','Go and submit the form again');?></p> </form> </body> </html>

Did you ever think that creating a confirmation view like the one shown above was pretty difficult? Well, fortunately you were wrong! As you can see, the previous view simply will print on screen a typical message indicating the HTML form has been submitted successfully, as youve done probably hundreds of times before. In addition, its worthwhile to notice how the url helper function provided by Code Igniter is utilized in this specific case, to include a link that points back to the controller. Of course, this could have been done manually, but I left this task to be accomplished by this helper. Now that you have grasped how the previous view file does its business, save it to the Code Igniter /system/application/views/ folder as success_view.php and finally type the following URL into your browsers address field to test this sample web application:

http://localhost/codeigniter/index.php/validator/

Here you have it. At this moment, youre armed with the required background to start developing your own data checking applications with Code Igniter. Try setting other rules for the validation class, and see what happens in each case. Final thoughts In this fifth chapter of the series, I explained how to use the validation class that comes bundled with Code Igniter to validate more strictly the data entered into a sample web form. As you saw before, thanks to the functionality provided by this class, the whole process was fairly simple to follow. In the next part, Ill show you how to work with Code Igniters active record class. In this way you can learn how to select, insert, update and delete database rows without having to get your hands dirty writing SQL statements. Dont miss the next article! Page 1 of 4 ) Naturally, if youve already read all the tutorials that precede this one, then you're probably familiar with utilizing some core classes that come bundled with Code Igniter. This framework can be used to perform all sorts of clever tasks, including the validation of HTML forms, working with MySQL, paging database records, and so forth. Indeed, this PHP 4-based framework allows you to develop a wide range of programs, by using the model imposed by the Model-View-Controller pattern. This pattern makes it extremely convenient to separate application logic from visual presentation. And now that I mentioned the MVC approach, surely youll recall that in the previous article of this series, I explained how to apply this design pattern to developing a web application whose main goal was validating the data entered into a sample online form. As with any other web program developed with Code Igniter, this data validation application was composed of two primary modules. The first one was a controller class, which implemented all the logic required for checking the validity of the data entered on the mentioned HTML form. The second module was comprised of two view files, which were used either to redisplay the form in question along with a bunch of error messages, or to print on screen a simple confirmation message, depending on the result of the validation process. Does all of this ring any bells for you? I bet it does! Besides, as I mentioned earlier, Code Igniter comes equipped with a handy active record class that permits you to select, insert, update and delete database rows without having to explicitly code any SQL statements. Therefore, in the next few lines Ill be creating some hands-on examples for you, aimed at demonstrating how to use this class to manipulate a few basic records stored on a MySQL table.

Are you ready to learn how to use the active record pattern within the Code Igniters context? Then lets begin now! Working with the Active Record Class in Code Igniter - Pulling database records with Code Igniters active record class (Page 2 of 4 ) A good place to start showing you how to use the active record class that comes bundled with Code Igniter to manipulate MySQL rows, is with creating a sample table for testing purposes. In this case, Im going to use the same users table that I used in previous tutorials, whose structure looks like this:

As youll certainly recall, the above MySQL table was populated with data about some fictional users (well, some are real, actually), so it is pretty useful for demonstrating how to handle its records via the active record pattern. Therefore, Im going to set up a basic example that fetches all of the rows from the previous table, by using first a model class, then the corresponding controller, and finally a view file. That being explained, heres the short signature of the model in question:

class Users extends Model{ function Users(){ // call the Model constructor parent::Model(); // load database class and connect to MySQL $this->load->database(); } // get all users function getUsers(){ $query=$this->db->get('users'); if($query->num_rows()>0){ // return result set as an associative array return $query->result_array(); }

} // get total number of users function getNumUsers(){ return $this->db->count_all('users'); } }

As you can see, the constructor of the above Users model first loads the database class, which will be used to fetch all of the records contained into the users table. However, you should pay close attention to the way that its getUsers() and getNumUsers() methods have been implemented. In this specific case, getUsers() behaves simply as a wrapper for the get() method that belongs to Code Igniters database class, which as its name implies, comes in handy for retrieving all of the rows from a selected table without having to specify explicitly any SELECT statement. Finally, the getNumUsers() method will return the total number of rows contained in a selected table to client code. Its that simple, really. Having studied in depth the structure of the Users model class, do you realize how easy it is to use the active record pattern to pull out a few database records from a MySQL table? I guess you do! So, now that you have grasped how the previous model does its thing, you should save it to the /system/application/models/ folder as users.php. Okay, its time to create the corresponding controller class, which naturally will use the models methods to extract the records of the users MySQL table. Heres how this brand new class looks: class Users extends Controller{ function Users(){ // load controller parent parent::Controller(); // load 'Users' model $this->load->model('Users'); } function index(){ $data['users']=$this->Users->getAllUsers(); $data['numusers']=$this->Users->getNumUsers(); $data['title']='Displaying user data'; $data['header']='User List'; // load 'users_view' view $this->load->view('users_view',$data); } }

At this moment, undoubtedly things are getting more interesting, since the above controller class performs two crucial tasks, in the following order: first, it loads the model class, and then implements the index() methods in such a way that it permits it to use its methods to fetch all of the rows of the previous users MySQL table. Second, this data is embedded directly into a view file called users_view.php for display purposes.

Definitely, the major advantage in using the active record approach is that it wasnt necessary to get our hands dirty coding SQL statements. Pretty good, right? Oops, before I forget, you should save the controller class to the Code Igniter /system/application/controllers/ folder as users.php. In this way it can be called by typing the following URL into the browsers address field: http://localhost/codeigniter/index.php/users/ However, before you do that, its necessary to create the view file that displays user-related data on screen. Thus, heres the definition of this simple file: <html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $header;?></h1> <ul> <?php foreach($users as $user):?> <li> <p><?php echo 'Full Name: '.$user['firstname'].' '.$user['lastname'].' Email: '.$user['email'];?></p> </li> <?php endforeach;?> </ul> <p><?php echo 'Total number of users :'.$numusers;?></p> </body> </html>

Definitely, the above view is pretty easy to grasp, so in this case Im not going to spend a long time explaining how it functions. In simple terms, it displays the data on the users stored in the sample MySQL table, along with the total number of rows. Below I included the output generated by the previous view file. Here it is:

User List

Full Name: Alejandro Gervasio Email: alejandro@domain.com

Full Name: John Doe Email: john@domain.com

Full Name: Susan Norton Email: susan@domain.com

Full Name: Marian Wilson Email: marian@domain.com

Full Name: Mary Smith Email: mary@domain.com

Full Name: Amanda Bears Email: amanda@domain.com

Full Name: Jodie Foster Email: jodie@domain.com

Full Name: Laura Linney Email: laura@domain.com

Full Name: Alice Dern Email: alice@domain.com

Full Name: Jennifer Aniston Email: jennifer@domain.com

Total number of users :10

In addition, you should save this view file to the /system/application/views/ folder, so it can be found directly by the controller. So far, so good. At this point, you have learned how to use the active record pattern with Code Igniter to fetch a few database rows from a MySQL table. As you saw for yourself, accomplishing this task didnt require coding any SQL SELECT statements, since the whole operation was handled behind the scenes by the corresponding database class. In the upcoming section, Ill be coding for you a brand new hands-on example, aimed at illustrating how to perform conditional SELECT queries by means of Code Igniters active record pattern class. Want to see how this will be done? Then click on the below link and read the next few lines. Working with the Active Record Class in Code Igniter - Performing conditional SELECT queries with the active record pattern (Page 3 of 4 ) True to form, executing conditional SELECT queries by means of Code Igniters database class is a straightforward process that only requires using its intuitive where() method. As its

name suggests, it can be used to run queries containing certain conditions, as youd normally do when using a WHERE clause. To demonstrate how the aforementioned method can be utilized within the context of a concrete example, again Im going to use the sample users MySQL table that was created in the previous section. Based on its structure, below I redefined the corresponding model, so now it looks like this: class Users extends Model{ function Users(){ // call the Model constructor parent::Model(); // load database class and connect to MySQL $this->load->database(); } function getAllUsers(){ $query=$this->db->get('users'); if($query->num_rows()>0){ // return result set as an associative array return $query->result_array(); } } function getUsersWhere($field,$param){ $this->db->where($field,$param); $query=$this->db->get('users'); // return result set as an associative array return $query->result_array(); } // get total number of users function getNumUsers(){ return $this->db->count_all('users'); } }

As shown above, the Users model looks nearly identical to its previous incarnation. There is a brand new method, however, called getUsersWhere(), which allows us to fetch database rows that match a certain condition. Of course, its clear to see that this specific method hides a WHERE SQL clause behind its signature, but fortunately you dont have to code it explicitly. Now that you have seen how the above model class was built, please save it to Code Igniters /system/application/models/ folder as users.php. Done? Then its time to define a new controller class, which will be tasked with fetching all the users whose IDs are lesser than 5. The signature of the controller class that performs this task is as following:

class Users extends Controller{ function Users(){ // load controller parent parent::Controller(); // load 'Users' model $this->load->model('Users'); } function index(){

$data['users']=$this->Users->getUsersWhere('id <',5); $data['numusers']=$this->Users->getNumUsers(); $data['title']='Displaying user data'; $data['header']='User List'; // load 'users_view' view $this->load->view('users_view',$data); } }

That was quite simple to code and read, wasnt it? As you can see above, the Users controller will extract from the sample users MySQL table all the rows with an ID less than 5. This conditional SQL statement is executed by way of the following expression: $data['users']=$this->Users->getUsersWhere('id <',5); Now that I have shown you how the controller works, its time to save it to the /system/application/controllers/ folder as users.php and proceed to create the pertinent view file, which actually looks as simple as this: <html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $header;?></h1> <ul> <?php foreach($users as $user):?> <li> <p><?php echo 'Full Name: '.$user['firstname'].' '.$user['lastname'].' Email: '.$user['email'];?></p> </li> <?php endforeach;?> </ul> <p><?php echo 'Total number of users :'.$numusers;?></p> </body> </html> Having now defined the above view file, and assuming thats been saved to the /system/application/views/ folder, you can test this MySQL-driven application by pointing your browser to the following URL: http://localhost/codeigniter/index.php/users/ If everything have been set up correctly, you should get an output similar to this: Full Name: Alejandro Gervasio Email: alejandro@domain.com Full Name: John Doe Email: john@domain.com Full Name: Susan Norton Email: susan@domain.com Full Name: Marian Wilson Email: marian@domain.com

Total number of users :10 Well, at this point you have hopefully grasped how to perform a simple conditional SQL statement by using the database class that comes included with Code Igniter. Therefore, the last thing that Im going to teach you in this tutorial will be how to extract rows from the same users MySQL table whose IDs are greater than 2, in this manner completing this introduction to using the active record pattern to execute WHERE SQL clauses. This topic will be discussed in detail in the section to come, so click on the link below and keep reading. Ill be there, waiting for you. Working with the Active Record Class in Code Igniter - Selecting database rows that match a given condition (Page 4 of 4 ) As you might have guessed, using Code Igniters database class for extracting from the users table only the database rows whose ID values are greater than 2 is a process very similar to the example developed in the previous section. Of course, in this case Im going to use the same model class. That being said, here is its signature: class Users extends Model{ function Users(){ // call the Model constructor parent::Model(); // load database class and connect to MySQL $this->load->database(); } function getAllUsers(){ $query=$this->db->get('users'); if($query->num_rows()>0){ // return result set as an associative array return $query->result_array(); } } function getUsersWhere($field,$param){ $this->db->where($field,$param); $query=$this->db->get('users'); // return result set as an associative array return $query->result_array(); } // get total number of users function getNumUsers(){ return $this->db->count_all('users'); } }

Obviously, the signature of the above model remains the same, because the class thats actually responsible for performing the conditional SQL statement discussed before is the controller, right? Therefore, keeping in mind this concept, below I created such a class, which looks like this: class Users extends Controller{ function Users(){ // load controller parent

parent::Controller(); // load 'Users' model $this->load->model('Users'); } function index(){ $data['users']=$this->Users->getUsersWhere('id >',2); $data['numusers']=$this->Users->getNumUsers(); $data['title']='Displaying user data'; $data['header']='User List'; // load 'users_view' view $this->load->view('users_view',$data); } }

As illustrated above, the previous User controller class has been provided with the ability to fetch, from the pertinent users MySQL table, all of the rows whose IDs are greater than 2. Naturally, performing a conditional SQL clause like this one is pretty trivial, but it demonstrates in a nutshell how to use the active record pattern with Code Igniter. Finally, theres one step that still remains undone. It consists merely of defining the view file that will display the values of these table rows on the browser. Here it is: <html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $header;?></h1> <ul> <?php foreach($users as $user):?> <li> <p><?php echo 'Full Name: '.$user['firstname'].' '.$user['lastname'].' Email: '.$user['email'];?></p> </li> <?php endforeach;?> </ul> <p><?php echo 'Total number of users :'.$numusers;?></p> </body> </html> Well, having created the above view file, and assuming that the model and the controller has been saved to their respective folders, if you test this sample application with your own web server, you should get the following output: Full Name: Alejandro Gervasio Email: alejandro@domain.com Full Name: John Doe Email: john@domain.com Full Name: Susan Norton Email: susan@domain.com Full Name: Marian Wilson Email: marian@domain.com Total number of users :10 Definitely, this isnt rocket science! Yet this practical example should give you a clear idea of how to execute conditionals SQL statements using the active record pattern. Besides, its

worthwhile to clarify that Code Igniters database class comes equipped with many other methods that permit us to perform queries without having to write SQL statements. However, if you wish to examine a full reference of them, the best place to go is its official web site. Final thoughts In this sixth episode of the series, I provided you with a quick overview on selecting database records through the active record pattern. Undeniably, Code Igniter makes this process easy, meaning that you shouldnt have major problems practicing the relevant techniques. In the upcoming article, Im going to finish explaining how to apply the active record pattern with Code Igniter, this time by discussing how to insert, update and delete database rows. Therefore, now that youre aware of the topics that will be covered in the next part, you wont want to miss it! Inserting, Updating and Deleting Database Rows with Code Igniter (Page 1 of 4 ) Introduction Admittedly, using a third-party PHP framework for building web applications rapidly confronts a PHP programmer with several challenging tasks, such as installing its source files and folders in the testing web server, probably editing and configuring a bunch of initialization parameters, and dealing with its learning curve. Although in certain cases, all of these tasks can be accomplished in a relatively painless way, the truth is that there are several PHP frameworks available nowadays on the web that are pretty difficult to set up, and certainly come packaged with many features that can be quite overwhelming, particularly for inexperienced developers. Fortunately, this isnt the case with Code Igniter (http://codeigniter.com), a compact and powerful PHP framework developed in PHP 4 that permits you to create full-featured web applications very quickly. Among other things, it features a friendly learning curve. And now that I mentioned the term friendly, you may recall that during the preceding article of this series, I demonstrated how easy it is to perform conditional SELECT statements against a selected table with the Code Igniters database class. Indeed, this class not only allows you to run queries using a traditional approach; it also allows you to select, insert, update and delete database records by means of the active record pattern, which lets you avoid coding SQL clauses explicitly. In the aforementioned article I developed a couple of hands-on examples aimed at demonstrating how to select a few database rows via the active record approach. However, as I said before, Code Igniter lets you perform inserts, updates, and deletion operations using this design pattern as well. Therefore, in the next few lines Ill be discussing these interesting topics, as always, by means of several code samples. So, are you ready to learn how to insert, update and delete database records with Code Igniter? Then dont waste more time in preliminaries. Start reading now! Inserting, Updating and Deleting Database Rows with Code Igniter - Performing conditional SELECT statements with Code Igniter (Page 2 of 4 )

Actually, before I proceed to demonstrate how to perform inserts, updates and deletions with the active record pattern, Id like to reintroduce a pair of practical examples developed in the previous tutorial. They showed how to run conditional SELECT statements via this pattern. Each of these examples was comprised naturally of three source files: a model, a controller class, and finally a view file. All of them worked with a sample users MySQL table, whose structure was similar to the following:

Okay, now that you remember how the table looked, heres the complete source code corresponding to the first example. It fetches all of the users whose IDs are less than 5. Take a look at it, please: (definition for users.php file - located at /system/application/models/ folder) class Users extends Model{ function Users(){ // call the Model constructor parent::Model(); // load database class and connect to MySQL $this->load->database(); } function getAllUsers(){ $query=$this->db->get('users'); if($query->num_rows()>0){ // return result set as an associative array return $query->result_array(); } } function getUsersWhere($field,$param){ $this->db->where($field,$param); $query=$this->db->get('users'); // return result set as an associative array return $query->result_array(); } // get total number of users function getNumUsers(){ return $this->db->count_all('users'); } }

(definition for users.php file - located at /system/application/controllers/ folder) class Users extends Controller{ function Users(){ // load controller parent parent::Controller(); // load 'Users' model $this->load->model('Users'); } function index(){ $data['users']=$this->Users->getUsersWhere('id <',5); $data['numusers']=$this->Users->getNumUsers(); $data['title']='Displaying user data'; $data['header']='User List'; // load 'users_view' view $this->load->view('users_view',$data); } }

(definition for users_view.php file - located at /system/application/views/ folder) <html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $header;?></h1> <ul> <?php foreach($users as $user):?> <li> <p><?php echo 'Full Name: '.$user['firstname'].' '.$user['lastname'].' Email: '.$user['email'];?></p> </li> <?php endforeach;?> </ul> <p><?php echo 'Total number of users :'.$numusers;?></p> </body> </html> As you can see, the three source files listed above are the building blocks of a basic MySQLdriven application. Its goal is to retrieve all of the rows included in the previous users table whose ID values are less than 5. Obviously, this is only a primitive example, but it shows how to use the active record pattern to perform conditional SELECT statements with Code Igniter. In a similar fashion, the following sample application fetches all the users whose IDs are greater than 2. Here are its corresponding source files. (definition for users.php file - located at /system/application/models/ folder)

class Users extends Model{ function Users(){ // call the Model constructor parent::Model(); // load database class and connect to MySQL $this->load->database(); } function getAllUsers(){ $query=$this->db->get('users'); if($query->num_rows()>0){ // return result set as an associative array return $query->result_array(); } } function getUsersWhere($field,$param){ $this->db->where($field,$param); $query=$this->db->get('users'); // return result set as an associative array return $query->result_array(); } // get total number of users function getNumUsers(){ return $this->db->count_all('users'); } }

(definition for users.php file - located at /system/application/controllers/ folder) class Users extends Controller{ function Users(){ // load controller parent parent::Controller(); // load 'Users' model $this->load->model('Users'); } function index(){ $data['users']=$this->Users->getUsersWhere('id >',2); $data['numusers']=$this->Users->getNumUsers(); $data['title']='Displaying user data'; $data['header']='User List'; // load 'users_view' view $this->load->view('users_view',$data); } }

(definition for users_view.php file - located at /system/application/views/ folder) <html> <head> <title><?php echo $title;?></title>

</head> <body> <h1><?php echo $header;?></h1> <ul> <?php foreach($users as $user):?> <li> <p><?php echo 'Full Name: '.$user['firstname'].' '.$user['lastname'].' Email: '.$user['email'];?></p> </li> <?php endforeach;?> </ul> <p><?php echo 'Total number of users :'.$numusers;?></p> </body> </html> Having listed the full source code for the two previous web applications, I should assume that running conditional SQL queries using the active record pattern is now a familiar topic to you, right? Thus, its time to learn how to use this pattern to perform inserts, updates and deletions against a selected database table002E As you may guess, this subject will be covered in depth in the following section. Please read the next few lines. Inserting, Updating and Deleting Database Rows with Code Igniter - Inserting new rows into a selected MySQL table (Page 3 of 4 ) In order to demonstrate how to insert a new row into the previous users MySQL table via the active record pattern, Im going to work with only a controller class. Eventually, I could define a couple of additional views for displaying either an error message or a confirmation web page, depending on the result of the insert operation. However, this will be left momentarily as homework for you, in case you feel bored and want to have some fun coding PHP classes. So, returning to the topic, the simplest way to insert a new record into a selected table is by using a method of the database class, not surprisingly called insert(). The prototype for using this brand new method can be seen in the code sample below. class Users extends Controller{ function Users(){ // load controller parent parent::Controller(); // load database class and connect to MySQL $this->load->database(); } // insert new row into 'users' MySQL table function index(){ $data=array('firstname'=>'Jane','lastname'=>'Smith','email'=> 'jane@domain.com'); $this->db->insert('users',$data); } } As shown before, the insert() method is so intuitive that it practically doesnt require any additional explanations. Anyway, you can see above that I built a simple controller class, which utilizes this method, to add a new fictional user to a sample MySQL table.

The data to be inserted is passed to the method in the form of an associative array, along with the name of the table that will be updated. In addition, its worth mentioning that its possible to utilize an object instead of an array, but for a detailed explanation of how to accomplish this, please check the Code Igniters user manual. So far, you have learned how to employ the insert() method that belongs to Code Igniters database class to add a new record to a selected table. Its feasible to achieve the same results by using another method called set(). A typical usage of this method is illustrated below. class Users extends Controller{ function Users(){ // load controller parent parent::Controller(); // load database class and connect to MySQL $this->load->database(); } // insert new row into 'users' MySQL table using the 'set()' method function index(){ $this->db->set('firstname','Jane'); $this->db->set('lastname','Smith'); $this->db->set('email','jane@domain.com'); $this->db->insert('users',$data); } } As you can see, inserting new database rows with the set() method requires a few extra lines of code, but you may find it a bit more intuitive than its counterpart, insert(). Anyway, both of them are valid, so you should choose the one that best suits your needs. At this point, I've shown you how to perform database insertions very easily with the active record pattern. The last thing Im going to show you in this article will be how to update and delete records from a MySQL table by using the pattern in question. To learn the complete details of how to perform these database operations with Code Igniter, please read the upcoming section. Were almost done! Inserting, Updating and Deleting Database Rows with Code Igniter - Updating and deleting database records using the active record pattern (Page 4 of 4 ) True to form, updating and deleting database rows with the active record pattern is only a matter of using a couple of intuitive methods, called update() and delete() respectively. They can be included in a simple controller class, as I did before when explaining how to perform database insertions. To dissipate any possible doubts about how to use these method, I coded two controllers. The first one updates an existing row of a sample MySQL table, and the second one deletes a specified record. Here are the respective controllers, so you can examine them in detail: class Users extends Controller{ function Users(){ // load controller parent parent::Controller();

// load database class and connect to MySQL $this->load->database(); } // update row of 'users' MySQL table function index(){ $data=array('firstname'=>'Jane','lastname'=>'Smith','email'=> 'jane@domain.com'); $this->db->where('id','3'); $this->db->update('users',$data); } } class Users extends Controller{ function Users(){ // load controller parent parent::Controller(); // load database class and connect to MySQL $this->load->database(); } // delete row from 'users' MySQL table function index(){ $this->db->where('id',2); $this->db->delete('users'); } } Undoubtedly, after studying the signature of the above controllers, youll have to agree with me that updating and deleting database rows with Code Igniter is an extremely simple process! In the first case, the controller uses the update() method to update a specific row in the sample MySQL table, while the second class simply deletes an existing record. And with this final example, Im finishing this brief introduction to inserting, updating and deleting database rows with Code Igniter. Dont forget to consult its user manual for a more detailed explanation of each of the methods covered in this tutorial. Final thoughts In this seventh part of the series, I provided you with a bunch of examples aimed at demonstrating how to perform insertions, updates and deletions on a selected MySQL table by using Code Igniters database class. As you saw before, all of these tasks are very intuitive and easy to grasp too. In the forthcoming chapter, Ill be taking a look at the email class of this handy PHP framework, so you can learn how to use this class within the context of the MVC pattern. Dont miss the next part! Working with the Email Class in Code Igniter (Page 1 of 4 ) Introduction Welcome to the eighth part of the series titled Introducing the Code Igniter PHP Framework. Comprised of nine comprehensive tutorials, this group of articles walks you through learning the main features that come packaged with this PHP-4 based software, and also teaches you how to develop diverse web applications by using the Model-View-Controller approach. Now that you've been introduced to the main subject of the series, its time to recapitulate very quickly the topics discussed in the last article. As youll possibly remember, in that article

I explained how to use the database class that comes bundled with Code Igniter to perform database insertions, updates and deletions via the active record pattern. In that particular case, all these database-related operations were accomplished without having to code explicitly any SQL statements, which makes web applications more compact and maintainable. However, Code Igniter comes equipped with so many other useful features, that covering all of them by a few articles is practically impossible. Even so, in this eight chapter of the series, Ill be providing you with a quick overview on working with its email class, in this manner you can start using it when developing your own PHP applications. Now, its time to continue this educational journey and learn how to send email with Code Igniter. Lets jump in! Working with the Email Class in Code Igniter - Sending email with Code Igniter (Page 2 of 4 ) True to form, sending email through Code Igniter is a process reduced to feeding its email class with some typical parameters, such the emails sender, the messages subject, the corresponding text, and so forth. Of course, this has to be done by using the MVC pattern, therefore Im going to define a controller class that sends email in a truly simple fashion. The signature of this controller is listed below. Take a look at it, please: class Email extends Controller{ function Email(){ // load controller parent parent::Controller(); $this->load->library('email'); } function index(){ // set email class parameters $this->email->from('me@domain.com','Alejandro Gervasio'); $this->email->to('you@domain.com'); $this->email->cc('migirlfriend@domain.com'); $this->email->bcc('myothergirlfriend@domain.com'); $this->email->subject('Testing email class'); $this->email->message('How are you, buddy?'); $data['title']='Sending email...'; $data['header']='Sending email now...'; $data['message']=$this->email->send()?'Message was sent successfully!':'Error sending email!'; $this->load->view('email_view',$data); } } As you can see, the above Email controller class presents a structure similar to the examples developed in previous tutorials. First, its constructor loads the corresponding email class via a loader object, so it can be used at a later time. Then, the index() method sets a few conventional parameters, which are used to send the email message, and finally dispatches the message via the send() method. Also, you should notice that the controller uses a view to display an error message or a simple confirmation of whether or not the email has been successfully sent. That was really simple to follow, wasnt it?

Now that you have learned how to use Code Igniter to send email messages very easily, its time to see how to code the previous view file, which will print on screen an indicative message. To learn how this view file will be created, please click on the link that appears below and keep up reading. Working with the Email Class in Code Igniter - Defining a simple view file (Page 3 of 4 ) In the section that you just read, I showed you how to build a basic controller class, which was provided with the capacity to send email messages in a simple fashion. Nonetheless, we need to construct the important part of the program that indicates to the user whether or not the message has been successfully dispatched. To perform this task, Im going to create a primitive view file, whose signature will look as simple as this: <html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $header;?></h1> <p><?php echo $message;?></p> </body> </html> Undoubtedly, the structure of the view file shown above is extremely simplistic. As you can see, this view, aside from displaying the title along with a simple header, will show an additional message on screen which indicates that the email message has been successfully submitted, or in the worst case, that it failed to be dispatched. It would also be possible to create two different views, where each of them would be used by the previous controller to display en error string or a confirmation message. However, in this case I decided to code only one view file to keep the example rather simple to follow. So far, so good. At this point I've demonstrated how to use Code Igniter to develop a simple email application, whose structure has been built around the schema imposed by the MVC pattern. So, what comes next? In the following section Im going to explain how to take advantage once again of the email class that comes included with Code Igniter. In this case, we'll build a PHP program that sends email using the data entered in a simple HTML form. To learn how this sample email application will be developed, youll have to click on the link shown below and keep reading. Working with the Email Class in Code Igniter - Sending email messages via an HTML form (Page 4 of 4 ) Essentially, the PHP application that I plan to build now will perform really basic tasks, such as sending email by utilizing an HTML form. However, the most interesting facet in developing such a program is that Im going to combine the functionality of two classes of Code Igniter: the one that sends email, and another one that validates input data.

In addition, Im going to use the url and form helper functions that you learned in previous tutorials to dynamically generate certain links. So, having explained how this sample email application is going to work, its time to create its first building block, the controller class, whose signature is shown below: class Email extends Controller { function Email(){ // load controller parent parent::Controller(); // load 'url' helper $this->load->helper('url'); // load 'form' helper $this->load->helper('form'); // load 'validation' class $this->load->library('validation'); // load 'email' class $this->load->library('email'); } function index(){ // set validation rules $rules['firstname']="required|min_length[6]|max_length[15]"; $rules['lastname']="required|min_length[6]|max_length[15]"; $rules['email']="required|valid_email"; $this->validation->set_rules($rules); // set values to repopulate fields $fields['firstname']='First Name'; $fields['lastname']= 'Last Name'; $fields['email']='Email Address'; $this->validation->set_fields($fields); // check if user form has been submitted properly if ($this->validation->run()==FALSE){ // redisplay user form and repopulate fields $this->load->view('form_view'); } // display confirmation web page and send email else{ // set email class settings $this->email->from($_POST['email'],$_POST['firstname']. ' '.$_POST['lastname']); $this->email->to('you@domain.com'); $this->email->cc('migirlfriend@domain.com'); $this->email->bcc('myothergirlfriend@domain.com'); $this->email->subject($_POST['subject']); $this->email->message($_POST['message']); $data['title']='Sending email...'; $data['header']='Sending email now...'; $data['message']=$this->email->send()?'Message was sent successfully!':'Error sending email!'; $this->load->view('email_view.php',$data); } } }

Actually, I dont wan to be excessively optimistic, but in this case the logic implemented by the above Email controller is very easy to grasp. As you can see, its constructor begins loading all of the source classes and functions that will be required later on, and this naturally includes all of the classes and helpers that were mentioned previously. Now, focusing on the implementation of the index() method, its clear to see that it first sets the validation rules that will be applied to the data entered in the HTML form, then validates

this incoming information, and finally submits it via email, assuming that its been filled in correctly. Otherwise, the online form will be redisplayed, indicating which entries should be corrected. As youll possibly agree with me, understanding how the above controller class work isnt something that will make you scratch your head, is it? However, theres still one step that remains undone if we want to get this email application working as expected. Yes, you guessed right! In this case, its necessary to create the view file that informs users that the HTML form has been submitted successfully. We also need to code the online form that lets them enter their personal information. So, taking into account those last requirements, heres the signature of these simple view files: (definition of 'email_view.php' file) <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title><?php echo $title;?>title> </head> <body> <h1><?php echo $header;?></h1> <p><?php echo $message;?></p> <p><?php echo anchor('email','Go and submit the form again');?></p> </form> </body> </html>

(definition of 'form_view.php' file) <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Entering user data</title> <head> <body> <h1>Entering user data</h1> <?php echo $this->validation->error_string;?> <?php echo form_open('email');?> <p>First Name <input type="text" name="firstname" value="<?php echo $this>validation->firstname;?>" size="50" /></p> <p>Last Name <input type="text" name="lastname" value="<?php echo $this>validation->lastname;?>" size="50" /></p> <p>Email <input type="text" name="email" value="<?php echo $this->validation>email;?>" size="50" /></p> <p><input type="submit" value="Send Data" /></p> </form> </body> </html>

Here you have it. Assuming that the controller class and the respective view files have been saved to the correct destination folders, the previous email application now should work like a charm. Of course, as I explained in preceding articles, you can test it by typing into your browse the following URL:

http://localhost/codeigniter/index.php/email/

And with this last hands-on example, Im finishing this overview of building an email application with Code Igniter. As always, feel free to tweak the entirety of the code samples included in this article, so you can improve your skills in using this powerful PHP framework. Final thoughts In this eighth part of the series, I explained how to build a web application with Code Igniter that permits users to send email via a simple HTML form. Although this example may seem pretty simplistic, it hopefully will be useful enough to demonstrate how to combine several classes and helpers into one single program. The last article will be the fruit of the cake, since Ill be showing you how to use Code Igniter to develop a content management system that will permit you to insert, update and delete information about a collection of movies. Yes, this time were going to Hollywood, so dont miss the last article! Building a Content Management System with Code Igniter (Page 1 of 4 ) Introduction If youre a PHP programmer whos seeking a framework that lets you build full-blown web applications very rapidly, without having to deal with complex installation issues, then you might want to look at Code Igniter (http://codeigniter.com). It is a friendly software package developed in PHP 4 that permits you to create web-based programs by using the Model-ViewController pattern. Naturally, if you've read the articles that preceded this one, then you have the background necessary to start building object-based PHP applications with Code Igniter. This framework provides developers with the right tools for constructing anything that they can think of, ranging from simple data validation programs to powerful database-driven applications. Now that I've mentioned the remarkable capabilities offered by Code Igniter when it comes to rapid application development, you will no doubt remember that in the previous article I created a simple web-based program that could send email messages by utilizing a regular HTML form. Regardless of the intrinsic simplicity of this application, it provided a pretty useful demonstration of how easy it is to build such an application with the MVC approach. Basically,

this email program was comprised of only one controller class, and two view files as well. It really was that simple. However, until now I've only shown you how to perform certain specific tasks, such as validating user-supplied data and sending email, handling and paginating database records, and so forth. But, as you may guess, all of these isolated procedures can be used perfectly together to develop a larger, real-world application. Therefore, with this idea in mind, this last episode of the series will be focused on building a primitive content management system with Code Igniter. This particular CMS will come in handy for adding comments about a group of popular movies previously stored in a MySQL database table. Now we will start developing this movie-related management system. Hollywood, here we go! Building a Content Management System with Code Igniter - Creating sample MySQL tables and defining a model class (Page 2 of 4 ) We'll begin building this content management system with Code Igniter by creating a couple of basic MySQL tables. The first one will be used for storing information about a few movies, including the corresponding titles and a brief description, while the second table will be utilized for inserting comments about each of them. Based on this database schema, the PHP application that I plan to develop will let users enter several comments on a particular movie by means of an HTML form. Having clarified this point, Im going to create the first sample MySQL table, which will be called movies, with a structure that looks like this:

As you can see, the movies table contains data about a few relatively recent movies, and its very simple to grasp. However, there is still one more step to take. We need to create an additional table for entering comments on each of the previous movies. The empty structure of this second table, called comments, can be seen below:

Now that the two sample tables have been properly created, everything is ready for us to begin developing this movie-related content management system. Therefore, to interact with these tables, Im going to define a model class that permits us to achieve this goal in a simple manner. The signature of this model class is as follows:

class MovieModel extends Model{ function MovieModel(){ // call the Model constructor parent::Model(); // load database class and connect to MySQL $this->load->database(); } // fetch all rows function fetchAllRows($table){ $query=$this->db->get($table); if($query->num_rows()>0){ // return result set as an associative array return $query->result_array(); } } // fetch rows based on a certain condition function fetchRow($param,$field,$table){ $this->db->where($field,$param); $query=$this->db->get($table); // return result set as an associative array return $query->result_array(); } // insert row function insertRow($table,$data){ $this->db->insert($table,$data); } // get total number of rows function getNumRows($table){ return $this->db->count_all($table); } }

As illustrated above, the logic that drives the previous MovieModel class is fairly easy to understand. Basically, all that this class does is implement a group of methods for fetching and inserting rows into a selected MySQL table, as well as for returning the total number of records contained within a result set.

This model class should be saved to the Code Igniter /system/application/models/ folder as moviemodel.php for later use. Okay, assuming that youve read the previous articles of this series, then you should be pretty familiar with the structure of the above model class, right? Therefore, it is time to take the next step involved in the development of this content management system, which obviously consists of defining a controller. As youll see in a moment, the controller will be responsible for displaying all of the movies contained in the movies MySQL table that you saw before. It will also let users enter different comments on each of them, via a simple HTML form. To see how this brand new controller class will be created, please visit the following section and keep reading. Building a Content Management System with Code Igniter - Building a controller class (Page 3 of 4 ) True to form, building a controller class that fetches all the movies included in the previous movies MySQL table, and also allows users to enter comments about each of them, simply involves defining a different method for performing each of these tasks. However, you will gain a better understanding of the way that this controller class is going to work if you examine its signature, which has been included below. Take a look at it, please: class Movies extends Controller{ function Movie(){ // load controller parent parent::Controller(); // load 'MovieModel' model $this->load->model('MovieModel'); // load helpers $this->load->helper('url'); $this->load->helper('form'); } // display all movies function index(){ $data['title']='Movies List'; $data['movies']=$this->MovieModel->fetchAllRows('movies'); // load 'movie_view' view $this->load->view('movie_view',$data); } // display all comments function comments(){ $data['title']='Comment List'; $data['comments']=$this->MovieModel->fetchRow($this->uri>segment(3),'movie_id','movie_comments'); // load 'moviecomment_view' view $this->load->view('moviecomment_view',$data); } // insert comment function insert_comment(){ $this->MovieModel->insertRow('movie_comments',$_POST); redirect('movie/comments/'.$_POST['movie_id']); } }

Although the definition of the above Movie controller looks pretty intimidating at first, it's actually pretty simple to understand. First, its constructor loads all of the source classes and functions that will be used within the management system; this includes the corresponding model, as well as the url and form helpers that you learned in previous articles of this series. Now, take a look at the index() method. As youll recall, it will be called automatically by Code Igniter when implemented, and it is tasked with displaying on screen all of the movies included in the movies MySQL table defined before. As you can see, this method first fetches all of the movies from the aforementioned table by means of the model, and lastly it embeds this data into a view file called movie_view.php for displaying purposes. For right now, don't worry about how this view looks, since this topic will be discussed in depth in the following section. At this level, you hopefully grasped the logic implemented by the pertinent index() method, right? So focus your attention now on the one called comments(). As its name suggests, this method is responsible for fetching all of the comments that belong to a specific movie. This task is performed by means of a conditional WHERE SQL statement, which is logically hidden behind the models API. In addition, you should notice that this method retrieves the comments made on a particular movie by using a parameter passed in within the URL, whose value is returned by the following expression: $this->uri->segment(3)

Actually, Code Igniter will automatically load a class called uri with each controller defined, so in this case its segment() method is utilized to retrieve the ID of the movie that has received a comment. And finally, the insert_comment() method again uses the models API, this time for adding a new entry to the comments MySQL table created in the previous section. Of course, the text and author that correspond to each comment are collected via a post HTML form, therefore the following expressions: $this->MovieModel->insertRow('movie_comments',$_POST); redirect('movie/comments/'.$_POST['movie_id']);

first add the comment in question to the corresponding comments MySQL table, and then redirect users back to the comments web page. Now, before I forget, please save the controller class to the Code Igniter /system/application/controllers/ as movies.php folder for further use. So far, so good, right? At this point, you should have a clear idea of how the previous Movies controller class does its thing. Also, its possible that you still have some doubts regarding the way that movies and comments are displayed on the browser, or even how new comments are submitted by a user.

However, you shouldnt be too concerned about this. In the next section, Ill be listing all of the view files that are required to perform all the aforementioned tasks. Want to see how this will be done? Click on the link below and keep reading. Building a Content Management System with Code Igniter - Completing the CMS with view files (Page 4 of 4 ) To get this movie-related content management system completed, its necessary to create all of the view files that are used for the previous Movies controller class to display the list of available movies and their corresponding comments, as well as the HTML form that permits the insertion of these comments into the corresponding MySQL table. That being said, heres the definition of the first view file, called movie_view.php. It is utilized by the controller to display the list of movies available for receiving comments. Have a look at it, please:

<html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $title;?></h1> <?php foreach($movies as $movie):?> <h2><?php echo $movie['name'];?></h2> <p><?php echo $movie['description'];?></p> <p><?php echo anchor('movie/comments/'.$movie['id'],'View Comments');?></p> <hr /> <?php endforeach;?> </body> </html>

Definitely, the above view file is quite simple to grasp. As you can see, this file will display all of the movies stored in the database. It includes a link that will take users to the comments web page, so they can submit a new comment for each particular movie. Besides, you may want to look at the following screen help, which shows precisely how movies are displayed on screen:

That image was pretty illustrative, right? Now its time to include the view file that renders the comments web page, which not surprisingly is called moviecomment_view.php. Here it is:

<html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $title;?></h1> <?php foreach($comments as $comment):?> <p><?php echo $comment['author'];?></p> <p><?php echo $comment['text'];?></p> <p><?php echo anchor('movie','Back to movies');?></p> <hr /> <?php endforeach;?>

<?php echo form_open('movie/insert_comment');?> <?php echo form_hidden('movie_id',$this->uri->segment(3));?> <p>Enter your comments below:</p> <p><textarea name="text" rows="10"></textarea></p> <p>Author:</p> <p><input type="text" name="author" /></p> <p><input type="submit" value="Submit Comment" /></p> </form> </body> </html>

As you can see, the above view file performs a couple of crucial tasks, such as displaying all the comments that have been submitted for a specific movie, and providing a basic HTML form, which lets users add new entries. Of course, youll understand much more clearly how this view works, if you look at the following screen capture:

See how easy it is to provide users with an interface that lets them enter comments on a specific movie? I guess you do! Naturally, these two view files should be saved to the Code Igniter /system/application/views/ folders, so that they can be loaded at runtime by the previous controller class. Okay, at this point I have finished building this simple content management system with Code Igniter. If you want to test it, you should type the following URL in your browsers address field:

http://localhost/codeigniter/index.php/movies/

Thats all. If all of the source files created earlier were saved to the correct locations in the web server, then the application should work flawlessly! Finally, feel free to introduce your own modifications to the files, so you can extend your Code Igniter skills to developing database-driven applications. Final thoughts Sad but true, weve come to the end of this series. The journey has been long, but hopefully instructive too, since you learned how to use Code Igniter to develop several useful web applications very quickly. So, if youre looking for a PHP framework that requires minimal setup and an easy learning curve, then Code Igniter might be the piece of software that you really need. See you in the next PHP development tutorial!

Handling Views with CodeIgniter (Page 1 of 4 ) Introduction Any PHP developer who has spent a few weeks working with the CodeIgniter framework quickly discovers its many virtues. It has a relatively flat learning curve, and clear, thorough online documentation. Moreover, it lets users implement the Model-View-Controller design pattern in a fairly strict fashion, and its flexible structure allows the extension of its core functionality via custom libraries, helpers and plug-ins. Naturally, for seasoned CodeIgniter users, it's a straightforward process to put all of these features to work together. For newcomers though, things tend to be more complicated, particularly when it comes to taking certain theoretical concepts inherent in the MVC schema and putting them into practice. As soon as an inexperienced user starts developing a simple web application with CodeIgniter, he/she will be confronted with a number of common questions regarding the proper implementation and usage of Models, Controllers and Views. While learning how to work with Models and Controllers can be a challenging task, at least at first, the truth is that generating views seems to be much more approachable. To clarify this concept a bit further, say that youre building a web site comprised of a header section, a main area populated with some database contents, and finally a footer. In a case like this, the approach to be followed is pretty simple: on one hand youd define a model that performs a few CRUD operations on your database, while on the other hand, there would be a controller that uses the models methods to fetch database rows, which would finally be embedded into some views to generate the different sections of the site.

In reality, implementing this view-centric method is actually pretty easy to achieve. However, CodeIgniter provides web developers with enough flexibility to handle views in all sort of clever ways. Therefore, in this series of articles Ill be discussing in detail some common approaches that you can use to generate views, ranging from loading them sequentially, to using more complex methods, such as including views within other views. Are you ready to learn how to handle views with CodeIgniter? Then lets begin right now! Handling Views with CodeIgniter - Preparing views to be rendered on screen (Page 2 of 4 ) The first approach that Im going to explore in this article involves loading views sequentially. To implement this specific method, Im going to recreate a fictional scenario where an entire web page needs to be generated using the structure mentioned in the introduction. In this particular case, the header and footer sections will be static view files, while the main area will be filled in with dynamic content pulled out from a MySQL database. Based on this scheme, its necessary to build the static files that will comprise this sample web page, that is, the header and footer parts. So, here are the two files that perform this task:

(definition of header_view.php file) <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Sample Web Page</title> </head> <body> <div id="container"> <div id="header"> <h1><?php echo $header;?></h1> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> </div>

(definition of footer_view.php file)

<div id="footer"> <h2><?php echo $footer;?></h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> </div> </div> </body> </html>

So far, nothing unexpected, right? As you can see, the structure of the above two view files is pretty easy to follow. In the first case, the header_view.php file embeds only a $footer PHP variable into the markup, while the second file does something similar, since the footer_view.php view includes another variable called $footer. As I explained before, these views could be considered the static sections of the web page that I plan to generate, even though each of them will contain some data that will be passed along via a still-undefined controller class. Assuming that the latest version of CodeIgniter has already been installed on your testing web server, then the two previous view files should be saved to the /application/views/ folder of CI, so they can be found by its loader class at a later time. Well, at this point I demonstrated how to build the header and footer views of a basic web page, which will be loaded via a sequential method. But, actually Im getting ahead of myself, since first we need to define the view file that corresponds to the main area of the page. As I mentioned previously, this file will be populated with some database content. Therefore, its time to build this additional view file. This process will be discussed in depth in the section to come, so click on the link that appears below and read the following segment. Handling Views with CodeIgniter - Creating a content view (Page 3 of 4 ) In the previous section, I explained how to build a couple of static views that will be used later on for generating the header and footer parts of a simple web page. However, the only view file that remains undefined is the one tasked with rendering the main area of this page. In this situation, Im going to populate this area with content from a MySQL table called users, which I also used in some other PHP articles published here at the prestigious Developer Shed network. As a quick reminder, the structure of this table looked like this:

Now that you hopefully recalled how this example table was filled with some trivial records, its time to build the view file that loops over each of them. Here it is:

<div id="content"> <?php if($users->num_rows > 0):?> <?php foreach($users->result() as $user):?> <p><strong>First Name: </strong><?php echo $user->firstname;?></p> <p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr /> <?php endforeach;?> <?php endif;?> </div>

Undoubtedly, the above view should be fairly easy to grasp for you, since all that it does is iterate over each user fetched from the previous MySQL table and display their first and last names, and their email address, on screen. Before I forget, please save this view under the /application/views/ folder of CodeIgniter, so it can be used later on. Done? Great. Having created the view file that generates the dynamic section of the sample web page, the next step Im going to take will consist of defining a simple controller class. As youll see in a moment, this controller will be responsible for loading the three views in a sequential fashion, in this way generating the entire web document. This procedure will be shown in the upcoming section of this article, so if you wish to learn more, please read the next few lines. Handling Views with CodeIgniter - Building a web page controller class (Page 4 of 4 ) To be frank, generating an entire web document by sequentially loading the three views that you saw before is a no-brainer process that youll grasp in a snap. But how can it be done? Well, first its necessary to define a controller class that performs this specific task. In this

case, since Im attempting to create a web page, the controller will be called WebPage (my creativity with names sometimes blows me away) and itll look like this:

<?php class WebPage extends Controller{ function WebPage(){ // load controller parent parent::Controller(); // load libraries here $this->load->database(); // load helpers here } // load views sequentially function index(){ // load 'header' view $this->load->view('header_view',array('header'=>'Header Section')); // load 'content' view and pass in database content $this->load->view('content_view',array('users'=>$this->db->get('users'))); // load 'footer' view $this->load->view('footer_view',array('footer'=>'Footer Section')); } } ?>

See how simple it is to build a web page by loading views in a sequential manner? The controller defined above demonstrates this process pretty clearly, since it firsts loads the CIs database class within its constructor, and then proceeds to build the different sections of the page by loading in turn each of the previous views. Simple and efficient. Now that you hopefully understood how the WebPage controller works, save it under the /application/controllers/ folder and type the following URL on your browsers address field to test it: http://localhost/codeigniter/index.php/webpage/

If everything goes well, you should get the following output on screen:

There you have it. At this stage you've learned how to sequentially load three different views to generate a basic web page. Logically, theres plenty of room to improve the signature of the controller or even the views themselves. But guess what? This will be left as homework for you. Final thoughts In this first episode of the series, I explained how to build different sections of a basic web page with CodeIgniter by sequentially loading three independent view files. It could be said that this approach is possibly the simplest to implement when handling views with CI, but as I said in the beginning, its not the only one. In the next article, Ill be polishing the visual appearance of the web page generated previously to make it look slightly more appealing. Now that youve been warned about the topic that will be covered in the forthcoming part of the series, dont miss it! Adding CSS to Handling Views with CodeIgniter (Page 1 of 4 )

Introduction If you've had the chance to work with CodeIgniter, then you know that it is a robust framework with many useful features that let PHP programmers build web applications very quickly and with minor efforts. Of course it has the ability to manipulate view files in different ways, which can be quite helpful when creating front-ends for a web application or for a web site. So, if youre interested in learning how to load views in all sorts of clever ways with this popular PHP framework, them start reading this series of articles right now! Returning to the topic of sequential methods, you may recall that in the previous article of this series I demonstrated how to generate independently the header, main area and footer section of a basic web page by loading sequentially three different views. This task was performed by a controller class, which was called WebPage. It's worth mentioning that even though this controller populated the content area of this sample web page with some database records, it didnt use any model to specifically handle this data. However, dont worry about this for now, since this topic will be covered in upcoming articles of this series. Now its time to continue exploring the capabilities given by CodeIgniter when it comes to handling views. Since the visual appearance of the web page mentioned above was pretty rudimentary, in this second article Im going to improve it a bit to make it look more appealing and professional. So, with the preliminaries out of our way, lets see how to enhance the look and feel of this example web page. Lets get started! Adding CSS to Handling Views with CodeIgniter - Review: loading view files sequentially with CodeIgniter (Page 2 of 4 ) If you dont have the time to take a look at the example developed in the preceding article, where I explained how to build a basic web document by loading sequentially three different views, heres the full source code from that example, so you can rapidly grasp how it works.

(definition of webpage.php file located at /application/controllers/ folder) <?php class WebPage extends Controller{ function WebPage(){ // load controller parent parent::Controller(); // load libraries here $this->load->database(); // load helpers here } // load views sequentially function index(){ // load 'header' view $this->load->view('header_view',array('header'=>'Header Section')); // load 'content' view and pass database content $this->load->view('content_view',array('users'=>$this->db->get('users'))); // load 'footer' view

$this->load->view('footer_view',array('footer'=>'Footer Section')); } } ?>

(definition of header_view.php file- located at /application/views/ folder) <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Sample Web Page</title> </head> <body> <div id="container"> <div id="header"> <h1><?php echo $header;?></h1> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> </div>

(definition of content_view.php file - located at /application/views/ folder) <div id="content"> <?php if($users->num_rows > 0):?> <?php foreach($users->result() as $user):?> <p><strong>First Name: </strong><?php echo $user->firstname;?></p> <p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr /> <?php endforeach;?> <?php endif;?> </div>

(definition of footer_view.php file - located at /application/views/ folder) <div id="footer"> <h2><?php echo $footer;?></h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> </div> </div> </body> </html>

These are all the files required for building a basic web page whose main section has been populated with contents fetched from a users MySQL table. In this specific situation, the views corresponding to the header, content section and footer were loaded sequentially by the WebPage controller listed above. Now that you hopefully recalled how to load views in a sequential way with CI, its time to improve the visual presentation of the web page generated previously. To do so, Im simply going to incorporate into this page a few CSS styles, but the details of this process will be discussed in the section to come. Therefore, click on the link below and read the following segment, please. Adding CSS to Handling Views with CodeIgniter - Enhancing the look and feel of view files with CSS styles (Page 3 of 4 ) In reality, enhancing the visual aspect of the web page created in the previous segment is only a matter of adding to the header_view.php file some basic CSS styles. Its that simple, really. Nonetheless, it's useful to keep these styles, along with images, JavaScript, Flash files, etc residing in a separate folder, as you usually do when building your own web applications, right? To accomplish this in a simple manner, Im going to create an assets folder under the codeigniter directory (assuming that this is the root directory in your CI installation) and add a new subfolder called css. Once there, Im going to define a default.css CSS file that will be attached to the header view, which will look like this:

body{ padding: 0;

margin: 0; background: #999; } #container{ width: 600px; margin: 0 auto; } #header{ padding: 10px; background: #eee; } #content{ padding: 10px; background: #9cf; } #footer{ padding: 10px; background: #eee; } h1{ font: bold 2em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; color: #039; } h2{ font: bold 1.5em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; } p{ font: normal .8em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; }

Thats not rocket science, right? All that I did above was create a simple CSS file that hopefully will make the whole web page look a bit more appealing. Apart from building your skills in CSS, the educational aspect of creating this file is that it should give you a clear idea of how to define the structure of your web application when using CodeIgniter. In a case like this, the assets folder would include CSS, JavaScript and Flash files, along with images and so forth. Well, now that I've defined the CSS file that will improve the visual presentation of the previous web page, its time to modify the header_view.php file that you learned before, so it can load the file. This will be done in the next section. Thus, click on the link that appears below and keep reading. Were almost finished! Adding CSS to Handling Views with CodeIgniter - Rendering the improved version of a web page (Page 4 of 4 ) If youre like me, then surely youll want to see how the CSS styles defined in the prior section can be tied to the header_view.php file created before. To demonstrate more clearly how this process functions, below I listed the improved version of this header file, along with the web page controller and the other views. Here they are: (definition of webpage.php file located at /application/controllers/ folder)

<?php class WebPage extends Controller{ function WebPage(){ // load controller parent parent::Controller(); // load libraries here $this->load->database(); // load helpers here } // load views sequentially function index(){ // load 'header' view $this->load->view('header_view',array('header'=>'Header Section')); // load 'content' view and pass database content $this->load->view('content_view',array('users'=>$this->db->get('users'))); // load 'footer' view $this->load->view('footer_view',array('footer'=>'Footer Section')); } } ?>

(definition of header_view.php file- located at /application/views/ folder) <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Sample Web Page</title> <link rel="stylesheet" type="text/css" href="../assets/css/default.css" media="screen" /> </head> <body> <div id="container"> <div id="header"> <h1><?php echo $header;?></h1> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> </div>

(definition of content_view.php file - located at /application/views/ folder) <div id="content"> <?php if($users->num_rows > 0):?> <?php foreach($users->result() as $user):?> <p><strong>First Name: </strong><?php echo $user->firstname;?></p> <p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr /> <?php endforeach;?> <?php endif;?> </div>

(definition of footer_view.php file - located at /application/views/ folder) <div id="footer"> <h2><?php echo $footer;?></h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> </div> </div> </body> </html>

As shown above, not only has the default.css CSS file been attached to the header view, but now the whole web application's structure looks improved. In addition to examining the previous code samples, you may want to look at the following screen shot, which shows the polished appearance of this sample web page:

I cant say that the web document is ready to be used in production environments, but it looks much more attractive now. Even so, this example shows in a nutshell how to add some CSS styles to views that have been loaded sequentially, which can be quite helpful if you want to get familiar with the core concepts that surround the usage of CodeIgniter. Final thoughts In this second chapter of the series, I demonstrated how to polish the visual appearance of the web page created in the previous tutorial. As you saw for yourself, this process is actually very straightforward, meaning that you shouldnt have major problems replicating it with your own CI-based applications. In the upcoming part, Ill be exploring another method for loading views with CodeIgniter based on its load->vars() method. So, heres a suggestion that you should take into account: dont miss the next article!

Using Nested Views with CodeIgniter (Page 1 of 4 ) Introduction As I mentioned, there are several ways to work with view files with the CI framework, ranging from loading them sequentially and using the $this->load()->vars() method, to including views within other views. Of course, its also possible to combine all of these approaches to build dynamic web pages, depending on the requirements of a specific PHP program. In this series of articles youll find concise code samples that will show you different methods that you can use for loading views within your CI-based applications. And now that you've been introduced to the main subject of this series of tutorials, its time to refresh the topics that were discussed in the last one, in case you havent had opportunity to read it yet. In that article I explained how to improve the visual appearance of a basic web page, which was generated by loading sequentially three different views, where each of them was tasked with building the header, main area and footer section of the page. Actually, CodeIgniter is smart enough to concatenate the contents of views, if theyre loaded in a sequential manner from inside a controller or from another view. This makes it much easier to generate web pages like the one mentioned above. As I said before, however, there are several methods that can be utilized for loading view files, and in this third chapter of the series Im going to discuss one that bases its functionality on the loader class that comes bundled with CI. If youve already seen the official user guide, then you may know that this class has a useful method called $this->load->vars() that behaves similarly to the extract() PHP native function. By means of this method, it is very simple to replace in one single step all the variables included into multiple views with actual data. Therefore, in the next few lines Im going to discuss how to use it to generate a dynamic web document, which will display some database contents. Now, lets get rid of the prologue and start discovering how to handle view data with CodeIgniters $this->load->vars() method. Lets go! Using Nested Views with CodeIgniter - Review: loading views sequentially with CodeIgniter (Page 2 of 4 ) Before I proceed to demonstrate how to handle data in views via the $this->load->vars() method mentioned in the beginning, it would be useful to reintroduce an example developed in the preceding tutorial. As I mentioned, in that article I showed you how to build a basic web page by loading three distinct views sequentially. Having said that, below I've listed the complete definitions of each source file that comprises the example in question. Here they are:

(definition of webpage.php file located at /application/controllers/ folder)

<?php class WebPage extends Controller{ function WebPage(){ // load parent controller parent::Controller(); // load libraries here $this->load->database(); // load helpers here } // load views sequentially function index(){ // load 'header' view $this->load->view('header_view',array('header'=>'Header Section')); // load 'content' view and pass database content $this->load->view('content_view',array('users'=>$this->db->get('users'))); // load 'footer' view $this->load->view('footer_view',array('footer'=>'Footer Section')); } } ?>

(definition of header_view.php file - located at /application/views/ folder) <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Sample Web Page</title> <link rel="stylesheet" type="text/css" href="../assets/css/default.css" media="screen" /> </head> <body> <div id="container"> <div id="header"> <h1><?php echo $header;?></h1> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> </div>

(definition of default.css file - located at /codeigniter/assets/css/ folder) body{ padding: 0; margin: 0; background: #999; } #container{ width: 600px; margin: 0 auto; } #header{ padding: 10px; background: #eee; } #content{ padding: 10px; background: #9cf; } #footer{ padding: 10px; background: #eee; } h1{ font: bold 2em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; color: #039; } h2{ font: bold 1.5em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; } p{ font: normal .8em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; }

(definition of content_view.php file - located at /application/views/ folder) <div id="content"> <?php if($users->num_rows > 0):?> <?php foreach($users->result() as $user):?> <p><strong>First Name: </strong><?php echo $user->firstname;?></p> <p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr /> <?php endforeach;?> <?php endif;?> </div>

(definition of footer_view.php file - located at /application/views/ folder) <div id="footer"> <h2><?php echo $footer;?></h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> </div> </div> </body> </html>

In this particular case, the group of source files shown above are the building blocks of a simple CI-driven application that generates a dynamic web page by using three different views, which are loaded in a sequential way by a WebPage controller. Also, its clear to see how the controller fetches some rows from a users MySQL table, which are embedded into the content_view.php file for display purposes. Moreover, its worthwhile to note here that the view responsible for building the header section of the web page also includes a separate style sheet called default.css for enhancing the visual appearance of the whole web document. So far, so good. Having quickly reviewed the previous example, its time to see how to utilize the CIs loader class to generate a web page similar to the one shown before. As youll see in a few moments, this process will require using some nested views along with the aforementioned load->vars() method. But to learn this topic in more detail, youll have to click on the link below and read the following section. Using Nested Views with CodeIgniter - Preparing a nested view for displaying database contents (Page 3 of 4 ) As I said in the introductory part of this series, another common approach that can be used for building different parts of a web page consists of using nested views. Sounds a bit complicated? It is not, trust me. Essentially, when using this method, theres a main view that includes other views, which generate the distinct sections of a web document. To clarify this concept a bit more, Im going to code a new view file called mainpage_view.php, which will load three partial views sequentially. The file looks like this:

<?php $this->load->view('header_view'); $this->load->view('content_view'); $this->load->view('footer_view'); ?>

As you can see, this main view simply includes other views to build the header, main area and footer section of the web page. Not too difficult to grasp, right? Naturally, based on this schema, its not necessary to change the definition of the partial views, so they remain the same, as indicated below:

(definition of header_view.php file - located at /application/views/ folder) <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Sample Web Page</title> <link rel="stylesheet" type="text/css" href="../assets/css/default.css" media="screen" /> </head> <body> <div id="container"> <div id="header"> <h1><?php echo $header;?></h1> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> </div>

(definition of default.css file - located at /codeigniter/assets/css/ folder) body{ padding: 0; margin: 0; background: #999; } #container{

width: 600px; margin: 0 auto; } #header{ padding: 10px; background: #eee; } #content{ padding: 10px; background: #9cf; } #footer{ padding: 10px; background: #eee; } h1{ font: bold 2em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; color: #039; } h2{ font: bold 1.5em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; } p{ font: normal .8em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; }

(definition of content_view.php file - located at /application/views/ folder) <div id="content"> <?php if($users->num_rows > 0):?> <?php foreach($users->result() as $user):?> <p><strong>First Name: </strong><?php echo $user->firstname;?></p> <p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr /> <?php endforeach;?> <?php endif;?> </div>

(definition of footer_view.php file - located at /application/views/ folder) <div id="footer"> <h2><?php echo $footer;?></h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui

blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> </div> </div> </body> </html>

Actually, including views within other views is a powerful technique that permits you to generate dynamic and static content with extreme ease. However, you should be aware of always keeping view files like dumb structures that are only tasked with rendering data; no application logic should be delegated to them, since this is precisely the task of controllers. Having now introduced the concept of nested views, the unique piece of this schema that still remains undefined is a controller that populates the variables included in the views with real data. Thus, in the following section Im going to create this controller class, in this manner completing the development of this simple CI-based web application. To see how the controller will be built, please follow the link and read the next few lines. Using Nested Views with CodeIgniter - Embedding actual data into views with a web page controller class (Page 4 of 4 ) In the previous section, you learned how to build a view file that also includes other partial views. However, its necessary to create a controller class that implements the logic required to generate a complete web page, which will be filled in with some database contents. In this specific case, the controller that Im going to define below will use the $this->load>vars() method included with CIs loader class to replace the variables included within the views with actual data. That being explained, the web page controller looks like this:

<?php class WebPage extends Controller{ function WebPage(){ // load parent controller parent::Controller(); // load libraries here $this->load->database(); // load helpers here } // generate web page with nested views function index(){ // generate header, content and footer sections

$data=array('header'=>'Header Section','users'=>$this->db>get('users'),'footer'=>'Footer Section'); // load variables in views $this->load->vars($data); // load 'main_page' view $this->load->view('main_page'); } } ?>

Short to code and even simpler to read. Basically, all that the above WebPage controller does is generate a simple web page whose main area has been populated with the contents of a users MySQL table. As I explained before, the replacement of variables included in the views is achieved with the $this->load->vars() method, before loading the view that renders the main web document. In summary, if all has gone well, if you type the URL below into your browsers address field:

http://localhost/codeigniter/index.php/webpage

Then you should get the following output:

Hopefully with this simple example, you learned how to build a dynamic web page with CodeIgniter by using nested views along with the $this->load->vars() method. As usual with my articles on PHP web development, feel free to edit all of the code samples shown in this tutorial, so you can practice handling views with CodeIgniter. Final thoughts In this third installment of the series, I explained how to build a dynamic web page using a combination of CodeIgniters $this->load->vars() method and nested views. Hopefully you wont have major trouble implementing this approach successfully when building your own PHP applications with CI. In the next chapter, Im going to extend the concept of nested views a bit further by using a third parameter within the $this->load->view() method shown before. Now that you know what the upcoming article will be about, you cant miss it!

Returning Strings from Views with Code Igniter (Page 1 of 4 ) Introduction Now that you know what to expect from this article series, its time to recapitulate briefly the topics that were discussed in the last installment. In that particular tutorial I demonstrated how to build a simple MySQL-driven application by using a combination of the $this->load>vars() method and nested views. This approach allowed me to generate independently different sections of a front page, whose main area was populated with data fetched from a sample users MySQL table. Admittedly, including views within other views is a useful method that permits you to use certain parts of a web document across multiple pages of a web site; but the most interesting aspect of it is that it can be implemented in different ways. Speaking more specifically, its possible to feed the $this->load->view() method of CI a third Boolean parameter, to return the contents of a view to calling code after the view has been parsed. This is a handy variation of the method demonstrated in the previous article, and in this tutorial Ill be taking a close look at it, so you can grasp its underlying logic. Now, its time to get things rolling on and see how to return strings from views with CodeIgniter. Lets do it! Returning Strings from Views with Code Igniter - Review: using nested views along with the load-vars() method (Page 2 of 4 ) Its possible that you still havent had the chance to read the preceding article. As I mentioned, I went through the development of a simple MySQL-driven PHP application that utilized a mixture of nested views and the $this->load->vars() method to generate a dynamic web page. Below I included all of the source files that comprised this PHP program, so you can examine them in detail. Here they are:

(definition of webpage.php file located at /application/controllers/ folder) <?php class WebPage extends Controller{ function WebPage(){ // load parent controller parent::Controller(); // load libraries here $this->load->database(); // load helpers here } // generate web page with nested views and the load->vars() method function index(){ // generate header, content and footer sections $data=array('header'=>'Header Section','users'=>$this->db>get('users'),'footer'=>'Footer Section'); // load variables in views $this->load->vars($data); // load 'main_page' view $this->load->view('main_page'); } }

?>

(definition of main_page.php file - located at /application/views/ folder) <?php $this->load->view('header_view'); $this->load->view('content_view'); $this->load->view('footer_view'); ?>

(definition of header_view.php file - located at /application/views/ folder) <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Sample Web Page</title> <link rel="stylesheet" type="text/css" href="../assets/css/default.css" media="screen" /> </head> <body> <div id="container"> <div id="header"> <h1><?php echo $header;?></h1> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> </div>

(definition of default.css file - located at /codeigniter/assets/css/ folder) body{ padding: 0; margin: 0;

background: #999; } #container{ width: 600px; margin: 0 auto; } #header{ padding: 10px; background: #eee; } #content{ padding: 10px; background: #9cf; } #footer{ padding: 10px; background: #eee; } h1{ font: bold 2em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; color: #039; } h2{ font: bold 1.5em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; } p{ font: normal .8em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; }

(definition of content_view.php file - located at /application/views/ folder) <div id="content"> <?php if($users->num_rows > 0):?> <?php foreach($users->result() as $user):?> <p><strong>First Name: </strong><?php echo $user->firstname;?></p> <p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr /> <?php endforeach;?> <?php endif;?> </div>

(definition of footer_view.php file - located at /application/views/ folder) <div id="footer"> <h2><?php echo $footer;?></h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in

hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> </div> </div> </body> </html>

Regardless of the apparently complex structure of the above CI-based application, each one of its parts performs some simple tasks. First, the controller is responsible for generating the typical sections of a web page, that is the header, contents area and footer. In this particular case, the main section of the web document is filled in with some database rows previously fetched from a MySQL table. But undoubtedly, the most relevant thing to spot here is how nested views are used to build the aforementioned web page sections. Having reviewed quickly this approach to handling view files with CodeIgniter, the next thing that Im going to discuss will be how to construct a web page similar to the above, but this time using an additional parameter with the $this->load->view() method. In case youre not aware of it, when this method is called with a third argument, for instance like this:

$data[header]=$this->load->view(myview,array(title=>Header Section),TRUE);

Then, not only the $title variable will be parsed within the view, but the resulting string will be returned to calling code, and in this case will be stored on the $data array as well. As you can see, this can be really useful for storing partial sections of a web page on variables, before rendering them completely on screen. So, in the next section Ill be explaining in more detail how to load views as shown before. However, to learn how this will be done, youll have to click on the link below and keep reading. Returning Strings from Views with Code Igniter - Generating partial sections of a web page (Page 3 of 4 ) As I stated in the previous segment, its possible to pass a third Boolean argument to the $this->load->view() method to return its output as a string after it has been parsed. By using this approach, it is also very simple to build sections of a web page independently, in a way similar to the method shown in the preceding article.

To demonstrate how this approach can be successfully implemented, first Im going to create some new view files, which are listed below:

(definition of main_page.php file - located at /application/views/ folder) <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Sample Web Page</title> <style type="text/css"> body{ padding: 0; margin: 0; background: #999; } #container{ width: 600px; margin: 0 auto; } #header{ padding: 10px; background: #eee; } #content{ padding: 10px; background: #9cf; } #footer{ padding: 10px; background: #eee; } h1{ font: bold 2em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; color: #039; } h2{ font: bold 1.5em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; } p{ font: normal .8em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; } </style> </head> <body> <div id="container"> <?php echo $header.$content.$footer; ?> </div> </body> </html>

(definition of header_view.php file - located at /application/views/ folder) <div id="header"> <h1><?php echo $header;?></h1> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut.</p> </div>

(definition of content_view.php file - located at /application/views/ folder) <div id="content"> <?php if($users->num_rows > 0):?> <?php foreach($users->result() as $user):?> <p><strong>First Name: </strong><?php echo $user->firstname;?></p> <p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr /> <?php endforeach;?> <?php endif;?> </div>

(definition of footer_view.php file - located at /application/views/ folder) <div id="footer"> <h2><?php echo $footer;?></h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut.</p> </div>

Hopefully, at this point the group of view files coded above should be fairly familiar to you, right? Naturally, these are responsible for generating different sections of a web page, plus theres one that acts like a general layout, called main_page.php, which loads the values returned from the other views. With this handy view structure at our disposal, now its time to see how it can be used in conjunction with the strings returned by the $this->load->view() method to build an entire web document. This task will be performed by a controller, and its definition will be shown in the next few lines. So, jump ahead and read the following section, please. Returning Strings from Views with Code Igniter - Putting all of the views together (Page 4 of 4 ) In order to build a complete web page with the views that you saw in the previous section, its necessary to define a controller class that first stores the strings returned from each of them,

and then passes this content to the layout view. If this sounds a bit confusing to you, the following web page controller should help to clarify any issues that you might have. Here it is:

<?php class WebPage extends Controller{ function WebPage(){ // load controller parent parent::Controller(); // load libraries here $this->load->database(); // load helpers here } // generate web page using partial sections function index(){ // generate header section $data['header']=$this->load->view('header_view',array('header'=>'Header Section'),TRUE); // generate content section $data['content']=$this->load->view('content_view',array('users'=>$this->db>get('users')),TRUE); // generate footer section $data['footer']=$this->load->view('footer_view',array('footer'=>'Footer Section'),TRUE); // generate full web page $this->load->view('main_page',$data); } } ?>

Do you see how simple it is to generate a dynamic web page by returning strings with the $this->load->view() method? I guess you do. In the above example, each of the sections that make up the page are stored temporally on the $data array, and then its passed to the main_page view for displaying purposes. Hopefully, this code sample should give you a clear idea of how to return contents from a view after they've been loaded, via the third TRUE argument as shown before. And finally, assuming that all of this has been set up correctly, if you type the following URL into your browser:

http://localhost/codeigniter/index.php/webpage

Then you should get the following output:

Here you have it. At this point, you've learned how to use the $this->load->view() method in a slightly different way to generate a simple database-driven web application with CodeIgniter. All of the examples developed in this tutorial can be enhanced. For example, you might want to create a users model and utilize it within the controller to fetch database rows, instead of using the database class directly. Whatever you decide to do, one thing is certain: CodeIgniter will keep you entertained for hours! Final thoughts In this fourth part of this series, I explained how to build a simple, yet dynamic, web page by returning strings from some views. As was illustrated earlier, this approach permits us to generate partial sections of a web document in a pretty intuitive and flexible fashion, and Im sure that youll find even more useful ways to use it.

In the following article, Ill be discussing how to make views even more "dumb" (if the term is actually applicable) by removing certain presentation logic from them. If you wish to learn how this will be done, dont miss the upcoming tutorial! Moving Presentation Logic Out of Views with Code Igniter (Page 1 of 4 ) Introduction At this point, after having introduced you to the subject of this series of articles, its time to recall the topics we discussed in the last tutorial, in case you still havent had the chance to read it. In summary, in that article I proceed to build a simple MySQL-driven application whose main task consisted of fetching some database rows and embedding this data into a basic view file. Apart from playing a bit with the schema dictated by the Model-View-Controller pattern, this particular example showed in a nutshell how to return strings from the $this->load->view() method to create different parts of a web page, such as the typical header and footer sections, and a main area as well. In addition, youll possibly recall that the view that displayed the database records implemented a simple presentation logic, reduced to looping over the records in question and nothing else. Its also possible to make this view even dumber by moving this looping structure out of it, in this way achieving a greater level of separation between the applications logic and its presentation layer. Therefore, in this fifth part of the series, Ill be rebuilding the web application that you learned in the last article, modifying the view file responsible for displaying database rows on the web page. Do all these things sound interesting enough for you? Then lets get started right now! Moving Presentation Logic Out of Views with Code Igniter - Review: returning values with a previous method (Page 2 of 4 ) In the introduction, I mentioned that its possible to remove from a view the PHP loop that iterates over the database rows, based on the structure of the web application developed in the previous article. But before I show you how to do that, Im going to reintroduce the full source code of this sample PHP program, so you can recall how it was developed initially. That being said, here are all the files that comprise this web application:

(webpage.php file located at /application/controllers/ folder) <?php class WebPage extends Controller{ function WebPage(){ // load controller parent parent::Controller(); // load libraries here $this->load->database(); // load helpers here } // generate web page using partial sections

function index(){ // generate header section $data['header']=$this->load->view('header_view',array('header'=>'Header Section'),TRUE); // generate content section $data['content']=$this->load->view('content_view',array('users'=>$this->db>get('users')),TRUE); // generate footer section $data['footer']=$this->load->view('footer_view',array('footer'=>'Footer Section'),TRUE); // generate full web page $this->load->view('main_page',$data); } } ?>

(main_page.php file - located at /application/views/ folder) <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Sample Web Page</title> <style type="text/css"> body{ padding: 0; margin: 0; background: #999; } #container{ width: 600px; margin: 0 auto; } #header{ padding: 10px; background: #eee; } #content{ padding: 10px; background: #9cf; } #footer{ padding: 10px; background: #eee; } h1{ font: bold 2em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; color: #039; } h2{ font: bold 1.5em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; } p{ font: normal .8em Arial, Helvetica, sans-serif; margin: 0 0 18px 0;

} </style> </head> <body> <div id="container"> <?php echo $header.$content.$footer; ?> </div> </body> </html>

(header_view.php file - located at /application/views/ folder) <div id="header"> <h1><?php echo $header;?></h1> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut.</p> </div>

(content_view.php file - located at /application/views/ folder) <div id="content"> <?php if($users->num_rows > 0):?> <?php foreach($users->result() as $user):?> <p><strong>First Name: </strong><?php echo $user->firstname;?></p> <p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr /> <?php endforeach;?> <?php endif;?> </div>

(footer_view.php file - located at /application/views/ folder) <div id="footer"> <h2><?php echo $footer;?></h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut.</p> </div>

Having listed all of the source files that compose the MySQL-driven application built during the previous tutorial of this series, its worthwhile to stress one point regarding the way its been

structured: as you can see, within the content_view.php view file theres a foreach construct that loops over the rows fetched from a users MySQL table. This is a valid approach, used frequently for constructing views. However, its also feasible to implement a little twist here and remove the loop from this specific view, in this way increasing the level of separation between the applications logic and its visual presentation even more. Provided that youre interested in learning how to turn the concept deployed above into functional code, in the next section Ill be creating a brand new view file, in addition to modifying slightly the signature of the WebPage controller class. Click on the link below and continue reading. Moving Presentation Logic Out of Views with Code Igniter - Moving presentation logic out of views (Page 3 of 4 ) Since in this case Im planning to move the foreach loop included within the content_view.php file out of it, the simplest way to do that is by implementing this part of the application straight into the controller. To demonstrate how to achieve this, below I listed the modified signature of the WebPage controller class, which now looks like this:

<?php class WebPage extends Controller{ function WebPage(){ // load controller parent parent::Controller(); // load libraries here $this->load->database(); // load helpers here } // generate web page using partial sections function index(){ // generate headers section $data['header']=$this->load->view('header_view',array('header'=>'Header Section'),TRUE); $query=$this->db->get('users'); if($query->num_rows > 0){ // generate content section $data['content']=NULL; foreach($query->result() as $user){ $data['content'].=$this->load->view('users_view',array('user'=>$user),TRUE); } } // generate footer section $data['footer']=$this->load->view('footer_view',array('footer'=>'Footer Section'),TRUE); // generate full web page $this->load->view('main_page',$data); } } ?>

As shown above, the logic implemented by the WebPage controller practically remains the same, except for a tiny detail: now the foreach loop included previously within the content_view.php file has been moved within the controller, and in consequence its necessary to create a new view that displays the data retrieved from the users MySQL table. The signature of this new view file, called users_view.php, looks as simple as this:

<p><strong>First Name: </strong><?php echo $user->firstname;?></p> <p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr />

Here you have it. Now the controller is responsible for looping over the rows fetched from the MySQL table, and the result is stored on the $data[content] array element. Lastly, each section of the web page is embedded into the main_page.php view, which finishes rendering the whole web document. Not too hard to understand, right? Having implemented an alternative approach to building a basic MySQL-based web application, now its time to put all of its pieces together, since two of its files were modified. Thus, in the last section of this tutorial Ill be listing for you the full source code of this sample PHP program, so you can copy/paste it and introduce your own improvements. Now, jump forward and read the next few lines. Were almost finished! Moving Presentation Logic Out of Views with Code Igniter - The modified source code of the sample PHP program (Page 4 of 4 ) Having demonstrated how simple it is to remove (at least partially) the presentation logic from a view file and delegate part of this task to the controller, here are all the source files corresponding to this sample PHP application, after we've introduced the changes that you learned in the prior section. Take a look at them, please:

(webpage.php file located at /application/controllers/ folder) <?php class WebPage extends Controller{ function WebPage(){ // load controller parent parent::Controller(); // load libraries here $this->load->database(); // load helpers here } // generate web page using partial sections function index(){ // generate headers section $data['header']=$this->load->view('header_view',array('header'=>'Header Section'),TRUE);

$query=$this->db->get('users'); if($query->num_rows > 0){ // generate content section $data['content']=NULL; foreach($query->result() as $user){ $data['content'].=$this->load->view('users_view',array('user'=>$user),TRUE); } } // generate footer section $data['footer']=$this->load->view('footer_view',array('footer'=>'Footer Section'),TRUE); // generate full web page $this->load->view('main_page',$data); } } ?>

(main_page.php file - located at /application/views/ folder) <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Sample Web Page</title> <style type="text/css"> body{ padding: 0; margin: 0; background: #999; } #container{ width: 600px; margin: 0 auto; } #header{ padding: 10px; background: #eee; } #content{ padding: 10px; background: #9cf; } #footer{ padding: 10px; background: #eee; } h1{ font: bold 2em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; color: #039; } h2{ font: bold 1.5em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; } p{ font: normal .8em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0; } </style> </head> <body> <div id="container"> <?php echo $header.$content.$footer; ?> </div> </body> </html>

(users_view.php file - located at /application/views/ folder) <p><strong>First Name: </strong><?php echo $user->firstname;?></p> <p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr />

(footer_view.php file - located at /application/views/ folder) <div id="footer"> <h2><?php echo $footer;?></h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut.</p> </div>

If you already have a fresh installation of CodeIgniter working on your web server, then when you type the following URL on your browser:

http://localhost/codeogniter/index.php/webpage

You should get the following output echoed to the screen:

Regardless of the simple structure of this sample PHP application, its useful for demonstrating another approach when it comes to handling views with CodeIgniter. As usual with other articles of this series, feel free to tweak all of the code samples shown in this article. This will help you understand more quickly how to create view files that include only basic presentation logic. Final thoughts In this fifth part of the series, I demonstrated yet another approach that can be used for partially removing presentation logic from views. Despite the fact that this method isnt as intuitive as others utilized in previous articles, it might be appealing to you. Again, its valid to say that theres not an official way to work with CodeIgniter, and it depends on you what approach to use when developing your own PHP applications. Now, returning to the examples developed so far in this series, you may have noticed that none of them have utilized a model to access the users MySQL table. Its not mandatory to code a model with CI, particularly if the program youre planning to build is fairly basic or your implementation of the MVC pattern is loose.

However, in the next chapter of this series Ill be defining a model, which will be incorporated into the PHP program developed earlier. Want to see how this will be done? Then, dont miss the forthcoming part! Defining a Model Class for Handling Views with CodeIgniter (Page 1 of 4 ) And now that youre aware of the topics that are covered in this group of articles, its time to review the concepts discussed in the last tutorial. In that part, I used a practical example to show you how to partially remove presentation logic from a particular view file, and implement it within a simple controller class. As with many other aspects related to using the Model-View-Controller pattern with CodeIgniter, making views a bit dumber has its pros and cons. How successful this approach can be in the end depends strongly on the structure defined for a particular application. Again, its fair to mention here that CI gives developers enough flexibility to implement the MVC pattern without forcing the use of a specific programming methodology. Indeed, this is one of its most appreciated characteristics. Now, returning to the previous tutorial, youll recall that I developed a sample PHP application. It displayed the contents of some database rows which were previously fetched from a users MySQL table. Moreover, these rows were retrieved by using the active record class bundled with CI. However, its also possible to define a model that performs all of the database-related operations, instead of directly using the database class. Thus, in the next few lines Im going to show you how to build another web application similar to the one that you learned in the preceding article -- but this time it will incorporate a basic model class. In doing so, youll be able to see how to handle views by using the entire Model-View-Controller triad. Are you ready to continue learning how to parse views with CodeIgniter? Then lets jump right in! Defining a Model Class for Handling Views with CodeIgniter - Review: moving presentation logic out of views (Page 2 of 4 ) If youre like me, then you cant wait to see how a model can be used for interacting with the users MySQL table that you saw in the prior tutorial. Before you learn that, however, Im going to list all of the source files corresponding to the web application developed in the previous article, so you can clearly see the differences between using a model and using the CIs database class directly. Having clarified that point, heres the complete source code for this sample PHP program: (webpage.php file located at /application/controllers/ folder) <?php class WebPage extends Controller{ function WebPage(){ // load controller parent parent::Controller(); // load libraries here $this->load->database(); // load helpers here }

// generate web page using partial sections function index(){ // generate headers section $data['header']=$this->load->view('header_view',array('header'=>'Header Section'),TRUE); $query=$this->db->get('users'); if($query->num_rows > 0){ // generate content section $data['content']=NULL; foreach($query->result() as $user){ $data['content'].=$this->load->view('users_view',array('user'=>$user),TRUE); } } // generate footer section $data['footer']=$this->load->view('footer_view',array('footer'=>'Footer Section'),TRUE); // generate full web page $this->load->view('main_page',$data); } } ?>

(main_page.php file - located at /application/views/ folder) <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Sample Web Page</title> <style type="text/css"> body{ padding: 0; margin: 0; background: #999; } #container{ width: 600px; margin: 0 auto; } #header{ padding: 10px; background: #eee; } #content{ padding: 10px; background: #9cf; } #footer{ padding: 10px; background: #eee; } h1{ font: bold 2em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; color: #039; } h2{

font: bold 1.5em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; } p{ font: normal .8em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; } </style> </head> <body> <div id="container"> <?php echo $header.$content.$footer; ?> </div> </body> </html>

(users_view.php file - located at /application/views/ folder) <p><strong>First Name: </strong><?php echo $user->firstname;?></p> <p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr />

(footer_view.php file - located at /application/views/ folder) <div id="footer"> <h2><?php echo $footer;?></h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut.</p> </div> In this case, three views and a basic web page controller class are the only building blocks required for developing a web application whose main task is to display the contents of the users MySQL table on screen. As I stated before, the controller directly uses the database class for retrieving database rows, which are properly parsed before being embedded into the main_page.php view file. Undoubtedly, the above approach demonstrates in a nutshell how to partially remove some presentation logic from a view, but its not the only method that you may want to use for handling views with CodeIgniter. Now that you've hopefully recalled how the web application shown a few lines before was built by using a single controller class and some additional views, its time to move on. We're going to start defining a users model class, which will be tasked with retrieving database rows from the already familiar users MySQL table. Of course, creating a model implies that the signature of the controller must be modified to work with it, but dont worry about this for the moment. Simply proceed to read the following section, where Im going to explain how to build this model class.

Now, click on the link that appears below and read the next segment. Defining a Model Class for Handling Views with CodeIgniter - Handling database contents with a simple model class (Page 3 of 4 ) In the preceding segment, I mentioned that it was perfectly possible to incorporate a model class to access database contents, instead of directly using the database class included with CodeIgniter. So, to put this theoretical concept into practice, below I created such a class. In this case, it is charged with fetching some rows from the users MySQL table that you learned before, and with counting its records as well. In summary, this model class, called User_model, is defined in the following way:

<?php class User_model extends Model{ function User_model(){ // call the Model constructor parent::Model(); // load database class and connect to MySQL $this->load->database(); } // fetch all users function getAll(){ $query=$this->db->get('users'); // return result set as object return $query->result(); } // fetch some users based on a predefined condition function getWhere($field,$param){ $this->db->where($field,$param); $query=$this->db->get('users'); // return result set as object return $query->result(); } // get total number of users function getNumber(){ return $this->db->count_all('users'); } } ?>

In reality, understanding how the above User_model class works is a pretty straightforward process, dont you think? As you can see, this model implements a few basic methods for retrieving users from the corresponding database table, and for counting them as well. Naturally, its feasible to aggregate more methods that perform inserts, updates and deletions, but for now Ill keep the signature of the model simple. So far, so good. At this point, I showed you how to build a basic model class that will be responsible for fetching user-related data from the pertinent MySQL table. Therefore, the next step is to change the signature of the WebPage controller class so that it can use the model for accessing database contents.

This modification will be discussed in detail in the last section of this tutorial. Therefore, please click on the link below and read the upcoming segment. Defining a Model Class for Handling Views with CodeIgniter - Demonstrating a simple use of the model class (Page 4 of 4 ) Since in the previous section I created a basic model class that permits us to fetch and count users stored on a MySQL table, the next thing Im going to do will be modifying the signature of the corresponding WebPage controller so that it can use the models methods from behind its API. Having explained that, heres how the controller now looks:

<?php class WebPage extends Controller{ function WebPage(){ // load controller parent parent::Controller(); // load users model $this->load->model('User_model'); // load some helpers here } // generate web page using partial sections function index(){ // generate header section $data['header']=$this->load->view('header_view',array('header'=>'Header Section'),TRUE); // generate content section $data['content']=$this->load->view('content_view',array('users'=>$this>User_model->getAll()),TRUE); // generate footer section $data['footer']=$this->load->view('footer_view',array('footer'=>'Footer Section'),TRUE); // generate full web page $this->load->view('main_page',$data); } } ?>

Simple to code and read, isnt it? As shown above, now the index() method of the controller generates the header, body and footer parts of a web page, but this time the body section is populated with database contents that are fetched via the getAll() method that belongs to the model. At this stage, not only does the controller show how to utilize the methods given by a specific model, but the example illustrates how to assemble an entire web page by returning different strings from the $this->load->view() method. The missing pieces of this schema are the three view files that actually render the web page in question. However, these will be created in the last article of the series. Meanwhile, feel free to edit and enhance the respective signatures of the model and the controller to acquire a more solid grounding in developing database-driven applications with CodeIgniter.

Final thoughts Over this sixth episode of the series, I went through building a basic model class with CodeIgniter. This class was incorporated into a simple PHP application whose primary functionality was displaying information on screen about some users stored on a MySQL table. Logically, at this point the application is still incomplete, since it is necessary to create three different views that will be responsible for generating independently the header, main area and footer section of the web page where user-related data will be echoed. Those views will be built in the last tutorial. So heres a piece of advice that you should consider seriously: dont miss the final article! Embedding Model Data in Views with Code Igniter (Page 1 of 4 ) Introduction The intrinsic flexibility offered by the CodeIgniter framework gives PHP developers the ability to handle views in several clever ways. This feature allows you to easily generate dynamic sections of web pages. From loading views sequentially and using layout views, to nesting them within other views, CI offers plenty of options that permit you to quickly build front-ends without having to struggle with the schema dictated by the Model-View-Controller pattern. However, for newcomers just starting to develop PHP applications with CodeIgniter, working with views in more complex ways can be challenging. Thus, if youre stuck within a maze of controllers and dont know how to make them interact with your views, then you should take a look at this group of articles, since theyll show you different approaches that you can use for manipulating views in a truly efficient way. And now that youre well aware of the subject of this series of tutorials, its time to spend a moment refreshing the topics that were treated in the last article, in case you havent had the opportunity to read it yet. In that part, I explained how to build a simple database-driven application, whose main functionality was based on displaying on screen a few user-related records, previously fetched from a MySQL table. In its current state, the structure of this sample application looked rather incomplete. It was comprised of a model and a controller class, where the first was responsible for retrieving user data from the table, and the second was charged with embedding this data in some view files, which actually havent been defined yet. Therefore, in this final chapter of the series Ill be creating these views, completing the development of this basic database-driven PHP program using CodeIgniter. By the end of this article, youll be equipped with a decent background not only in creating basic PHP applications with CI, but in manipulating views in an effective way. Are you ready to tackle the last episode of this educational journey? Then, lets get started right now! Embedding Model Data in Views with Code Igniter - Review: the first two modules of the previous web application (Page 2 of 4 )

Before I proceed to build the three view files required to complete the PHP application created in the previous tutorial of this series, it would be useful to list the signatures of its model and controller classes, to help you recall more quickly how they were built. That said, below I included these two classes. Have a look at them, please: (user_model.php file located at /application/models/ folder) <?php class User_model extends Model{ function User_model(){ // call the Model constructor parent::Model(); // load database class and connect to MySQL $this->load->database(); } // fetch all users function getAll(){ $query=$this->db->get('users'); // return result set as an object array return $query->result(); } // fetch some users based on a predefined condition function getWhere($field,$param){ $this->db->where($field,$param); $query=$this->db->get('users'); // return result set as an object array return $query->result(); } // get total number of users function getNumber(){ return $this->db->count_all('users'); } } ?>

(webpage.php file located at /application/controllers/ folder) <?php class WebPage extends Controller{ function WebPage(){ // load controller parent parent::Controller(); // load users model $this->load->model('User_model'); // load some helpers here } // generate web page using partial sections function index(){ // generate header section $data['header']=$this->load->view('header_view',array('header'=>'Header Section'),TRUE); // generate content section $data['content']=$this->load->view('content_view',array('users'=>$this>User_model->getAll()),TRUE); // generate footer section

$data['footer']=$this->load->view('footer_view',array('footer'=>'Footer Section'),TRUE); // generate full web page $this->load->view('main_page',$data); } } ?>

Undeniably, the tasks performed by both the model and controller classes are very easy to follow. First, the model has a few simple methods for counting and retrieving rows from a user MySQL table. On the other hand, the controller implements an index() method that uses the models getAll() method to generate the contents section of a web page. Of course, its valid to point out here that each part of the web page being created is stored on a $data array, which is finally passed to a main_page.php view. All of these tasks, accomplished by the WebPage controller, naturally imply that the views need to be created accordingly. Therefore, in the following section Im going to build the first three views, which will be tasked with generating the header, content and footer sections of the web document. To learn how this will be achieved, youll have to click on the link that appears below and read the section to come.

Embedding Model Data in Views with Code Igniter - Creating some basic view files (Page 3 of 4 ) If you already went through the preceding articles of this series, then you're already familiar with building simple views. The views that I plan to build now will be really simple to grasp as well. As youll surely recall from the controller defined in the previous section, these views must be capable of generating independently the header, main area and footer section of a web page. This is actually very easy to accomplish. Here are the three views that render the web page in question:

(header_view.php file located at /application/views/ folder) <div id="header"> <h1><?php echo $header;?></h1> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut.</p> </div> (content_view.php file located at /application/views/ folder) <div id="content"> <?php foreach($users as $user):?> <p><strong>First Name: </strong><?php echo $user->firstname;?></p>

<p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr /> <?php endforeach;?> </div>

(footer_view.php file located at /application/views/ folder) <div id="footer"> <h2><?php echo $footer;?></h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut.</p> </div>

As I said before, the signatures corresponding to the above views are fairly simple to understand. In this case, the content_view.php file is possibly the most complex to grasp, but all that it does is iterate over all the rows fetched from the pertinent users MySQL table and display the users first and last names, as well as their email addresses. Due to the simple structure of the views coded before, I dont want to spend more time explaining what they do, since that would be pretty pointless. However, as you may have noticed, theres still one view that remains undefined, called main_page.php, which is precisely the one responsible for concatenating the other views. Therefore, the last segment of the tutorial will be focused on creating this layout view, in this manner concluding this instructive journey on handling views with CodeIgniter. Now, if you want to see how this view will be coded, click on the link shown below and read the following section. Embedding Model Data in Views with Code Igniter - Finishing the sample PHP application with CodeIgniter (Page 4 of 4 ) In the previous section, I created the three views that will be used for generating independently several section of a web page. Therefore, the last step that Im going to take will consist of building the layout view, which was called main_page.php. Obviously, this particular file is tasked with concatenating the contents of the other views, meaning that its signature will be very simple to code. Below you'll see the entire source code corresponding to this layout file. Have a look at it, please:

<!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Sample Web Page</title> <style type="text/css">

body{ padding: 0; margin: 0; background: #999; } #container{ width: 600px; margin: 0 auto; } #header{ padding: 10px; background: #eee; } #content{ padding: 10px; background: #9cf; } #footer{ padding: 10px; background: #eee; } h1{ font: bold 2em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; color: #039; } h2{ font: bold 1.5em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; } p{ font: normal .8em Arial, Helvetica, sans-serif; margin: 0 0 18px 0; } </style> </head> <body> <div id="container"> <?php echo $header.$content.$footer; ?> </div> </body> </html>

If you were expecting to see a lengthy view, you might feel a little disappointed. Apart from including a few basic CSS styles, the above layout file contains only one echo PHP statement that appends the contents of the other views to generate the header, main area and footer section of the web page. Of course, this isnt the only approach that can be utilized for building front-ends dynamically with CodeIgniter, but it certainly is a common one. Finally, now that you've learned how to handle views in a few clever ways, feel free to tweak all of the code samples developed in this tutorial. Doing this should give you a more solid understanding of how to create web pages with CI. Whatever you do from this point onward, one thing is for sure: fun is already guaranteed! Final thoughts

Its really hard to believe, but weve come to the end of this series. If youve been a patient reader and examined in depth all of the code samples included in these tutorials, then by this time should have a clear idea of how to process views with CodeIgniter. As you can see, there is not just one right way to handle views; CI offers several approaches that can be used to suit the requirements of a specific PHP application. From my point of view as a web developer, I find returning strings from views a very useful method for building web pages where static and dynamic contents are generated independently, but again, this is only a matter of personal preference. See you in the next PHP development tutorial!

Вам также может понравиться