Ternary Operator – Your Best Friend

If you have never used the Ternary Operator, or ? operator, your life is about to change. The ternary operator is used as a shorthand for if .. else structures that can really clean up your code. Some may want to classify this under a intermediate or advanced skill, but it is so useful that I think it should be included with the most basic tutorials.

Take this for example:

<?
if( $use_live_server ) {
     $url = "http://www.thelivesite.com"
} else {
     $url = "http://www.thedevsite.com";
}
?>

This block of code sets which URL we want to connect to based on if a variable called $use_live_server. While the block of code is perfectly valid, there is a much better way to do the exact same thing in a single line of code.

<?
$url = $use_live_server ? "http://www.thelivesite.com" : "http://www.thedevsite.com";
?>

That one line of code does the exact same thing and once you understand how this works. Here is how the ternary operator works:

<?
$variable = $expression_to_evaulate ? true : false
?>

You do not necessarily have to have a variable that is true or false. You can do any expression you need to.

Separating HTML From PHP Code

The first thing you will notice in all PHP programs is the use of special tags that tell the webserver to have PHP to process the code inside of those tags.

There are a few different versions of the tag that can be used.  The default version is:

<?php
// Code To Be Executed
?>

Any code between these two tags will be processed.  Anything outside of them will not be processed and outputted as it is typed.

There is also a short tag that can be used if you set the short_open_tag value in your php.ini file to 1.  This tag is:

<?
// Code To Be Executed
?>

PHP Hello World

Not be cliché, but I any book, tutorial or website discusses a programming language always begins with a program that simply displays the text “Hello World” on the screen and I intend to follow that tradition.

The process of writing text in PHP requires you to use either the “echo” of “print” function. There are some very minute differences between these two functions, but for these purposes, we will just say that they are interchangeable. If you really want to know the differences, there is an article that details this here.

Anyways, here is the hello world program for PHP.

<?
echo "Hello World";
?>

You could also use the print function and that would look like this:

<?
print "Hello World";
?>

You will notice that at the end of each line of code there is a semi-colon. Like many other languages, this is used at the end of most of the lines of code.

PHP Variable Syntax

PHP is a dynamically typed language. What this means is that you do not have to specify the variable type. You do not even need to declare you variable before using it. All variables have a $ in front of them and cannot be more than 64 characters long. String variables require that the value be surrounded by double or single quotes. Numerical values do not need to surrounded by quotes, but they can be if you so desire. They will still be recognized as numerical (PHP is nice that way).

For example, here are some basic variable declarations:

<?
$address = "123 Somewhere"; $zip = 49123
?>

Querying A mySQL Database Using PHP

Querying a mySQL database requires an established connection to a mySQL database.  You can read our article on connecting to a mySQL database here.

Querying the mySQL database is as simple as creating the SQL query and passing it through the mysql_query function.

<?
$sql = "SELECT * FROM products";
$results = mysql_query( $sql, $resource );
?>

With the $results variable you can use it to do a few different things. The first one we will discuss is to determine the total number of rows that was returned by the Select query. You can do that by doing the following:

<?
$num_rows = mysql_num_rows( $results );
?>

It should be noted that using mysql_num_rows is not the most efficent way to determine the number of rows being returned. If there are a lot of rows (I have seen it happen with as few as 1000 rows) that it is faster to query the database for the number of results like this:

<?
$sql = "SELECT COUNT(*) as num_rows FROM products";
$num_rows = mysql_fetch_array( mysql_query( $sql ) );
?>

This example also introduces the mysql_fetch_array function. This function is used to grab the next row of a mySQL query result. The row is returned as an array with the indexes named as the names of the columns in the database. Once there are no more results the function returns null.

The best way to iterate through a result set of a mySQL query is to use a while loop:

<?
$sql = "SELECT * FROM products";
$results = mysql_query($sql);
while( $row = mysql_fetch_array($results) ) {
    echo $row['products_id'] . ': '. $row['products_name'] . '
'; } ?>

Use hoverIntent To Capture Your Users Mouse Intentions

First of all, allow me to apologize for that title. There really is no better way to describe in a concise way what hoverIntent does. HoverIntent is a jQuery plugin that helps you capture mouse events only when your user intends to have them fire.

There is an example available for this demonstration that is available at: http://www.learnjquerynow.com/demos/hoverIntent.php. You will want to look at the source to see how everything is done.

The most ideal problem this plugin solves is having complex menus for your website to show and hide in a way that is very smooth and natural for the user. You can have menus only appear and disappear only when you are sure that is what your user wants to do.

This is without a doubt a plugin that you do not want to forget about. It is just too helpful to not have in your toolkit.

Use jQuery To Make Multiple Columns The Same Size

Probably just about every web developer has run into this problem. You have a two or three column layout on your website and your center column has a ton of great content that spans a very long way down the page and your side bars are short. They are different colors and they just look funny. Well today I have the solution for you!

Using jQuery you can actually tell your columns to become the same height as the longest column. It is actually very easy to do and you will find that you use this over and over again.

Let’s take a look at the code:

function heightmatch(columns) {
 var highest = 0;
  for( var i in columns ) {
   if( $(columns[i]).height() > highest ) {
    highest = $(columns[i]).height();
   }
  }

  for( var j in columns ) {
   $(columns[j]).height(highest);
  }
}

As you can see the code is very simple. You pass the function an array of your jQuery selectors that you want to be the same height and it goes through, finds the longest one, and then sets the height of all of them to the tallest value.

Very simple. You can expect this to be in the jQuery Toolkit that I we are planning on putting together.

Pre Load Your Webpage Using jQuery

Preloading a webpage image is not an easy feat. Some don’t look good, others don’t really work. QueryLoader is a very quick and easy way to pre load images for your website.

You can download QueryLoader from http://www.gayadesign.com/diy/queryloader-preload-your-website-in-style/. The code is incredibly simple. All you have to do is include the plugin and then place the following line of code at the end of your page:

QueryLoader.init();

Create Your First jQuery Plugin

Today is a big day. Up until now we have been using other people’s plugins to improve our web applications. Today we will create our own. It will be an incredibly simple plugin, but will build a foundation for creating more advanced plugins.

This plugin will require you to look at the following pages:

http://www.learnjquerynow.com/lib/addresshide/1.0/addresshide.js
http://www.learnjquerynow.com/demos/addresshide.php

The addresshide.js file contains the actual code for the jQuery Plugin. The php file is our implementation test. What our plugin will do is hide an email address from spam crawlers. It does this by taking in a series of arguments and simply concatenating them together to create a single string. You could do this with simple jQuery or JavaScript code but why not create a plugin? It is a useful function that you will could use over and over again in many different projects.

So on to the explanation of the code.

In the plugin you will notice that there really is not much code here. The most important part of this file is the jQuery.extend({}) line. What this does is tells jQuery that this code is an extension. You will notice that we are using jQuery instead of $. This is because there are other JavaScript libraries use the $ function and this will force the JavaScript to use the jQuery object.

Inside of the extend function you will notice addresshide: function(options) {}. This is the name of our function that is going to be called. This function will be called in the format $.addresshide(opts).

The options parameter is actually a JavaScript object. It contains the following values:

name – The username of the email address (The “josh” in josh@notarealaddress.com)
separator – The separator of the email address (The “@” in josh@notarealaddress.com)
domain – The separator of the email address (The “notarealaddress” in josh@notarealaddress.com)
tld – The separator of the email address (The “com” in josh@notarealaddress.com)
write – This is a boolean value that when true, writes the created email address out using document.write command
selector – This is a string value that places the created email address in selector provided.

Now you can take a look at the PHP file and see how the plugin is utilized. You simply call it using the code described above, giving it the options required and you have yourself your first plugin.

What I would recommend is creating your own “jQuery” library that is your own personal toolbox of things that make your life easier.