The Elusive Bug

November 26th, 2005

Congratulations to me, I just wasted an hour debugging a PHP script.

Illustrative code to summarise:

< ?php
  $var_SQL = "SELECT * FROM example WHERE 1";
  $var_SQLResults = mysql_query($var_SQL) or die ($var_SQL."[E]".mysql_error());
	
  while ($var_Array = mysql_fetch_assoc($var_SQLResults));
  { //: While loop
    echo "Inside while loop - ";
    print_r($var_Array);
  }
?>

The results:
This code would echo “Inside while loop - ” and just finish. Checks of $var_Array’s contents showed me naught but an empty string, and yet checking the number of results returned by the SQL showed at least one result. I was stumped, and ready to tear my hair out! Read the rest of this entry »

PHP Random Password Generator

November 26th, 2005

Whilst hunting furiously for a password generating routine for the EbonHost Gift Registry, I found a routine by Jon Haworth. There are some issues with the routine, which I’d like to discuss. (Please visit Jon’s page for original code)

The main concern with the routine is when a large value is specified for $length. As $length approaches the length of the string $possible, the likelihood of the routine hanging increases greatly, up until the point of ‘definitely hangs’ at $length = strlen($possible). Let’s see why. Read the rest of this entry »

More on Readable Code - Variable Names

November 24th, 2005

Just a little more on making your PHP code readable… I’m tired of reading through sections of code, and seeing variable names like $g and $tmp. What is this so-called $g, and who let it out of it’s cage? Sure, $g is quick to type when you’re hacking out some prototype code or running through a thought-experiment, however when you’re reviewing the same code six-months later, will you remember what $g represents? Chances are you’ll need to go through the whole file of code, figuring it out through context.

The tip is this - Use descriptive variable names! - Instead of $g, try $var_MessageText or $array_TableOfNames. You’ll find your code much easier to read and maintain, which more than compensates for the additional typing. Of course, loop counters like $i can still be used, just as long as it’s used for the same purpose every time, so as to avoid ambiguity.

regards,
David (That Script Guy)

Gift Registry for Ecommerce Templates Shopping Cart System

November 23rd, 2005

Phew! After a few days of heavy coding (and a headache or two), my latest release is nearly completed!

EbonHost Gift Registry will be shortly available for purchase, at a cost of AUD$49, with installation available for a small additional fee. The mod requires ECT Shopping Cart PHP version to function, and installation requires only minor changes to the base system files.

If you have any queries, please leave a comment here, or you can email me directly - dave(at)ebonhost.com

regards,
David (That Script Guy)

Good Comments = Readable Code!

November 22nd, 2005

I’ve always found myself re-reading old code I’ve written, and seriously wondering what the heck I was thinking when I wrote the code. Most of my confusion came from nesting various IF-ELSE structures, and leaping up-and-down the page, tring to figure out which curly-brace went with which conditional..

Then I found a simple, elegant solution - whenever I create a new IF-structure, I immediately pump out something similar to:

if ($user == 'admin')
{ //: User is admin
    echo 'Welcome, admin!';
} // end User is admin
else
{ //: User is NOT admin
    echo 'Go away!';
} // end User is NOT admin

By labelling the brackets themselves, and creating the empty structure all-at-once, the risk of losing one’s place or leaving out a closing curly-brace is gone. The code also becomes much easier to review at a later date. It’s a beginner-level tip, yet I’ve read other other people’s (so-called ‘commercial grade’) scripts, and been horrified at how unreadable the code is!

regards,
David (That Script Guy)

Javascript Confirm boxes

November 21st, 2005

More non-PHP stuff, but this one is also useful!

Rather than using a whole new page to confirm a critical operation (such as deleting an item), you can use a snippet of Javascript, and turn it into a popup message box.

<a href="dodelete.php" onClick="return confirm('Delete item?');">Delete Me</a>

To see a version of this in action, click here

If the user clicks “Cancel” or “No” (depends on browser which button titles are displayed, and they can’t be changed!), the HREF action is stopped, and nothing further happens.

Also, if using the above in PHP, don’t forget to escape any quotes in the confirmation message!

regards,
David (That Script Guy)

Javascript “Go Back” Link / Button

November 21st, 2005

Ok, so it’s not quite PHP, but this is useful none-the-less.
If you find yourself needing to refer someone to the previous page in their browser cache, try the following:

<a href="javascript:history.go(-1)">Go Back</a>

or, if you prefer to use a button:

<input type=button value="Back" onClick="history.go(-1)">

Of course, these only work if Javascript is enabled in the browser. There are other (non-Javascript) solutions, but they involve Sessions, HTTP referrers, and other tricky things. Each method has it’s own downfalls, so use whichever suits your application best!

regards,
David (That Script Guy)

Useful MySQL die() messages

November 20th, 2005

Normally, just using die(mysql_error()) as an error case for mysql_query doesn’t provide much information when there’s something wrong with the SQL.

I’ve found that the error is usually caused by something outside of what MySQL graciously decides to say, often leaving one bewildered as to precisely where the problem lies.

Instead of trying to decrypt MySQL’s ramblings, get the full SQL query with the error message, and see precisely what’s causing the issue!

$var_SQLResult = mysql_query($var_SQL) or die("<b>Error in SQL</b>: $var_SQL - <b>Message</b>: " . mysql_error());

Enjoy!
David (That Script Guy)

date() format to match MySQL DATETIME

November 20th, 2005

A quick one-liner to help those that prefer not to use NOW() during MySQL inserts, but instead need to process the date manually.

The PHP date() format that precisely matches the MySQL DATETIME field format is:

$datetime = date("Y-m-d H:i:s");

regards,
David (That Script Guy)

Welcome to PHP Snippets, Tips and Tricks

November 20th, 2005

Greetings, coders of all skill-levels!
Welcome to PHP Snippets, Tips and Tricks, my blog to catalogue various ideas and code tidbits I’ve either found or written along my PHP travels.

I hope at least some of this info is useful to someone!

regards,
David (That Script Guy)