It’s been a while

February 22nd, 2010 Chuck 2 comments

My last entry is dated January 12, 2010… hah! I’ve been too busy with work to write about anything in a while.

Many of my more recent entries were about my computer/electronics cravings. I mentioned something about going socket AM3 but I instead ended up with a LGA1156 Core i5 setup. I also changed a lot of my computer’s components amongst other things, got a new car, bought a Nintendo Wii console. Finally, I’m planning to get myself an SLR next month (a Nikon D90).

Now that I’m on the topic of “new stuff” and “work”, I forgot to mention here that I’m now working for cr8v Web Solutions still as a PHP Web Developer. I still have the same home-based work arrangement as I did with Zallas; we also have the same work shift, migration to the new company was pretty painless as far as I am concerned.

I’m pretty much trying to enjoy the fruits of my labor while I still can, because I won’t be able to do these stuff once I’ve decided to settle down…

I hope my D90 purchase would be the last of this recent string of purchases, haha, I really need to start saving for real.

Now that I mention it, I really should set up a photo gallery section soon to make use of all this space.

New Year, New Stuff

January 12th, 2010 Chuck No comments

Hey, it’s been a while since I laid my hands on my blog. I’ve been too busy with work. I guess that’s a good thing. Yes I’m still alive, haha!

I was planning on adding new stuff here but I never got around it due to deadlines at work, but I’ll eventually get to it.

I’ve been spending much of my time coding server-side, so I figured I’ll drop my Mootools training for now and focus on cURL. When I do start messing with that, I’ll make sure to post my progress here.

The Itch – Part 2

October 25th, 2009 Chuck 1 comment

I’m looking into selling my current CPU-Mobo-Ram trio and build myself an AM3 rig. Why AM3 and not Core i7? Well, it’s kinda hard to source the parts locally, and if they are available, they’re expensive despite making compromises to the setup. I’m still planning on keeping my BFG 8800GT, and besides, the onboard Radeon HD4200 on the 785G motherboard would make a great backup video when I do intend to upgrade my videocard as well.

Anyway, I’ve decided to go with the following setup – an AMD Phenom II X4 965 cpu, an AM3 motherboard based on the AMD 785G / SB710 chipset, and 2 sticks of 2GB DDR3 memory.

I’m still trying to decide whether I should skip the Phenom 955 and go directly to 965. It’s only a 200MHz difference with the 965 costing P1,250 more (about $26).

Categories: General Tags: , , , , ,

The itch

October 22nd, 2009 Chuck No comments

It’s been a while since my last post… almost a month actually. It’s just that I’ve either been too busy with work, or enjoying work too much that I kinda neglected doing my regular stuff here for a while…

With that said, I’ve been working too much and haven’t had the chance to enjoy my salary yet… well, one of the first things that came to mind was getting a camcorder (which, actually is already happening, haha!), secondly, my computer upgrade itch.

Damnit, I’m eyeing the Samsung T260HD LCD monitor, and I’ve also been itching to upgrade my processor, motherboard and RAM.

Christmas is approaching, all in due time I guess.

My Canvas

September 27th, 2009 Chuck 2 comments

I have recently opened yet another section for my website, named “Canvas“. This is basically my testing area for my Mootools experiments.

If you’ve seen what I have so far, you might’ve guessed what I am aiming for. That’s right, I’m simulating a window-based workspace. For now the content is static but I’ll eventually fill it up with dynamic content once I am comfortable with AJAX.

That makes  3 major sub-areas of my website,

  1. My blog – you’re currently reading this
  2. TheDirtLab – a repository of my recent scripts and experiments
  3. Canvas – my window-system experiment

I might even probably open up a section for multimedia, but I don’t see it anytime soon, lol.

TheDirtLab is coming up soon

September 20th, 2009 Chuck 1 comment

It has been a while since my last entry, being busy with work and all, so I’ve decided to spend some time this weekend working on the basic framework for TheDirtLab.

I’ve already written some content for it in my past entries (scripts, that is), so at least it won’t be empty when it goes up. Hopefully I’d be able to publish them by the end of the day or early Monday.

More minor website updates

September 8th, 2009 Chuck No comments

If you’ve visited the front page recently, you’d have probably noticed the mailbox on the far right side of the lawn. This mailbox will be linked to a contact form (which I haven’t started coding in yet, haha!).

Also, I’ve made slight modifications to the top navigation bar. The menus are now semi-transparent. I’ve yet to decide if I’ll keep it that way or revert to the old solid white and gray menus.

Aside from that, I am hoping to be able to find the time to work on the other planned features of my website. Please keep coming back for updates.

How to: Insert a new field into a dynamic array

September 7th, 2009 Chuck No comments

I’ve been busy with work – deadlines and all, so it’s been a while since my last entry. For now I’ll just share a quick tip. How to Insert a new field into a dynamic array.

If you’ve been reading the code snippets I’ve been posting thus far, you’ll notice that I am doing this thing a lot. Anyway, here’s a little background on this situation.

Let’s say you just retrieved records from your database table and stored them into an associative array named $results, now you want to insert an extra field for each row but you don’t know how to to assign them since you don’t know how to walk through the array.

Let’s say you have this array:

Array
(
    [0] => Array
        (
            [user_id] => 1
            [user_name] => Chuck
            [user_level] => 3
            [birthdate] => 1984-09-15
        )

    [1] => Array
        (
            [user_id] => 2
            [user_name] => Blah
            [user_level] => 1
            [birthdate] => 2001-01-01
        )

    [2] => Array
        (
            [user_id] => 3
            [user_name] => New user
            [user_level] => 1
            [birthdate] => 2002-10-30
        )

    [3] => Array
        (
            [user_id] => 4
            [user_name] => Random guy
            [user_level] => 1
            [birthdate] => 1992-07-21
        )

)

This means, each row has the following fields – user_id, user_name, user_level, and birthdate.
Now, let’s say we wanted to create a new field named “age” and store it in the same array. Here’s my preferred method of doing this:

foreach($results as $index=>$row){
     $results[$index]['age'] = get_age($row['birthdate']);
}

Take note that to maintain the abstraction of the code, I just called a function named get_age();. Remember that there is no such function so you’ll have to code that in to make it work. For completeness sake, here’s how I’d probably do it:

// Accepts 2 parameters, $bday and $now. $bday is of
// the 'YYYY-MM-DD' format. The result is based on the
// difference between $now and $bday converted to
// years. $now is optional. If it is not supplied, it uses
// the current time. This is not exactly accurate since I
// just indiscriminately used 365.25 days in my calculation.
// To improve, I'll have to detect leap years and just
// add 1 day to that, instead of 1/4 days to every year.
function get_age($bday, $now = NULL){
     $bday = strtotime($bday);
     $now = ($now)?strtotime($now):mktime();
     return floor(($now - $bday)/(60*60*24*365.25));
}

Anyway, after doing all that, you will get this result:

Array
(
    [0] => Array
        (
            [user_id] => 1
            [user_name] => Chuck
            [user_level] => 3
            [birthdate] => 1984-09-15
            [age] => 24
        )

    [1] => Array
        (
            [user_id] => 2
            [user_name] => Blah
            [user_level] => 1
            [birthdate] => 2001-01-01
            [age] => 8
        )

    [2] => Array
        (
            [user_id] => 3
            [user_name] => New user
            [user_level] => 1
            [birthdate] => 2002-10-30
            [age] => 6
        )

    [3] => Array
        (
            [user_id] => 4
            [user_name] => Random guy
            [user_level] => 1
            [birthdate] => 1992-07-21
            [age] => 17
        )

)

As an aside, you could probably use array_walk() to achieve something similar, but this method is way simpler. I hope this has been helpful to you!

Categories: PHP and MySQL Tags: , , , ,

Juggling time zones

September 3rd, 2009 Chuck 11 comments

Handling times for different timezones is one of the usual things I had to face with every project that has in one way or the other involves the element of time.

The usual projects I work on store dates into a datetime field in the database. This means that the date must use the YYYY-MM-DD HH:MM:SS format (e.g. 2009-09-03 07:45:00).

One of the first things you’d want to do is to let the user specify a timezone setting for that user account (assuming this is in a multi-user environment, as most web applications are). You could view all the timezones using this code:

echo '<ul>';
foreach(DateTimeZone::listAbbreviations() AS $timezone_abbreviation=>$timezones){
     foreach($timezones AS $timezone)
          if(isset($timezone['timezone_id']))
          echo '<li>'.$timezone_abbreviation.' - ' . $timezone['timezone_id'] . '
          <ul>
               <li>Uses DST: '
. ($timezone['dst']===TRUE?'Yes':'No') . '</li>
               <li>Offset: '
. $timezone['offset'] . '</li>
          </ul></li>'
;
}
echo '</ul>';

You could modify the code above to create a drop-down list of the different timezones to make it easier for the user to pick a timezone (because simply writing GMT+8 or UTC+8 might be confusing for some people).

Next, we will have to convert all of our stored dates into a single timezone, for simplicity, I use GMT/UTC as a reference timezone (since it is easy to add timezone offsets to it). If you store your dates in a datetime field, you can perform the following conversion after retrieving the timestamp from the database:

// let's assume $parsedtime is the entry we have in the database
// and $offset is the timezone offset we got based on the user's settings
$parsedtime = '2009-09-15 12:00:00';
$offset = 8*60*60; // this is GMT +8
// get the GMT counterpart of the parsedtime
$unix_time = strtotime($parsedtime . ' GMT');
echo gmdate('m d Y h:iA',$unix_time-$offset); // displays: 09 15 2009 04:00AM

So that means, 12nn of September 15, 2009 is 4am of September 15, 2009 in GMT/UTC.

Let’s say we had a Calendar application, and you wanted to set an alarm for 6pm on that same day. You could do the something like the this (assuming you wrote some sort of class for this thing):

$reminder = new Reminder('2009-09-15 18:00:00','Dinner with the family');
echo $reminder->timeLeft();

Since the current date and time was 12nn of September 15, 2009, this means that the above reminder will display “6 hours left”, depending on how the timeLeft() method is formatted.

If we didn’t convert the date into a standard timezone, this will force our functions to use the server’s timezone setting and that might not be what you want.

Regular expressions in MySQL

September 1st, 2009 Chuck No comments

MySQL I’ve been using MySQL for the better part of the past 6 years so it comes as a pleasant surprise when I found out last month that it can do regular expressions within its SQL!

I’m not sure about the other databases, the last time I’ve used Oracle was around 2004-2005 during my college days, so I can’t really say if this is a MySQL-exclusive feature or something along those lines. I’m pretty positive that this isn’t standard SQL though, since we never had such lessons back in college.

Anyway, if you’re familiar with SQL and string matching within SQL, it makes use of the LIKE = '[string]' clause. Where [string] is the string to be searched for. Optionally, you could also use wildcards like _ (underscore), % (percent), [charlist] (character list) or [^charlist] (negated character list) or a combination of those to match string fragments. Unfortunately this has also been one of the major points of entry for hacking/hijacking a database-driven website, via SQL injection. Due to this vulnerability, I’ve either been using heavy data validation, or store encoded data, or at times, avoiding this altogether… but I digress.

Using regex in my SQL queries is a godsend. It helps reduce my data processing and validation overhead.

MySQL supports the use of almost all POSIX regex  metacharacters via the REGEXP or RLIKE clause (or a negation using NOT REGEXP or NOT RLIKE).

The following list describes some characteristics of extended regular expressions:

  • “.” matches any single character.
  • A character class “[...]” matches any character within the brackets. For example, “[abc]” matches “a”, “b”, or “c”. To name a range of characters, use a dash. “[a-z]” matches any letter, whereas “[0-9]” matches any digit.
  • “*” matches zero or more instances of the thing preceding it. For example, “x*” matches any number of “x” characters, “[0-9]*” matches any number of digits, and “.*” matches any number of anything.
  • A REGEXP pattern match succeeds if the pattern matches anywhere in the value being tested. (This differs from a LIKE pattern match, which succeeds only if the pattern matches the entire value.)
  • To anchor a pattern so that it must match the beginning or end of the value being tested, use “^” at the beginning or “$” at the end of the pattern.

Let’s start with the traditional SELECT ...  LIKE query. Here’s a query that selects all animals whose name begins with “ant”

SELECT name

FROM animals

WHERE name LIKE 'ant%'

The results could be something like this:

name

---------

ant

anteater

antelope

...

A regex version of that would be:

SELECT name

FROM animals

WHERE name REGEXP '^ant'

So far they look similar… but, say, what if you wanted to use a complex rule like: “select all animals whose names starts with either ‘a’ or ‘c’ and ends with either ‘t’ or ‘p’.  It would look messy if you do it this way:

SELECT name

FROM animals

WHERE name LIKE 'a%t'

OR name LIKE 'a%p'

OR name LIKE 'c%t'

OR name LIKE 'c%p'

However with regex, it is as simple as this:

SELECT name

FROM animals

WHERE name REGEXP '^[ac].*[tp]$'

Imagine if your filtering conditions were much more complex. It’s not hard to see how regexp can help with that!