Building a Database-Driven Application with the Code Igniter PHP Framework

If you’re a PHP developer who’s searching for a framework that lets you build full-blown web applications very quickly and with an easy learning curve, look no further. Welcome to the second part of the series entitled “Introducing the Code Igniter PHP framework.” This series of articles shows you how to use this friendly yet powerful PHP framework to easily develop database-driven applications by using the Model-View-Controller design pattern.

Introduction

Now that you have been introduced to the main subject of this series, it’s time to recall the concepts deployed in the preceding tutorial, in case you haven’t 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 application’s 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. That’s all.

However, this initial sample application was pretty primitive, actually. Therefore, in this second part of the series, I’m 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 you’ll 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, don’t waste more time in preliminaries and begin reading now!

{mospagebreak title=Retrieving user-related data from a MySQL table}

As I anticipated in the beginning, the first step involved in the development of this MySQL-driven 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, I’m 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 here’s 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 Igniter’s 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 I’m 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 model’s 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.

{mospagebreak title=Defining a controller class}

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. It’s 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, don’t 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, it’s time to pay attention to the implementation of the “index()” method, which actually is very interesting. As you can see, it uses the model’s 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, it’s very important to stress here the notation used for accessing the model’s API. Here’s 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 there’s a model called “Blog,” it should be called within the controller as $this->Blog. That’s 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 model’s API, to fetch some rows from a sample “users” MySQL table, and to embed this data into a view file.

Nonetheless, if you’re like me, then at this moment you’re wondering how this view file actually looks. Well, in response to that question, in the following section I’ll be creating this view, completing the development of this MySQL-driven application.

Please, click on the link below and keep reading. We’re almost done!

{mospagebreak title=Outputting user-related data with Code Igniter}

Before I proceed to demonstrate how to build a simple view file for displaying the contents of the corresponding “users” MySQL table, first it’s 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, here’s 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, it’s 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, it’s 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/


That’s all, trust me. Try out this example with your own web server and you’ll 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 aren’t 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, I’m going to teach you how to paginate database records with Code Igniter, so now that you know what to expect from this tutorial, you don’t have any excuses to miss it!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye