skip to content

Using PHP for random, non-repeating numbers

July 30th, 2007

Need a series of non-repeating but random numbers? For example, random images from a gallery or portfolio screenshots? Let me save you some time:

$numbers range($min$max);
shuffle($numbers);

$random_1 $numbers[0]// first random number
$random_2 $numbers[1]// next random, non repeating
$random_3 $numbers[2]// next random, non repeating 

Normally I wouldn’t blog about something like that, except that I just spent 20 minutes using rand() to generate a random number, then saved it into an array, then ran an in_array() to look for it, and start the process over.

It wasn’t until I was about 15 minutes into it that I thought to myself… “What on Earth am I doing?”.  Then stubbornness kicked in and I tried to finish my monstrosity, then I finally re-evaluated my strategy.

Funny, because I’ve never used shuffle() before for anything, so my brain could only think of commonly used array functions like sort() and asort() (and of course, your favourite and mine… array_intersect_uassoc() - which I freely admit to only just now looking up to discover it exists).

Why are we sometimes driven to code the most complex solution possible, and worse, even when we know it is utterly involved and inelegant, we still drive to make it work, “just to see it working”?

Changing MySQL default character sets to UTF-8

July 16th, 2007

With BambooInvoice 0.8 about to be released, and the big new feature being internationalization, this has brought to light a few issues with character sets, particularly as they apply to the database.  It seems that MySQL, in its default configuration, and especially with popular installers such as XAMPP, MAMP and WinLamp, usually sets the default character set as “latin-1”.  For English, this is a complete non-issue, and things work as they should, however if you try to set other languages, characters such as ö, ä, and ï (as well as dozens of others) tend to load to the screen as garbage.  This is often compounded by the fact that the webpage itself might be in a character set such as UTF-8, which is very “international friendly”, and so things appear to work on the “front end” but as soon as data goes into a database and back out… its borked.

The solution of course is to simply use UTF-8 as the character set for your database.  The problem though, is that many of us have legacy data in MySQL, and as mentioned above, the data started its life as latin-1.  This is particularly true of BambooInvoice, as the installer I set up did not specificy any character set, so nearly everyone’s databases (my own included) is in latin-1.

I’ve found 2 good ways of converting an existing database from latin-1 to UTF-8.  Here’s how you can convert your data…

alternating comment styles

May 22nd, 2007

I've been asked how I acheive the alternating comment styles in my blog. When this blog was custom built on CodeIgniter, I used alternator() in the string helper. It looked like this:

<?php foreach ($post_comments->result() as $comment): ?>     <div class="comment<?= alternator(' even', ' odd');?>        <p><?php         if ($comment->comment_author_website) {             echo anchor ($comment->comment_author_website, $comment->comment_author_name);         } else {             echo $comment->comment_author_name;         }         ?> wrote on <?= date ('F jS, Y @ G:i', $comment->comment_date);?></p>         <?= $comment->comment_body;?>     </div> <?php endforeach; ?>

When I switched my blog over to ExpressionEngine a few months ago, I decided to change my strategy a bit, and use the tools EE makes available for me. Specificly, the {switch} tag for comments.

{exp:comment:entries sort="asc"}     <div class="{switch="even|odd"}">         <p>{url_as_author} wrote on {comment_date format="%F %d<sup>%S</sup>, %Y @ %G:%i"}</p>         {comment}     </div> {/exp:comment:entries}

I find it ever bit as intuitive as pure PHP, and I love the convenience shortcuts like {url_as_author} (Hyperlink pointing to the URL (if it exists) with the author name as the link title. If the URL does not exist simply the name is returned).

I still have all the legacy code (of course) from the custom written blog app, and while I don't want to release it wholesale, I'd be happy to field any specific questions about any part of it.

Web Application / CodeIgniter face to face course in Toronto

April 22nd, 2007

Some of you who know me, know that I roughly split my professional time between development and training.  I’ve been lucky to have some success over the years, and I’ve managed to build up a pretty good rapport with local universities and colleges.  Like any relationship, after a while, your input starts to be highly trusted, and I’m fortunate to find myself in this situation.  It has put me in a position recently to get a new course on the books at area schools, I’ve called it “Building a Web Application: Concept to Completion Workshop”.  Why do you care?  It’s a course on how to build a web application using CodeIgniter and other “web 2.0” technologies.

My vision was to create a course for working web professionals who want to explore the ins and outs of CodeIgniter, professional web 2.0 application development, and/or have a vision for a web application, but don’t know how to make it a reality.  This is not a course to teach you PHP, and javascript - I expect that you already have intermediate knowledge of that - and preferably you’ve built a few things with PHP/JS before, and now want to get ambitious.  I will assume though that you’ve never used CodeIgniter before, and on that front we’ll start at “ground zero”, and quickly build our way up.

We’re going to plan, wireframe, mockup and build a full-on, functional web-application.  I’m not sure what exactly yet, but it’ll be something practical, and not a complex example of “hello world”.  It’ll be data-intensive, and I’ll probably release the final product under the GPL, just like BambooInvoice

The first run is going to be in North Toronto at Seneca College’s Markham Campus.  If I get any interest from around Hamilton, I also have permission to start up a course at McMaster University.

Inspired by Lightbox: Anatomy of a Modal Window

April 11th, 2007

Ugh... that just might be the worst title I've ever written...

For a "ultra-top secret"™ web application I've been working on, I need to take all focus away from the browser screen, and allow/force the user to interact with a window before being able to continue. Commonly, these are called modal windows, and gained some credibility for having practical uses with Lokesh Dhakar's wonderful Lightbox script (incidently, I use a variation of it on this script on DerekAllard.com).

There are many variations of modal windows running around, but I wanted a simple, unanimated "overlay" would would require a user's interaction, so I set about to build my own. The first thing I needed, was an alpha transparent div to sit on top of the whole screen. I stole was inspired by Matthew Pennel's great article on Easy Cross Browser Transparency, and began building from there. The ultimate alpha transparent solution I chose was a pure CSS base.

Not so useless! image_to_text() as a CAPTCHA

April 10th, 2007

This entry is guest-posted by CodeIgniter programmer Alexander "Iksander" Springmeyer, who contacted me about a unique use of my "Most Useless CodeIgniter Helper Ever". I've asked him to write up a few words, that I present here for all. My sincerest thanks to go Alexander for looking for new ways to implement old ideas, and for teaching an the old image2text() dog a new trick!
-Derek

Some time ago I happened across Derek's blog post on the 'useless' image2text helper he had created. Despite all the "it is useless" comments in the entry, I felt it had powerful possibilities offered by its application in my Sentinel re-write and upgrade of the Freak Auth light authentication system (by Daniel "danfreak" Vecchiato). [editors note: if you want to, you can read a very long and detailed account of its evolution.]

I was inspired to use it for a CATPCHA. Here's how did I do it?

Flash : Save and Compact

March 18th, 2007

Just a quick tip for those of you working away in Flash. You've probably noticed that the source fla files get really big, really fast. In fact, Here's a fun little exercise for you.

  • Create a new, blank .fla file and save it.
  • Note the filesize.
  • Add a bunch of sound files to it, some components, a couple symbols... now resave, and note the new file size. It should be bigger (d'uh!)
  • Now remove all that crap. Resave, and note the new file size.

Your instincts would tell you that since you removed all that information, that the file should be smaller, but in fact, its the opposite...

Code Igniter in the Real World : Part 2

February 27th, 2007

I posted earlier about an article that James Nicol had up on this blog.  The long awaited (well, long awaited for 6 days) article is now up, Real world apps with CodeIgniter: part II.  Clever title!

He delves deeper into the black art of Code Ingiter, and discussing integrating with third party systems, validation, and my favourite understatement of the week.

Before we even went live the clients came back asking for more features...

<sarcasm>What!?!  That hardly ever happens!</sarcasm>

At any rate, its a great read, and I hope James keeps writing!

Code Igniter in the Real World

February 21st, 2007

Code Igniter programmer, and good friend, James Nicol has written up a wonderful summary of his experience using Code Igniter in a production environment that he's called "Real world apps with CodeIgniter: part 1". His company developed a scheduling and logisitics management application for one of the candidates for the next US federal election (he isn't saying whom yet). His solution included building in table relationships, dynamic PDF generation, AJAX and javascript effects and CI used in a real-world app.

Finding the Second Highest Value with SQL

February 12th, 2007

For a project I'm currently working on, subscribed users get up to the minute most current information (as outlined by a date field in MySQL).  Unsubscribed users get the information still, only it is a day behind. 

Due to the way the information is going into the system, there could be multiple entries for one date, and then no entries for a few days, then new, etc.  Basically, the information cannot be predicted by the application.  Retrieving the most recent date is trivially easy with a MAX command, but there is no "almostMAX" command, so I found myself staring at the screen wondering what the most efficient way to approach this was.  Here's my solution:

SELECT * FROM table GROUP BY dateIssued ORDER BY dateIssued DESC LIMIT 1,1

Fortunately for me, LIMIT accepts offsets, and I can specific to grab only the second entry.  If you can think of a more elegant way to do this (or heck, if you just want to comment), please leave a note below.

 <  1 2 3 4 >

Derek Allard

I'm Derek Allard, a programmer, author, and award-winning instructor. I'm also Technology Architect at EllisLab, and the programmer behind BambooInvoice, a simple, Open Source, web-based invoicing application. [more about Derek]

Categories