After reading Paul’s article “CSS The Star Matrix Pre-loaded“, I wanted to contribute by writing a back-end solution to the CSS effect.
Before we get into this, you will need to have PHP 5 installed and MySQL 3.23 or higher. PHP 5 allows for greater implementation of OOP (Object Oriented Programming) than its predecessors.
Step 1: Analyze the Project
The first step is always the most crucial, so it should take some thought: What do we want to achieve, and how detailed do we want to get? All of these are questions that should be asked prior to any coding or any development work.
What do we want to achieve and how detailed should we get?
In this project, we want to use Paul’s CSS technique to build a fully functional rating system. Ideally, one that does not require any administration. Everything is automated by pasting a segment of code written in PHP onto a page.
Secondly, we want to ensure that only one IP Address can rate each unique item. Therefore one person isn’t repeatedly clicking on ’5 Stars’ to throw off the rating average. Now granted, ensuring a single IP Address is used in rating isn’t fool proof. As those with dial-up connections will likely have a different IP address every time they reconnect, we have to remember our first goal, “does not require any administration!” No administration means no username and passwords to be assigned.
What about cookies? Glad you asked; I did think of using cookies to do the tracking, but I figured that would be much easier to overcome than basing it on IP address. It has become easier to clear the privately stored data in our modern browsers and thus cookies could easily be foiled.
Finally, we want each user to be able to add new ratings without having to insert anything into a database table. Simply put, the HTML components built should derive the rating data for us. I’ll clear this up later, but you should be excited to know that when we are done you will only need to copy and paste code and the new rating entry will be ready for use. Nothing more is required.
Step 1 Recap:
In step 1, we answered the questions “What do I want to achieve and how detailed do I want to get?” The answer can be summarized in these points.
- Use Paul’s CSS Star Matrix technique.
- Log the Ratings by IP address to ensure no IP address can rate the same item twice.
- Update the Rating seamlessly for the user to see the new average rating.
- Make it easy to add new items to rate.
Step 2: Designing the Database and Table
Step 2 is designing the storage facility to keep our information. There are a few questions to ask yourself when designing a table like this. What information do you plan to hold in it? How do you plan on using the data?
What information do I plan to hold in the table?
Below is the list of the data we plan to keep track of:
- Item Name
- IP Address
- Date Rated
There won’t be much use immediately for Date Rated, however, it could be used in the future to build any reports on when each item was rated.
How do you plan on using the data?
Each item you plan to keep track of should ALWAYS have a use, whether it be immediate or in the future. For example, Item Name, IP address, and Rating will all be used immediately within this application. The Item Name will describe the item being rated, the IP address is the IP address of the person rating the item, and Rating, is course their rating for the specific item.
Date Rated is there for a future use. It has no immediate use, primarily because it is outside the scope of this project, but as I mentioned before, it could be used to generate reports in the future.
Step 2 Recap:
Here we defined what we will be tracking, how it will be used, and whether it has immediate or future use. Item Name, IP address, and Rating all have immediate use — only Date Rated is considered future use.
Step 3: Building the Database and Table
You can opt to create a new Database or use an existing Database; the option is yours and will have no impact on this application. For those wanting to create a new Database, you can use the following MySQL query (replacing the word ‘ratings’ with your database name):
CREATE DATABASE 'ratings' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Nothing special about the Database creation, as all of the little details are found in the table. The table will hold all of the information we described in Step 2 above.
CREATE TABLE `rating` (
`item_name` VARCHAR( 20 ) NOT NULL ,
`ip_address` VARCHAR( 15 ) NOT NULL ,
`rating` TINYINT( 1 ) NOT NULL ,
`date_rated` DATE NOT NULL ,
PRIMARY KEY ( `item_name` , `ip_address` )
) ENGINE = MYISAM ;
Notice that the primary keys are “item_name” and “ip_address”. This is to help ensure that no “ip_address” can be used to rate the same “item_name”. Also notice the lengths of each item. Item Names are not allowed to be more than 20 characters. If you want to have Item Names that are longer than 20 characters, you will need to alter the above statement with the length you want to use (up to 255).
Step 3 Recap:
We defined our Database and table so the rating information can be stored. We set the “item_name” and the “ip_address” columns as our Primary Keys to ensure only one IP address can rate each Item Name. We also defined the max name length for Item Name as 20.
Step 4: Writing our Rating Class
Strong OOP skills are something to never overlook, as they provide you with clever ways of extending your work in the future, plus they focus entirely on being reusable. With that said, you may remember my previous articles “OOP in PHP from a .NET OOP Perspective: The Error Class” and “OOP in PHP from a .NET OOP Perspective: The Database Class.” These two articles are going to be used in this project as well. The Error Class will handle any Database errors we might have, and the Database class will handle the Database connection, Query Execution, etc.
To go any further, you will need to download the following file: RatingSystem.zip
After it has downloaded, extract the contents to your computer. You should see a ‘RatingSystem’ folder. This folder is our example application, go ahead and browse to the RatingSystem > classes folder.
Open the rating.class.php file in any editor. This is the class that will be used to output the rating information to the page and record a rating by a user.
Now I won’t get into all of the code here (you’ll have to read those other articles), but I will point out a few things.
- The first thing you should notice is the OutputRating method. This method is what loads the CSS technique written by Paul. If you look at lines 31 and 44, you will see his technique used. I also made a few modifications to it (of which I hope he does not mind, but I will describe those later).
- Next find the RateItem method (approximately line number 66). This method writes the user’s rating to the table. So if you changed the table name, you will want to update the table name in this method as well.
- On line number 111 is the CalculateAverageRating, this method calculates the average rating of an item within the MySQL statement. Again, if you choose a different table name than described in this article, you will want to update this statement to reflect that change.
- Finally, I want to point out line number 170, the CheckRatingsByIp method. This is the last place you may have to update the table name if you did not use ‘rating’.
Step 4 Recap:
I provided you with the files to run this rating system and gave key pointers on where the table names may need updated if you opted to use a different name.
Step 5: Setting the Database Connection
To set the database connection open the “include.all.php” file in the “classes” folder. Notice the line:
- Database::Initialize("mysql", "localhost", "3306", "ratings", "username", "password");
Replace “ratings” with your database name, username with your database username, and password with your database password.
Once finished, save the file.
Step 6: How to output the Rating information to your page
To display the rating information on your page, you will need to do four things.
- Place the following snippet at the top of your file (for an example, look at ‘rating-example.php’ in the RatingSystem folder).
- Next you need to have the following in your <head> tags:
<link type="text/css" href="styles/rating.css" rel="stylesheet" media="all" />
This code is what sets the stylesheets, AJAX calls, etc. within your page.
- Next, find the location you want to output your Rating Stars and paste this code:
- $ratingData = Rating::OutputRating('demo');
- if (Error::HasErrors())
- echo Error::ShowErrorMessages();
- echo $ratingData;
- Finally, end the page with the following code:
Replace the word ‘demo’ with the name of your Item. If no errors occur, you should see the 5 stars not lit up when you run the page, otherwise, you will see the error messages that occurred.
Step 5 and 6 Recap:
In Step 5 and 6 we entered the Database connection information, and we pasted our code to show the Rating System for a specific item.
That’s it! There isn’t anything else needed to get this working. All you have to do is copy the same snippet of code wherever you want it to appear on your page. You can have one item to rate on a page, or you can have 10. Just give them all unique IDs and they can all be on the same page.
Even though you now have a working Rating System, allow me to give you one last walk through of this system.
Crash Course Walk-Through
This walk-through will be based on the “rating-example.php” file from the top-down, not necessarily in processing order.
When your page is loaded, the “classes/include.all.php” file is loaded which establishes your Database connection, initializes the Error class, and allows the Rating class to be used.
Next the Rating::OutputRating is called to show the rating details of ‘demo’. If an error occurred our error messages are shown, otherwise, it will display the stars lighting up the current rating.
Once the processing is finished, the user will see the page generated.
When the user hovers over a rating that they have not rated before, the stars light up appropriately.
Finally, when the user clicks a star, it is recorded and the average rating is shown to the user with green stars. Note that even if the user hovers over the stars, they will not light up because they have already cast their vote and rated that item.
Now this is where I altered Paul’s code. I created a new class called ‘rated’ (found in the “styles/rating.css”) that does not contain the hover effect. This way if the user already rated an item, they do not the see the hover effect for the item they rated.
When the user clicks on a star, an AJAX event is sent, the rating is calculated, and then the information is returned in a Name/Value pair. For example, it might return: “item=demo&classes=rated threestar”. Simply put, it means the user clicked on the ‘demo’ item, and the new classes to use on that item are ‘rated’ and ‘threestar’. The class “rated” defines the user has rated that item, and no longer provides the hover effect, and the class “threestar” is the average rating for the item, so it is to light up three green stars.
That ends the task of providing a functional Rating System using Paul’s CSS Star Matrix Pre-Loaded technique. I want to thank Paul for the excellent CSS work, and hopefully I have done it a bit more justice by adding the back-end functionality.
Feel free to leave any comments, remarks, questions, etc. as I will be happy to answer them.