User Management System: Part 1
Published on Monday, August 31st, 2009 12 CommentsA simple login form with hard coded users is good for small projects. Larger projects however, require much more to stay efficient and expandable. With a larger system, you might also want to store additional information about a user. Information such as: The IP address they logged in from; The date and time the account was created; etc…
I will walk you through how to put together such a system. This user management system can be used for any application or website you create and can be altered to accommodate any other information you may want to store.
Setting up the Database
To begin, we need to create a database that will store our tables. Name it whatever you like. Inside the newly created database, we will need to create a new table called `accounts`. The columns we will create for this tutorial are as follows:
- account_id - unique ID for each account
- account_email - email address of account
- account_password - encrypted password of account
- account_name - name of account
- account_role - privilege level of account
- account_creation_date - date account was created
- account_last_login - date of last login
- account_last_ip - IP of last login
Here is the Create Table Syntax for MySQL:
CREATE TABLE `accounts` (
`account_id` int(11) NOT NULL auto_increment,
`account_email` varchar(200) NOT NULL default '',
`account_password` varchar(250) NOT NULL default '',
`account_name` varchar(150) NOT NULL default '',
`account_role` enum('user','admin') NOT NULL default 'user',
`account_creation_date` datetime NOT NULL,
`account_last_login` datetime NOT NULL,
`account_last_ip` varchar(25) NOT NULL default '',
PRIMARY KEY (`account_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
Now that the database is setup, we will move on to setting up CodeIgniter.
Setting up CodeIgniter
To begin setting up CodeIgniter, we must first download it! Once you have downloaded CodeIgniter, unzip the the file and upload the files to your web server. I like to move the application directory outside of the system directory to the root directory where the index.php file is. It doesn’t matter which way you choose as long as you stay consistent.
Now, I will go ahead and update the config files for my server. Do the same for yours.
In config.php:
$config['base_url'] = "http://localhost/sandbox/user_management/";
$config['encryption_key'] = "yourencryptionkey"; // (random 32 character string)
In database.php:
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "yourusername";
$db['default']['password'] = "yourpassword";
$db['default']['database'] = "yourdatabase";
Now that CodeIgniter is setup and connecting to our database, we need to create our Model which allows us to alter the data in the database.
Creating the Model
I like to create Models that are short, simple, and very flexible to an application. I have modified the way I structure the retrieve function in my Models. They no longer accept parameters for filtering data. Rather, you filter the data before calling the function. This way the method in the Model is not limited to a single functionality.
When first creating a Model for a table, make sure you implement CRUD functionality: Create, Retrieve, Update, Delete. The first Model we will create will be called accounts_model.
<?php
class Accounts_model extends Model
{
function Accounts_model()
{
parent::Model();
}
/**
* Create a new account entry in the database
*
* @access public
* @param array
* @return int
*/
function create($params = array())
{
$defaults = array(
'account_email' => '',
'account_password' => '',
'account_name' => '',
'account_role' => 'user',
'account_creation_date' => date('Y-m-d H:i:s'),
'account_last_login' => date('Y-m-d H:i:s'),
'account_last_ip' => $this->session->userdata('ip_address')
);
$params = array_merge($defaults, $params);
$this->db->insert('accounts', $params);
return $this->db->insert_id();
}
/**
* Retrieve accounts from the database
*
* @access public
* @return array
*/
function retrieve()
{
$accounts = $this->db->get('accounts');
return $accounts->result();
}
/**
* Update accounts in the database
*
* @access public
* @param array
* @return boolean
*/
function update($params)
{
return $this->db->update('accounts', $params);
}
/**
* Delete accounts in the database
*
* @access public
* @param string
* @param string
* @return boolean
*/
function delete($column, $value)
{
$this->db->where($column, $value);
return $this->db->delete('accounts');
}
}
/* End of file accounts_model.php */
/* Location: ./application/models/accounts_model.php */
As you can see, I have used Active Record throughout this Model. Active Record is a great library provided by CodeIgniter which allows the creation of database queries to be easier to do. I use it in every application and website I create and I am very happy with it.
The Model should be self-explanatory but, if you have any questions, leave a comment below. It would be much appreciated.
Concluding Part 1
The beginning of our User Management System is now complete. So, what’s next? For the next couple weeks, we will continue building upon our User Management System. We will create an administration area where we can create users, delete users, update user info, etc. Then, we will create a place to give users access to our site or application by logging in.
Check back next week for the next additions!
Reader Comments (12)
Even though I’m already pretty experienced with CodeIgniter and have my own user management systems built where necessary, I’m looking forward to seeing where you go with this. Never know where you might pick up a tip or trick from.
Also, did you happen to forget to include any parameters in your Delete function? Right now it will just effectively delete everything from your accounts table, and I can’t imagine a time when you’d need that when dealing with user management.
Hey Eric!
I am looking forward to hearing from people about what they would do differently, what they agree on, disagree on, etc.
I thought the Delete function would come up eventually! haha. I did intentionally leave it out so the Model would be simple (just CRUD functionality) and flexible. Currently I would do query filters (using Active Record) before calling the model. Like so:
It seems like the Accounts Model is useless, right? Why do that? Well, what if the person creating the admin wanted to delete the account based on the account_name or account_email? They would do this:
Just a couple examples of my thought process. What do you think about it? Do you think it’s unnecessary? Please share! I love to hear other ways of solving problems.
id say your WHERE statement belongs in the model myself
I can understand your logic behind wanting to do it that way. I wouldn’t personally, for these two reasons:
1) I like keeping all aspects of the model functions within the model itself. It’s just more organized for me, and if there’s an issue it’s usually easier to track down. It wouldn’t be hard to add in the option of setting two variables in the function to ask for the column and value to compare.
function delete($column, $value){
$this->db->where($column, $name);
return $this->delete('accounts');
}
You get the idea.
2) If you have an issue with your where command, or you forgot to add it, or any other reason – you could very easily delete all of your users.
I’d also personally add in some more verification processes just to make sure I had any required params before performing DB or related functions. It’s probably a little overkill in a lot of situations, but it can help remove chances of major issues in some cases (like making sure you have some parameters when using the delete function, hehe).
Tiny error in the code I posted above (I wrote $name instead of $value), but you get the point. =P
@Eric Roberts: Can’t believe I didn’t think about that. Must have been rushing. I have added your change to the above tutorial. Thanks!
Have you looked into freak auth light validation for codeigniter by 4webby. I used that and its packed full of features. As you say though, this is for small projects. Just reading through waht freak auth did toook about a week.
@matthew fedak: Yes, I have looked at the freak auth library. However, I am a fan of creating my own libraries from scratch, even if I am re-creating the wheel. I feel I get a better understanding of PHP, CodeIgniter, and what I am trying to accomplish. I would recommend every developer create there own set of libraries rather than drop in a pre-built one and figure out how to use it. Although, if I do like something a pre-built library is doing I will also add that functionality to my library.
The first article I wrote (simple login form) was created for use in small projects. This article can be used for the larger projects that require more than a few users.
What happened to part 2?
[...] next part of our user management system we will be creating are the views and css styles. The styles are going to be really simple and [...]
Have you ever thought of putting videos for your blog posts to keep the visitors even more entertained? What i’m saying is I just read through the entire posting of yours and it had been very fantastic but because I’m significantly more of a visual learner, I found videos to be significantly more helpful. well, let me know what you feel.
Hey Myrna,
Thanks for the suggestion! I have actually thought of doing screencasts for things like this. Maybe I’ll do both for each type of learner. I even thought of doing a screencast only for the longer tutorial posts and write for the short posts. We’ll see…
Thanks for reading!