MySQL joins made easy with naming! (and other mysql tricks)

In the interest of decreased overhead or a simpler bit of code it’s often necessary to join multiple arrays together from the mysql query. It saved from making a bunch of mysql calls in a loop and general is easier to work with, except for when the two tables share some common schema names, then it gets kinda messy. A php array can only have 1 item with a particular name, so if both your tables have a “name” field well ones going to write over the other. That is, unless, you do some renaming.

Lets say you have two tables, one for names and one for addresses, both of these have some common items, like an id, and lets sane a name (the name of the person and the name of the address (home, wrok, ect), along with their independent data).

If you did a simple mysql join like this:
SELECT n.id, n.name, a.name FROM names a LEFT JOIN address a ON n.id = a.person_id;

In this case, the output would be something like this:
array(
[0] => 4
[1] => John Doe
[2] => Home Address
[name] => Home Address
)

Now in this example it’s not hard to just use the numbers, But it’s easier to soo what I’m getting at when theres not a ton of fields to wade through. As you can see from the example you can only define name once, so to call the persons names you have to call it via 1. The solution to this is simple, give them all new, proper names like this.
SELECT n.id AS 'id', n.name AS 'person', a.name AS 'address_type' FROM names a LEFT JOIN address a ON n.id = a.person_id;

Those simple little AS statements are all it takes to turn a messy disorganized one into a neat one, using the above example it would now look something like this.
array(
[id] => 4
[person] => John Doe
[address_type] => Home Address
)

Makes for a much simpler fetch array does it not? This can also be used for queries that don’t have a join if you just want to do some renaming, the only reason I’ve even though of for that is when I want to use some variable variables (for small calls that I’m not running via a loop for whatever reason, there aren’t many). It turns out something like this.
SELECT c.ttl AS 'county', s.ttl AS 'state' FROM counties c LEFT JOIN states s ON c.id = s.id

After that run it through a little bit of variable variableness like $$result['state'] = $result['country']. And just like that you have an array of a state name with the country of origin in it. It’s pretty pointless but I have found a use for it when filling data to very short tables, anything more than about 4 entries might as well be done in an array (not to mention an array is easier). I guess it could be used as a way to obfuscate code (especially if you use nonsensical single letter variables) but I’ve never seen a good reason to make your work harder to decipher for the next guy.

The last little tip I’ve used to pre-formatting information, just to save yourself a little extra work, it’s somewhat limited what you can do but it can save you a line of PHP, and sometimes, well, hell you might as well. Lets say I’m sorting images in the img/ folder, and the filenames are stores in the database under the logical schema filename. A simple little query like this:
SELECT name, concat('img/', filename) FROM images

The output will now look like img/filename.jpg. I have actually found a good use for this. Pulling image names from two separate locations. One a serialize table sotred in a single tabel entry, another in a completely different table stored as just a name. Both scripts, of course, written by completely different people. One set had the image path already attached to it, the other didn’t, so all I had to do it concat the path to the ones stored in the database and then I didn’t have to worry about checking in PHP if it had the path or not, saved another if statement, although honestly I havent checked the speed of processing, so I don’t know if it’s actually faster (the code is shorter, and I like short code, look neat and tidy).

Have any tips, want some clarification, leave a comment and I’ll get back to you, clarify anything that I made extra confusing. LOL, like anybody reads this blog.

Prevent stale AJAX data in jQuery

I posted earlier about an ideal I had on preventing stale ajax data from being placed over fresh ajax data, well recently I implemented a simple method of doing this in Query.

Stale ajax data is data that you don’t want anymore. For instance lets say I have a list of cities, say 3000. I want a live filter on this list and I dislike having to press buttons (they are such a bother after all) so I write a script that will load the result filtered for whatever is in my text box every time I release a key in that box, and to keep in all simple I use the onkeyup command.

So I search for “Seattle”, a search is run for “S”, then “Se”, then “Sea” ect ect until I get “Seattle”. Each character is it’s typed. Now there are far more results for that contain “S” then there are that contain “Seattle” so naturally that search will take longer to process*. As such your page will return the “S” result before the “Seattle” result. So the script displays the “Seattle” results, then gets the “S” results and displays them instead, and in so making the search useless.

My initial ideal (even before posting the old post about this) would be to simple compare string sized, since a filter can only make the results smaller, not bigger. Although that in reality is not true, if you type the wrong character and delete it the results could then again be bigger. And the possible solution I posted before is actually a lot more work since it’s passing json variables back and comparing timestamps. This solution is the best I’ve though of, although it too has its downsides.

This solution simply cancels the previous ajax call before making the next one, the following jquery function is ran onkeyup or onkeydown.

Snipplr: http://snipplr.com/view/48097/prevent-stale-ajax-data-with-jquery/

The .abort() commands it’s what makes this work, killing off old ajax calls before making new ones. There are some caveats with this method. First, it doesn’t necessarily stop the server from processing the action (although according to the documentation it will try) so the server may keep doing it wasting cpu and ram on nothing. Second, the javascript error console (at least in chrome) sees it has an error when the .abort() happens. This doen’t cause any problems to the end user but can ugly up the console. I’d would guess though that the only people who would bother to look at the console are other programmers (because a non-programmer wouldn’t know exactly whats going on and it’s of no help to them) and they’ll be able to look at the code and see that it’s not truly an error. If you are uncomfortable with running the script with those problems theres always my previous ideal, it should be error free (but it’s all a theory I never put to use).

There’s no example for this one (although if requested I can make one).

* A simple single table search for names on even a large database would probably not have a problem, searching with a more complicated query across multiple databases and post processing those results both slow down the response and are far more common in my experience, especially since I usually don’t return json or XML but pre formatted ready to post HTML. This has the added advantage of (if properly set up) only requiring 1 script to call the data for both the initial load and any ajax loads, making future changes all the faster

Content load on Scroll with jQuery

To produce a similar effect as twitter (although for an entirely different purpose) I created a little bit of script to load additional content to ht end of the document when you scroll to the bottom. This will create the effect of the page being as long as your total content, no page switching, no linking to to other pages, just one long page.

This version uses jQuery because the site I’m making uses jQuery for a bunch of other things, I do have a complete non-jQuery version if anybody is interested. Anyways, heres the code

Snipplr: http://snipplr.com/view/47744/simple-content-load-on-scroll/

The scripts pretty straight forward, only things to note are that the current top display number is stores in a hidden input, the reason I have it set up this way is because if the user doesn’t have jquery, of the script fails to load for some reason, I’ll still know where the are so a traditional next page button will pick up where they left off. There’s also a minor bug on my phone when testing, I’ll look into it and post a fix if I find one, shouldn’t be to hard to fix with some polling (check position every x milliseconds), which, coincidentally is how the non-jQuery version works.

Example can be seen right here: http://fatfolderdesign.com/ex/scroll_load/, it’s as basic as basic can be.

Edit 07/15/2011: Having a problem getting this to work properly in Firefox? So did commenter Mihajlo, he also supplied a fix before I even had a chance to take a look. I talk a little in a new post, aptly names Content load on scroll with jQuery UPDATE but for the short version is add this bit of code, just add it or integrate it into existing code:

Snipplr: http://snipplr.com/view/47744/simple-content-load-on-scroll/

I’ve updated the snipplr post and example page accordingly. Thanks Mihajlo.