Category Archives: PHP

PHP Pagination Class – Version 3

It’s been a while since the popular PHP pagination class has received any of my attention, so a few months ago I set out to re-write the class to be more up to date. This version takes advantage of both code and security updates as well as updates to PHP and MySQL. I’m also planning on moving the code over to GitHub where it should be easier to manage.

Here is the new and improved PHP pagination class for your enjoyment:

Download

See the example files for how to use. I’ll create step-by-step instructions shortly.

Demo

Note that the demo uses MySQL’s free “world” database available at http://dev.mysql.com/doc/index-other.html

  • Example 1 (basic paginated database result set)
  • Example 2 (Form variables passed via pagination class)

PHP Pagination Class Updated – Version 2

Based on feedback (and the long time between updates), I’m releasing an updated version of the PHP pagination class.

Changes

  • No more SQL errors if using the class on a query with no results (although I fail to see the point of using it on an empty query anyway, but the bug is fixed)
  • When selecting ‘ALL’ only one page is displayed, and if you are using the display_items_per_page drop-down menu, ‘ALL’ is now selected as well.
  • If a page less than page one, or greater than the total number of pages is requested, no results are displayed and the appropriate prevous/next links are disabled
  • The items per page array that populates the display_items_per_page drop-down menu is now an option that can be configured when instantiating the class. Previously this was hard-coded to the class.
  • The $high option has been removed from the class (it was never used).

Note that if you receive a PHP notice about undefined indexes that you should turn down your error reporting. This notice may be displayed when loading the page for the first time when no $_GET variables are present. The class accounts for this, however PHP throws a notice about it.

Examples

I’ve also added license info at the head of the class (CC Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0)).

Download

Narrow Minded

Recently I was checking out some code written many years ago by another developer, and as I was hacking it up to be re-used, I started wondering why he had decided to split up his lines of code so that they were very narrow. Comments, for example, that were a few sentences long ended up spanning nearly a dozen lines when they could easily exist on just a couple of lines. It was then that I noticed that he had been wrapping his text at 80 columns – in other words, each line contained no more than 80 characters. It’s been a long time since I forced myself to wrap code at 80 columns, either because what I had written was concise to begin with, or because no one else would be looking at the code and it just didn’t matter, and I had almost forgotten why people did this in the first place.

I’ve seen code wrapped at 80 columns plenty of times before, but something about picking apart this code at that moment made me suddenly ask why. What was so special about this 80 column “standard” and why was it seen throughout the programming world? When I first started out coding this was just assumed to be the way to do things but I had never fully heard an explanation as for why this was done.

As it turns out the answer lies in old technology and tradition. In the early days of coding,  text based terminal displays were only 80 characters wide, so any lines longer than 80 characters needed to be wrapped. There just wasn’t any choice in the matter. Remember that GUIs and mice didn’t exist back then and scrolling was typically done only vertically. Some people believe that the even older computing method of using punch cards, which also typically had 80 columns, is the reason for this style of coding, however while it may have influenced the design of those old terminals, I don’t believe that punch cards directly gave way to practice of coding text at 80 columns.

Now since virtually no one uses an old terminal to write code, and today’s monitors are larger and have larger display resolution than older machines, why do we still see this? The answer? Tradition. Well that and readability. While most modern code editors will let you type a single line for as long as you want, reading that line becomes a huge pain in the ass. You’re forced to scroll horizontally to the right to read the code or comment, and then scroll back to the left to get back to the rest of the code. While an 80 column limit might seem constrictive or limiting, it actually makes code easier to read, and can help you write better code by making you find ways to shrink your code down to fit in one line. Another advantage to limiting the characters per line is code comparison. By staying with the 80 column rule you can usually fit two files side by side and examine them line by line quite easily.

Oh and while 80 columns is sort of a standard, 72 and 76 column layout are also quite common, but slightly more restrictive. Personally I am lazier than I like to admit and I often don’t pay a load of attention to how many columns each line of my code takes up. But that’s being both a bit lazy and selfish. By making your code readable, it helps you and anyone else looking at it…and you just know you’re going to need another set of eyes looking at your code at some point to help ferret out a bug down the line. And while I’m no advocate for 80 columns, if you stick with a layout that makes your code easy to read why not pick something like 100, 120, or 132 columns now that most people have larger monitors? Being lazy I also don’t think that any of this should be a rule but more of a suggestion or guideline. Bottom line, once you get your code to work the way you want it to, why not make it look good and improve the readability at the same time?

Introduction to PHP’s Serialize Function

I was tinkering with a WordPress database the other day and was nosing around through some tables, looking for some statistical data which I never found, and noticed that a few of the tables were storing data in an unusual format (to me at least). Specifically one record I found looked like this:

a:6:{s:5:"width";i:250;s:6:"height";i:323;s:14:"hwstring_small";s:22:"height='96' width='74'";s:4:"file";s:72:"/uploads/2008/04/wireframes7.jpg";s:5:"sizes";a:2:{s:9:"thumbnail";a:3:{s:4:"file";s:23:"wireframes7-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;}s:6:"medium";a:3:{s:4:"file";s:23:"wireframes7-232x300.jpg";s:5:"width";i:232;s:6:"height";i:300;}}s:10:"image_meta";a:10:{s:8:"aperture";i:0;s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";i:0;s:9:"copyright";s:0:"";s:12:"focal_length";i:0;s:3:"iso";i:0;s:13:"shutter_speed";i:0;s:5:"title";s:0:"";}}

Whoa. Looked like some sort of delimited data (it is) but not in a form I recognized. Now over the years I thought I had seen my share of input that is stored in a database. Like most PHP developers I didn’t learn PHP through a class, I learned it by reading and trial and error, but I don’t remember seeing something like this before. Now some of you already know what kind of data this is while others are probably scratching your head and wondering what kind of strange delimited data this is. Isn’t it obvious, that’s an array.

Serialization

cerealAccording to Wikipedia, serialization “is the process of converting an object into a sequence of bits so that it can be persisted on a storage medium (such as a file, or a memory buffer) or transmitted across a network connection link. When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object.

Now that I’ve gotten the obligatory definition out of the way, let’s humanize exactly what we’re talking about with a real world example.

Let’s say that you have a feedback form on your website and you want to store all the feedback in a database so that you can analyze it later. Along with the feedback that visitors provide you’re also interested in storing the date and time of their visit, their IP address, and some other information. One way to do this would be to create a table where you had a column for each field in your form. Every record entered in the table would need to insert each field of your feedback form, and other data you wanted to store (e.g. IP address, time submitted), into the table with a long SQL statement. Later if you needed to change your form, say add or remove a field, then you would not only need to change your table schema, but you’d also have to alter your SQL statement. Managing the feedback data this way would also result in the database table growing quite large over time. Since you can’t insert an object or array into a MySQL database (you’ll see an error like Unknown column ‘Array’ in ‘field list’ ) it would be nice if there was another way to easily store all the values we receive, especially if the number of fields could change. So what’s the alternative? PHP’s serialize() function.

PHP’s serialize function was designed for just this sort of job. What it does is basically flatten an array or object into a string (according to php.net, it “Generates a storable representation of a value”). Using our feedback form example, we could pass the $_POST array through the serialize function, and end up with a string which we can store in our database. When the serialize function is done doing its magic with whatever you throw at it, the output is a whole bunch of curly braces and semicolons which looks similar to a:1:{i:0;s:7:"slugdiv";} and the example in the first paragraph. (Note that whenever you enter user submitted data its a good idea to run it through the PHP mysql_real_escape_string function first.) So serializing an array converts it from the array to a string:

serialize

All the array keys and values are preserved by the serialize function so that they can be reconstituted later. If we use serialize() to store our feedback form data, we can eliminate all the fields in our table and just keep the one field for our serialized string. That’s a big space saver. Plus, by storing just the one serialized string in our database we can greatly simplify our SQL statements and no matter how many times we change our form, all the array contents will neatly fit in our table without it or the SQL statements needing to be modified.

Right about now you might be asking, well that’s pretty cool but how do I get my data back out of the database when I need it? No need to fear, just use unserialize() to reverse the process. If you assign the output of unserialize() to a variable then that variable will be a clone of what the original input was. Unserialize will keep all the keys and values of our feedback form’s $_POST array so that they’re instantly available just as they were when they were first created. For example, if you retrieved a serialized row from our table, we could run it through the unserialize function and assign the output to a variable: $reconstituted = unserialize($row['feedback']);.

Sounds great, so what’s the down side? Well by storing our feedback form data in serialized form in the database we lose the ability to use SQL to manipulate the data. So if we wanted to run a query that returned only the email addresses for all of our feedback, then we’d be out of luck. We’d have to use PHP to pull all the data out of the table, unserialize it, and then search through it using PHP instead of MySQL. If our data was stored in unserialized form, where each column corresponded to a field in our feedback form, then searching through and manipulating the data would be far faster and easier with MySQL. So knowing when to use serialization is important. Storing user preferences, or say attributes for an image (like WordPress does), is a perfect use for serialization. If you’ll have the need to search, update or delete parts of serialized data, or otherwise manipulate parts of the data you’re storing, then serialization may not be the way to go. However if you simply need to store arrays or objects in a database so that they can be pulled out in their entirety later, it may be the perfect solution.

PHP Pagination Class

Some of you have asked for more examples of the PHP pagination class I wrote, specifically the same examples I’m using here on the site. The database comes from
MySQL’s free example databases available at http://dev.mysql.com/doc/#sampledb (my example uses the world database). The two examples I use here can be seen at
http://www.catchmyfame.com/paginator/example.php and http://www.catchmyfame.com/paginator/example-form.php. You can download both PHP files, along with the
pagination class in a zip file. Don’t forget to grab the sample database from MySQL.

Note that the MySQL site seems to be undergoing some updates and the sample databases are hard to find. If the above links don’t work try http://dev.mysql.com/doc/index-other.html