and not letting it ruin your day
Usually, it's a bad idea to allow elements in a tree to be parents of themselves, because that creates problems with trying to add other children to those elements, or even listing out the tree's structure.
But, sometimes things
have to be their own parent. For example, if you want to report details of an element's children to the parent element, what happens at the top level of the tree? You can't outright exclude a tree element from the reporting, you can't create a placeholder element because that would skew the tree, and you can't add in a special case in your code base for that single item.
Well, you
could, but you
don't want to. You'd rather have a simple and elegant solution that doesn't require lots of special cases for tree levels, and that doesn't require maintenance. So what do you do?
Read more →
Using .htaccess and Cookies to manage a maintenance page
A common task in web development is updating a live server. There are many ways to do it, but some of them require downtime. Rather then turn users away, it is best practice to put up a maintenance page. But what if you still need access to the site while you are updating it? .htaccess and Cookies to the rescue!
Read more →
Which is faster? Does it matter?
When creating large strings a programming axiom has been to create an array, then join all it's pieces together at once. It is suggested this is better for memory and for speed. PHP, however, is optimized for string manipulation. Does this change the axiom? Read on and find out!
Read more →
The web design and development blog Smashing Magazine published an article today about a problem when using a Subversion checkout to deploy files to a live webserver. In short, anyone could browse to a directory on your website, and see all the source code, including database connection information. (Don't worry, at SiteCrafting we don't do this. We have a much better system.)
The Smashing Magazine article includes tips on how to secure common web servers. Here's another way to secure a site using two simple htaccess rules.
Read more →
How to get the calling function in PHP

PHP has great debugging functions. By wrapping one we can find out who the caller of a function is. This blog entry gives a code snippet that returns the name of the function who called the current function by looking at the debug of the stack.
Read more →
A quick look at an awesome function
The jQuery function $.closest() is a particularly handy function when doing DOM manipulation. I'll discuss it's power along with an example of it's use.
Read more →
Make jQuery UI Widgets Attach Dynamically
jQuery has some awesome widgets, but all of them need to be attached after an element is added to the page. With some quick changes, your widget can be added dynamically to any element using $.live().
Read more →
JQuery Saves The Day
From time to time, we need to put default values into input fields, and have those values go away when a user clicks on that field. There are a few ways to make that happen. I was working on a new project, and came up with a quick way to setup any number of default-able fields. There are two simple steps.
1) Add class="default" and value="Some default text..." to your field. The value can be anything.
2) Include this little jquery function on the page.
$(function() {
$('.default').each(function () {
var default_val = $(this).val();
$(this).focus(
function() {
if(default_val == $(this).val()) {
$(this).val('');
}
}
).blur(
function() {
if('' == $(this).val()) {
$(this).val(default_val);
}
}
);
});
});
View a demo >
A Way To Name Your jQuery Objects
This blog entry shows you how to cache a jQuery object into a variable for future use. I present a naming convention that I have been using that visually separates jQuery objects from other JavaScript variables.
Read more →
The Wonders of the FIELD() Function

One of the common needs for a content management system (
hey, that's what we make!) is some form of page ordering. Clients need to be able to manually order pages to suit their fancy, rather than relying on something arbitrary like update time or alphabetical order. For this we use a simple numeric field. On any given given page in the admin center, the user can shuffle around all that page's siblings, which are then posted and have their ordernum fields reset. Typically this is done with a query apiece, as one would expect when trying to update multiple rows with multiple different values on multiple keys. Wouldn't it be nice, though, if there were an easy way to perform this same entire action with a single query?
Read more →
Finally, a pure CSS solution!

Centering a div horizontally and vertically has always been a pain for CSS. Not any more! With this trick, you can create a centered block in no time.
Read more →
The Phantom Menace
Using intervals in JavaScript for pausing/unpausing events can sometimes cause a phantom interval which you can't control. Learn how to stop that phantom in it's tracks with one line of code.
Read more →
A new way to setup events
jQuery 1.3 has added support for live events, and it makes developing a breeze. Before, you'd have to wait until the page is completely loaded to add events to elements. And if you added new elements to the page, they would need special attention to have events added. Not anymore!
Read more →
Actions without JavaScript!
A concept of how to define actions using classes. Best part is, there's no need to know JavaScript!
Read more →
jQuery to the rescue!
Internet Explorer 6 is just too old to support all the fun CSS tricks of the modern web. The Input Type selector is one of the most problematic. I suggest a quick jQuery function to get around this.
Read more →
jQuery Namespace Workarounds

Prototype and jQuery conflict over the $ function. In the entry, I will show you how you can start to include jQuery code in the an environment that is already Prototype heavy.
Read more →
It's not as bad as you'd think
Sometimes, you just need a way to GOTO. Here is a little trick that will duck out of a section of code using break
Read more →
Not as snazzy-looking as my last two, but a useful query nonetheless. One the applications we built over the years, among other things, takes a list of names and addresses (currently a little over 2600), and selects around 200 of them at random. The client has been keeping track of the alphabetical distribution of last names with each random batch, and was concerned that the apparent weighting of the list toward the beginning of the alphabet was evidence that the lists were not truly random.
Fortunately I was able to get a quick statistical breakdown of the overall list, using the following:
Read more →
Fun with ASCII graphs!

(Author's note: not necessarily actually a practical idea. But fun!)
So pictured here is a histogram of a moderately large set of random integers. Each vertical line represents the total number of entries at each particular integer. Since each number is made up of multiple random factors (10 different random numbers, each between 0 and 100, added together), the distribution tends toward a bell curve.
So how did I build the graph? Excel? PHP? Nope. Just a MySQL query.
Read more →
Finding spikes in your normal data

With most large sets of data, especially numerical data, statistical analysis plays a key role. You can't be bothered to look at every record yourself; that's what computers are for.
One useful tool in any statistical analysis is the identification of
outliers. Assuming you have a
normally distributed set of data, outliers can help to identify user error in the data entry process, or genuine spikes in the data. Once found, these numbers can be set aside for closer analysis or eliminated to normalize the data set.
There are many different methods for identifying outliers, with varying levels of rigor. Here I'll just demonstrate one of the simplest definitions: an outlier is any value greater than three
standard deviations away from the
mean.
Read more →
Fun with stored procedures pt. I
(First in what will probably be a series of blogs as we move all our projects to a replicated, MySQL 5.0 environment, and I finally get to start playing with all the useful features that come with it)Say you've got a client, Mystery Client A. Mystery Client A has hired a marketing consultant. As a part of their rebranding efforts, they have decided to refactor their company spelling convention to MysteryClientA!, for whatever reason. That's fine for replacing a few logos, but MCA has a database-driven content management system, and their name is riddled throughout the database in page content, event description, news headlines and so forth. Your job is now to sift through the entire system and apply the newly crafted spelling to the entire database. So what do you do?
Read more →
Does anyone use it yet?
I am starting an experiment to see whether the recent blog chatter about window.name is actually being used. Included is some JavaScript that you can put in GreaseMonkey to help me in my search.
Read more →
Harry Potter and the Onload Collisions
There is no other variable more fought over then the coveted window.onload. Its job is to run a function after a page has been loaded. The problem is that there is only one variable, and therefore only one function can run. Once you have set this you would think you are in the clear. That is until another script comes in and overwrites onload.
But all can be made well in JavaScript land once one of four choices is made. I give four ways to get around this problem, and suggest a way for modern browsers to be rid of this problem once and for all.
Read more →
Fun with bitwise logic!

A web app full of data is often going to be full of tables (at least on the administration end). A listing of users here, all the recently created events there. Often for readability we will alternate rows between two slightly different background colors.
This can be handled on the PHP end with a bit of math and a counter, like so:
$count = 0;
while( $row = mysql_fetch_assoc($res) ) {
if( $count % 2 == 0 )
$background_color = 'white';
else
$background_color = 'gray';
/* OUTPUT TABLE CONTENTS WITH GIVEN BACKGROUND */
$count++;
}However, it can also be done entirely in-database, via creative use of the XOR operator:
Read more →
Not just an endeavor in aesthetics!

Having recently discovered the plethora of coding fonts available online, it occurred to me that quite a bit of thought has been put into something I have always seen as rather trivial. The more I read about it, the more I have come to realize that using a font specifically designed for software development can be extremely beneficial.
Read more →
Four hilarious programming videos!
During my morning blog-scan I came across four videos that really set my day off on the right foot. And that song! Oh that song! As much as I can't stand it, I'll be humming it all afternoon today. If you're familiar with the MVC model, then these videos were made for you.
Read more →
Deleting all semi-matching rows in MySQL
One of the more recent additions to the SiteCrafting CMS arsenal is a comprehensive error logger, tracking all PHP and MySQL errors (by default... other error types can be created on a case by case basis) that occur in new sites we build. Errors are stored in our own intranet system with a timestamp, error body and a site ID (assigned to each client at a different stage of our project workflow). The table looks something like this:
+----+---------------------+---------------+---------+
| id | logTime | text | project |
+----+---------------------+---------------+---------+
| 2 | 2008-05-14 14:42:15 | A PHP Error | 1 |
| 3 | 2008-05-14 14:42:26 | A PHP Error | 1 |
| 4 | 2008-05-14 14:42:34 | A PHP Error | 1 |
| 5 | 2008-05-14 14:42:47 | A MySQL Error | 1 |
| 6 | 2008-05-14 14:42:56 | A MySQL Error | 1 |
| 7 | 2008-05-14 14:43:05 | A PHP Error | 2 |
| 8 | 2008-05-14 14:43:10 | A PHP Error | 2 |
| 9 | 2008-05-14 14:43:21 | A MySQL Error | 2 |
+----+---------------------+---------------+---------+
8 rows in set (0.00 sec)
Obviously sometimes we get duplicate errors coming through. Aside from being mere mortals who aren't always fast enough to correct an error before it recurs, one of the first stages of debugging is to try and replicate the error. These are often pretty easy to manage. It's pretty trivial to search for all matching errors, check them all, and delete them. Sometimes, though, this just doesn't cut it. Like when there are a few different errors with 10,000 occurrences apiece.
Read more →
Rock it as well, if you must

This time of year you either get hooked or get sick of everything politics. That's right, it's a Presidential election season and the 24-hour news cable channels are firing out tons of info both via your TV and online. Some worthy strides in web development practices have also come about on one news site in particular that may help political junkies get their fix anytime, anywhere.
Read more →
The TO Pattern

The Template Object (or TO) is a design pattern of my own that I developed to fill the role of the View layer in the MVC model. As you have probably figured out, the purpose of the TO is to handle everything related to the user interface. The idea here is to separate the interface as much as possible from the rest of the application, so that we could do a complete rewrite of an application without ever touching (or accidentally "breaking") the
view portion.
Read more →
A new way of solving an old problem
A nice feature of JavaScript is that functions are objects. As such, they do not need a name if they are used right away. But what if you need a short anonymous recursive function? arguments.callee becomes your new best friend.
Read more →
The DAO and VO Patterns

In this installment, we will be looking at two patterns that have been 'borrrowed' from Java. If you've had any development experience with J2EE, you are probably well aware of how handy Data Access Objects and Value Objects can be. If you haven't, don't fret! This article was written especially for you!
If you've never heard these terms before, you may be wondering why I have chosen to group them together within one article. The simple explanation is ... well you'll see. For now just accept that they go hand-in-hand, much like salt and pepper or peanut butter and jelly or .
Excited? Let's dig deeper...
Read more →
The Registry Pattern

This is the first in a planned series of articles discussing the application of various PHP patterns. If you're still getting your feet wet developing in PHP (or programming languages in general), you may be wondering what a "pattern" is in the first place. The best place to find a quick explanation is over in Wikipedia's article (which does a much better job than I could hope to do within the scope of this article).
Now, let's move on to the fun part . . .
Read more →
There are a number of reasons why you may want to capture a web user's IP address. You may want to only allow certain IP addresses to view your website, to allow only one vote per IP address, track unique clicks on links and buttons, a location of web users on Google Maps using MASHUP, and whatever else you can think of.
Below are a couple of examples to get the client's IP address in PHP and ASP.net, along with a couple of things to watch for.
Read more →
A balance of needs and time
I recently decided to try the Gridview control in asp.net 2.0. I read some documentation and decided that it would be very easy to implement. I started by following a step-by-step tutorial on creating a table using the Gridview control, which uses the SqlDataSource control. This step-by-step tutorial included details on how to add paging, column sorting, updating a record, and deleting a record. The tutorial can be found
here. I was actually excited when I got this to work and how easy it was to do. It would only take a few minutes to create a simple, paged, sortable table where a user can delete and update records right on the page. Please note that
simple is the operative word here.
Read more →
Visual Basic for ASP.NET 2.0
When developing a recent project for ASP.NET, there was a need to migrate a large number of generic functions that were created in PHP into the .net web project. For .net 1.0, you were able to add a code page that could be used for creating a bunch of functions. However, in .net 2.0, you still had the ability to add a code page, but it had to be a class. This meant placing all of our migrated functions as methods inside a class. To use a generic function, such as generateNewPassword(), you would have to first create a new object for the class and then call the method.
Read more →
When attempting to use the SMTP library from PEAR for a project, I was having problems with including the file. I kept getting a file stream error for this code:
require 'Net/SMTP.php';
I figured the problem had to be related to the include_path setting in the configuration file.
Read more →
More form, less space
Some really large forms can be a bit of an eyesore especially to the people filling them out. One thing that always bothered me was how bulbous most textareas had to be just to make enough room for a user to feel they could type what they needed. So I set out to figure a good way to clean up my forms a bit while still allowing the multi-line input of textareas.
Read more →
Yesterday I was working with a script that saves an uploaded image to a database. If you've ever seen a binary file as a string, there's a ton of gobbelty-gook that is unreadable to people. For some very odd and inexplicible reason, my script only saved the first four character's worth of data to the database, and that's not very helpful. I did some digging, and revealed a weird gotcha in the way PHP treats strings.
Read more →
The fewer the queries the better
I always enjoy trying to do my work creating web applications using the fewest number of database queries possible. It's kind of a pride thing, I guess. That and I suppose it makes to improve an app's performance and reduce the load on a server. If you're into that kind of thing. ;)
A technique I use subtitutes the temptation of using queries whose results call queries and instead uses only two.
Read more →
There's small choice in rotten apples.
Recently, I had a need to POST a form, using PHP script, to a remote url. As I started to research a solution, I soon realized there were very few limited options.
Read more →

I never enjoy finding quirks in something so seemingly simple when I'm coding but it certainly happens. The following is a tale of how I ran into trouble with a couple attributes that should be worlds apart.
Read more →
Code Soup versus Short Stories
On my way to meeting with a client, I got into a conversation about using functions in your code. One of the guys learned to write assembly first, and so his stance was that creating functions was only feasible when you used the same code more than (about) three times. That view makes a certain sense - don't deal with the overhead of creating tons of functions for stuff you'll seldom use.
I argue that you should use functions where ever possible, first because it makes code easier to generalize (and thus re-use), but also because it makes code much more readable.
Read more →
It's pretty common for PHP developers to make complex and difficult to maintain scripts, and I am no exception. I write my code in two distinctly different ways: scripts that do a whole bunch of things depending on input, and classes that do a bunch of things depending on how they are called, but from lots of different scripts. But which is better?
It's a nice ego boost for any prrogrammer to know they created a script/function/class that is really useful, and well designed, but at some point the code stops being well designed, and becomes gross. I think that point is when you have one script that displays an entire (SQL) table of data, views a particular row, edits that row, can delete that row, or can add new row to the table.
If my Software Engineering professor sees me doing that, I imagine that he'll reevalute my grade in his class.
Read more →
text, ntext, and image data types have been deprecated
How I discovered that text, ntext, and image data types have been deprecated and replaced by varchar(max), ntext(max), and varbinary(max).
Recently, I needed to perform a query to update a number of links for the Pierce Count Library website. I thought I could use a simple REPLACE() string function, unfortunately, this turned out not to be the case. In order to update text and ntext datatypes using a query you're limited to a few functions, in my case I would be forced to use SUBSTRING() or UPDATETEXT().
Read more →
Applying MySQL Wizardry to MS SQL Server
Back in the day, we worked on developing a specialty application that was basically a lead generation system with a database that stored over 200,000 records, with a potential for a lot more. The web application displayed numerous reports that calculated totals from disparate sources. We discovered that once our client began adding all their data that those reports were running slower and slower and slower.
The problem was that we had one primary query to pull the records out, then, as the code looped through each record, several other queries were needed to calculate the disparate totals. That resulted in numerous database calls that slowed the entire web application. That's when Mike discovered
MySQL Wizardry, that used the SUM(IF()) and the GROUP BY clause, problem solved.
Read more →
Something no developer wants to see...
foreach ($left_elements AS $le) {
?>
<table class="leftnav_<?=$le['class']?>">
<tr>
<td class="leftnav_<?=$le['class']?>">
<a href="<?=$le['target']?>" class="<?=$le['theme']?>"><?=$le['name']?></a>
</td>
</tr>
</table>
<?
}
Nobody wants to see that. Especially not seven different times with seven tiny variants covering seven different if conditions.
Each higher 'class' number is a deeper indentation. Apparently it's necessary for this class identification to be repeated for the table, table cell and link. Converting this to a nested list format (part of my current task) is going to be an adventure.
Well... at least it's indented nicely.
Earlier this week the brand new
Pierce County Library website officially launched. It was a pretty complex build that took a lot of effort between ourselves and the library's staff to make sure that everything worked right for the site's users. One of the more important features on any website with a large amount of content is a solid search function, and this site was no different. With over 300 pages (and still growing), a user could easily have some difficulty tracking down the information that they are looking for. So what can you do to make finding information easier?
Read more →
I've been using a fairly complicated function to grab the extension of an uploaded file. I have run across many instances where I have wanted to split up the file name from the file extension, or just find the file type. Since MIME types are not reliable enough for grabbing a true extension, I have been using this aforementioned function.
Read more →
At least it's clean code!
While I was taking some time to evaluate a 3rd-party application for a customer I took a peak at their site's HTML. I was pretty shocked when I found some very strictly organized code that contained gobs of nested tables. At one count I found a structure that was 10 tables deep! I suppose since enjoying creating clean mark-up and mostly table-less designs for the last few years I've forgotten my roots.
Read more →
Making Inserts Sucks
If you've ever created
SQL queries with
PHP, you probably know what a pain it can be to create insert and update statements. I really, really (really) don't like it. As I was working on my personal site, and exploring possible frameworks to use, I came across
CodeIgniter. They have a great database interaction library, especially the function for creating the insert queries.
Today, armed with only the descriptions of
CodeIgniter's query helper functions, I spent 20 minutes trying to duplicate some the effect of the insert and update functions. I've never seen the code, or even used it, but I didn't have to see the code to write a similar function. Both functions take a table name and an associative array of column names and values. The update function also requires a WHERE statement, and it can't be blank. This is different from CodeIgniter, and that's so you don't accidentally reset all of the passwords in the mysql users table, or any table for that matter. And then, *poof*, the function gives you a nice sql statement.
I'll never have to write another "INSERT blah blah blah" again. Yay!
Read more →
Why butter fingers break apps
Happens all the time, right? One minute you're cranking out line after line of quality code then the next it all comes to a screeching halt for no apparent reason. I immediately go into troubleshooting mode. A quick and simple redirect using a
header("Location: ...") function should pose no danger of messing up my app -- but today it did.
Read more →