Feed on
Posts
Comments

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.

jQuery Panel Gallery Plugin 1.2

I’m happy to announce the release of version 1.2. This version adds the ability to pause the transitions simply by placing your mouse over the image as well as specify an amount of overlap in terms of the time of the section transitions.

The best part of this plugin is that not one image needs to be sliced or edited to work with it. Next, you can choose the direction in which the transition occurs from left to right, right to left, top to bottom, or bottom to top – now for each image individually. You can set the initial delay before the transitions begin, set the transitions to loop or stop after the last image, set the time it takes for each panel to appear, and set the delay between the images. Phew.

Download

Download jquery.panelgallery-1_2.js

What’s So Great About this Plugin?

  • No slicing or editing of the images is needed
  • It’s just 8 KB
  • Each image can have its own fade direction
  • The gallery can be set to pause on mouseover (new)
  • Section transition timing can be set to overlap (new)
  • Easily configurable
  • Reusable on multiple containers

How to Use

First, all of your images should be the same size and wrapped in a containing element
(I recommend a div) which must have an ID. Any images will work, however transparent images aren’t recommended. Finally, your container element should be positioned (e.g. relative, absolute, etc.). The container needs to be positioned otherwise the images within it won’t end up in the right spot on your page.

<div id="container" style="position:relative">
	<img src="image1.jpg" alt="image 1" width="500" height="250" />
	<img src="image2.jpg" alt="image 2" width="500" height="250" />
	<img src="image3.jpg" alt="image 3" width="500" height="250" />
	.
	.
	.
</div>

All images *MUST* have the width and height declared otherwise the plugin won’t
work in Safari, Chrome, and any other webkit-based browsers. Also, all images should
be the same size. You can mix various image formats like Gif, Jpg, and Png, however
transparent images aren’t recommended.

To use the plugin you’ll need to have a copy of jQuery, or point to jquery on Google, and the plugin. Place the files on your site and link to them:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.panelgallery-1_1.js"></script>
<script type="text/javascript">
$(function(){
	$('#container').panelGallery();
});
</script>

Finally, while you don’t have to specify any directions for the fade (the default direction is left to right), you can give each image it’s own direction. To do this, add the name attribute to the image and specify either (lr, rl, tb, or bt). For example:

<img src="image2.jpg" alt="image 2" name="bt" width="500" height="250" />

That’s it! You can apply the panel gallery to any number of elements on a page.

Options

The following options are configurable:

  • sections – the number of panels to divine each image into (default: 3)
  • imageTransitionDelay – the time (in milliseconds) to pause between a
    completed image and the next image (default: 3000)
  • startDelay – the time (in milliseconds) to pause before beginning the first transition (default: 2000)
  • sectionTransitionDelay – the time (in milliseconds) to pause between each section of an image (default: 700)
  • overlap – the percentage of the sectionTransitionDelay option a section should wait before beginning (0 to 1). For example, if the sectionTransitionDelay is 1000 milliseconds and the overlap is set to .75, then at 750 milliseconds the next section transitions will begin. If you want a section to fully complete before the next section begins, set this to 1. (default: .75)
  • enablePause – whether or not to pause the animations when the mouse is placed over an image (default 1).
  • repeat – whether to endlessly repeat the series of images (default: true)
  • direction – the default direction of the transitions: “lr” (left to right), “rl” (right to left), “tb” (top to bottom), and “bt” (bottom to top) (default: “lr”)

Options are added when calling the script:

$('#container').panelGallery({
	sections:5,
	imageTransitionDelay :3000,
	startDelay:5000,
	sectionTransitionDelay : 700,
	repeat:false,
	direction:"tb"
});

Enjoy!

Demos

I’m working on a complete redesign of a site that’s been unchanged for about six years now and among other things, jQuery is being used in the project. I was tinkering with the contact form on this site and was thinking of the bazillions of forms I’ve seen on the web, and how when it comes to forms, contact forms are usually the most basic (although that’s not always the case). Fortunately for me, it is for this form. All that’s needed here is the visitor’s name, email and their comment (all required). Plus a CAPTCHA but that’s not going to change for the redesign. So I was thinking, how could I make this form a) functional (i.e. easy to use) and b) unique? Since this form is pretty basic there wasn’t a whole lot of room to create something that would be useful as well as interesting.

One thing I like to see in forms in general is default text that disappears when a field is clicked on. This tells the visitor what type of input is expected without getting in their way. The most basic JavaScript code would do this with a call to the onfocus event which would clear out the contents of the field. Nothing new. Better code would replace the default text if the visitor leaves the field (onblur) without entering anything. So I set my sights on coming up with something different to accomplish the same effect. Here’s the result (note that the email field has an easing effect applied to it):

As you can see, the default text here smoothly animates out of view once the field is focused on (via keyboard or mouse). Turn JavaScript off and the form works perfectly; however the effect no longer exists, so it also degrades without a problem. Note that I’m not entering a textual default value for the various fields and then deleting the text with jQuery because if the visitor has JavaScript disabled (both of you) then they would have to manually delete the default text, which is more annoying then helpful.

When the user leaves a field, the default text doesn’t return if they have entered something. However if it’s blank, then the default text slides on back in. Unobtrusive, eye-catching, and unique.

All of this is accomplished by manipulating the background image of each text field. jQuery 1.3.2 can animate the background image of an element horizontally (on the x axis) but not vertically. A nice plugin by Alexander Farkas can handle this in case you want to change the effect to look like this (here the comments field has a different easing effect applied to it):

When we focus on a field we slide the background image out of view, and when we leave the field we check the length to see if it is empty in which case the image needs to be moved back to its original position. The typical JavaScript technique that creates or deletes a text field’s default text usually also needs to check to see if the current value of the text field matches the default text since you don’t want whatever is in the text field to disappear every time the field gets focus. Imagine if you entered your name in a field, realized you misspelled it, then clicked back to correct it only to have the whole thing disappear. We don’t have to deal with that scenario here at all since we only check the length of the text in the text box on the onblur event and don’t care about what was entered as long as something was entered. I’ll leave data validation for PHP on the server side for this form. Come to think of it, this method could probably be extended to highlight required fields and perform some basic error checking.

WordPress, the web’s best blogging tool, holds WordCamps which are “informal, community-organized events that are put together by WordPress users like you. Everyone from casual users to core developers participate, share ideas, and get to know each other.”

I’ve been using WordPress casually for a couple of years now and recently saw a blog posting on their site announcing that they were holding a contest to design the logo for the next WordCamp in New York City. Being from New Jersey I couldn’t resist, so I put together a submission and I lost! Well sort of. In the end I, and four other WordPress lovers came up with very similar subway sign ideas that ended up garnering the most overall votes. The judges were so taken with these submission that they declared all four of us winners. Our designs will be used on a variety of materials to market the event.

See http://2009.newyork.wordcamp.org/2009/09/08/logo-contest-winners/ for more.

The design I submitted was:

Technology Importanceometer

Communicating in today’s busy, web-centric world gives people more choices than ever in how they can communicate with each other. Use the scale below to determine how important you are to someone communicating with you. Methods are listed in order from most to least important.

  1. Face to face – the most important way to communicate. Nothing says you’re important more than a face to face meeting.
  2. Phone call – When face to face communication isn’t possible due to distance or time, the next best option is a phone call. A plane ticket was out of the question but long distance fees weren’t.
  3. Email (sent directly to you) – Sometime cost matters. When you don’t justify the cost of a stamp or waiting for the post office to deliver a message would just take too long, there’s email.
  4. Letter – Taking the time to hand write a message and cough up 44 cents for a stamp shows that someone values you, although the fact that it will take several days for you to receive it slightly reduces your importance.
  5. Instant message – I need to tell you something, however it’s not important enough for me to fire up my email program nor is it important enough for me to spell check what I’m writing, so I’ll send you an instant message instead. I also hope you weren’t expecting an attachment.
  6. Text message – I’m holding in my hand a cell phone, a device which is capable of the number two most important form of communication, however I decided against calling and instead chose to send you a short text message. My thumbs are willing to hunt and peck out some message that won’t be spell checked nor grammar checked, and will probably contain idiot shorthand like “ur” and “cul8r”, however they aren’t willing to dial your phone number so that I can use my voice to actually talk to you. Alexander Graham Bell spins three times in his grave for every text message you send.
  7. Video/Teleconference – I was required to tell a bunch of people something all at the same time. No one merited a face to face meeting and calling each person individually would’ve been waaaay too much work.
  8. Email (cc’d to you) – This message isn’t even really for you but I thought I should cover my ass and let you know what I was telling someone else. Read this if you’re bored.
  9. Facebook – When you want to share information with a bunch of people you may or may not know, and don’t care about enough to tell directly, write it on Facebook. Sharing information by using Facebook is like sending out a holiday newsletter detailing what you’ve been up to all year – only more often and with less importance.
  10. Twitter – The least important, and most narcissistic, method of communicating, Twitter says it all. As long as it’s less than 140 characters. Tweets have all the value of a fortune cookie message and are roughly equivalent to writing something on the wall of a bathroom stall. You don’t really care who reads it and almost no one gives a damn.