Wednesday, January 19, 2005

Take a Break, Solve a Puzzle

It is always good to relax after long hours of coding. You clear your mind, you think better, you feel better, and you WILL code better programs if you do not over-strain yourself.

Here's a good word search puzzle web site to visit ... http://www.webvroom.com

Do remember to 'vroom' back to PHP after your break.

Friday, November 19, 2004

PHP Form Trap

PHP are great for processing input forms ... Just look at this form:

<html>
<body>
<form action="process.php" method="post">
What is your name: <input name="username" type="text"><br>
What is your age: <input name="age" type="text"><br>
<input name="Submit" type="submit" value="Submit Now">
</form>
</body>
</html>

To get the submitted values, this code will suffice:

<?php

echo("The user's name is " . $username);
echo("The user's age is " . $age);

?>

( Simply cool! ... You might be thinking already...)

Now go on ... Run the code and see what you get ...

Do you get this result?

The user's name is John. (Assuming you entered Jack)
The user's age is 23. (Assuming you entered 23)

No? Do you get an error?

( Yep. What am I doing wrong? ... Are you wondering? )

Let's see ... if you encounter the following error, you are not alone ...

Notice: Undefined variable: username in ......\test.php on line 3
Username is
Notice: Undefined variable: age in ......\test.php on line 4
Age is


Almost every PHP newbie suffers from this maddening experience. A simple form exercise turns out to be minutes (hopefully not hours ...) of debugging.

Luckily for you, you won't suffer the same trauma.

The reason why this error occur lies in the "php.ini" file.

Look for register_globals = off. Turn it on and try again.

You should be popping champagne this time! Well let's not be estatic.
Although it works for now, it might be better to turn it off again.

(Any reason why?)

Security issue.

If someone create a bogus form with tonnes of input fields and send it to your php script, your script will end up with tonnes of landmines in the global register.

Sounds bad enough?

Remember to turn it off.



Wednesday, November 17, 2004

Function Calls at Runtime

It is possible to select the correct function to call at run-time ... here's how:


function requestLogin() {

print("Please login first.
");

}

function welcomeUser() {

print("Welcome to my homepage.
");

}

function checkUser($userLogin) {

global $runFunction;

if ($userLogin) {

$runFunction = "welcomeUser";

} else {

$runFunction = "requestLogin";

}

$runFunction();

}

$userLogin = true;

checkUser($userLogin);

$userLogin = false;

checkUser($userLogin);

?>

prints:

Welcome to my homepage.
Please login first.

Tuesday, November 16, 2004

PHP Array Functions

Refer to the PHP manual for more details.

is_array($array) - Tests if $array is an array. Returns (true|false).
array_merge() - Combines 2 or more arrays. Returns combined array. (From PHP4 onwards)
array_push() - "Pushes" 1 or more items into an array.
array_shift() - "Pops" 1 item from an array. Returns item.
array_slice() - Duplicates portions of another array. Returns new array.
sort() - Sorts an array (either alphabetically or numerically depending on item datatype). Returns nothing.

<?php

// Start with an array
$cookbook1[] = "chicken pie";

// add another recipe
array_push($cookbook1, "durian cake");

// show and remove the first recipe from cookbook
print(array_shift($cookbook1) . "
");

// create another array
$cookbook2 = array ("apple pie", "orange pie", "milkshake");

// merge both cookbooks
$cookbook3 = array_merge($cookbook1, $cookbook2);

// sort the cookbook
sort($cookbook3);

// print the cookbook
foreach ($cookbook3 as $recipe) {
print("$recipe .
");
}

?>

Saturday, November 13, 2004

Variable within Another Variable

A quick quiz ...

Is this code legal? ...

<?php

$fruit = "apple";
$temp = "fruit";

print($$temp);

?>

If you answered "Yes", congrats ... you are right. If you said "No", better luck next time!

Read on!

$$temp actually evaluates to $fruit. Hence, the code is legal and the word "apple" is printed.

PHP if ... elseif ... else ...

Sample code:

<?php

$temperature = 0; // degrees celsius

if ($temperature == 0) {
print("I am freezing.");
} elseif ($temperature == 100) {
print("I am boiling.");
} else {
print("In between boiling and freezing points.");
}

?>

prints

I am freezing.

Shortcut using the ternary operator:

If there are only two possible alternatives, you can use the ternary operator as a shortcut:

eg.

<?php

$reply = 1;

if ($reply == 1) {
$result = "yes";
} else {
$result = "no";
}

print($result);

?>

is the same as :

<?php

$reply = 1;
$result = (($reply == 1)? "yes" : "no");
print($result);

?>

"Pass By Value" versus "Pass By Reference"

PHP supports "pass by reference" variables by prefixing a variable with an ampersand(&)(PHP4 onwards ...). By default, variables are "passed by value".

e.g.

<?php

$varA = "apple";
print($varA . "
");

$varB = "orange";
print($varB . "
");

$varC = "pineapple";
print($varC . "
");

$varC = &$varA; // reference $varA
print($varC . "
");

$varA = "watermelon";
print($varC . "
");

$varC = &$varB; // reference $varB
print($varC . "
");

$varC = $varA; // copy of $varA's value
print($varC . "
");

?>

Prints results:

apple
orange
pineapple
apple
watermelon
orange
watermelon

To pass a variable by reference to a function, do this:

<?php

function passToFunction1(&$arg1) {

// ...

}

passToFunction1($varByRef);
?>

Looping in PHP

There are 2 standard types of while loops.

Type 1: while loop

eg.

<?php

$x = 0;
while ($x < 10) {
// do something
$x++;
}

?>

The conditional test is evaluated BEFORE the code block is executed.

Type 2: do ... while loop

eg.

<?php

$x = 0;
do {
// do something
$x++;
} while ($x < 10);

?>

The conditional test is evaluated AFTER the code block is executed.
This means that the code block is run a minimum of 1 time.

break and continue statements can affect looping if added in the code block.

break; abandons the while loop, and continues to the next statement.
continue; skips the current loop, but continues with the next loop.

eg.

<?php

$x = 0;
while ($x < 10) {
if ($x == 5) {
$x++;
continue;
}
if ($x == 8) {
break;
}
print($x . "<br>");
$x++;
}

?>

prints:

0
1
2
3
4
6
7

5 is missing as that iteration is skipped by continue;
8,9 are missing as break; terminated the loop when $x equals 8.

for loop statement:

eg.

<?php

for ($x=0; $x<10; $x++) {
if ($x == 5) {
continue;
}
if ($x == 8) {
break;
}
print($x . "<br>");

}

?>

prints the same results as above.

PHP Switch

Sample code:

<?php

switch ($temperature) {


case 0: print("I am freezing.");
break;

case 100: print("I am boiling.");
break;

default: print("In between boiling and freezing points.");

}

?>

Note the "break" statement after every case statement. If omitted, "fall-through" will occur.

PHP Constants

How to define a PHP constant?

Use the function: define("CONSTANT_IN_UPPERCASE", value);

eg.

<?php

define("CAR_WEIGHT", 100);

print("This car weighs ".CAR_WEIGHT." kg.");

?>

displays

This car weighs 100 kg.

Note the missing $ sign before the constant name.

PHP Tips

1. Choose descriptive but concise variable names.
2. Use parentheses to clarify operations.
3. Always end the statement with a semicolon;
4. CONSTANTS names should be in UPPER-CASE by convention.

Fun with Operations

I hope you have used a calculator before ... If not, go buy one and work on it ... it makes the following explanation much clearer ...

Maths Operation

Add: +
Subtract: -
Divide: /
Multiply: * (not 'x' as on a calculator;)
Modulus: %
Assignment: =

String Operation

Concatenate: . (yes ... it is a 'dot')

Shortforms

Add and Assign: +=
Subtract and Assign: -=
Divide and Assign: /=
Multiply and Assign: *=
Modulus and Assign: %=
Concatenate and Assign: .=

Comparison Operation

Equal: ==
Not equal: !=
Equal and same datatype: ===
Greater: >
Greater than or equal: >=
Less than: <
Less than or equal: <=

Logical Operations

OR: ||
AND: &&
NOT: !
XOR: xor (... ONLY IF either left or right operand is true.)

Pre-Increment: ++$var
Pre-Decrement: --$var
Post-Increment: $var++
Post-Decrement: $var--

eg.

<?php

$left = true;
$right = false;

$result = ($left xor $right);

print($result);

?>

What will be the result? Try it out! (Result is "1".)

Include PHP code in HTML

PHP code can be added to any part of a HTML document.

For ease of maintenance, you can do the following:

<!-- start of html file -->

<?php

// Put in as much PHP code at the top of the document as possible.
$title = "This is the title of the webpage";
$body = "This is the body of the webpage";

// and more code ...

?>

<html>
<head>
<title><?php print($title); ?></title>
</head>
<body>

<?php print($body); ?>

</body>
</html>

<!-- end of html file -->

PHP Associative Arrays

How to create an associative array ...

<?php

$car = array ("weight"=>"100kg", "year"=>"2004", "price"=>"7000");

?>

Alternative code:

<?php

$car["weight"] = "100kg";
$car["year"] = "2004";
$car["price"] = "7000";
$car["discount rebate"] = "12";

?>

To display the items in an array, do this:

<?php

// display car properties
print($car["price"]."<br>");

// display all car properties
foreach ($car as $property=>$value) {
print($property . " is " . $value . "<br>");
}

?>

How to sort an associative array ...

asort() - Sorts an associative array by value. Returns nothing.
ksort() - Sorts an associative array by key. Returns nothing.

eg.

<?php

$fruittrolley = array ("apple"=>"100", "orange"=>"20", "pear"=>"30");

asort($fruittrolley);

print("After asort: <br>");

foreach ($fruittrolley as $fruit=>$no) {
print("There are $no ${fruit}s.<br>");
}

ksort($fruittrolley);

print("After ksort: <br>");

foreach ($fruittrolley as $fruit=>$no) {
print("There are $no ${fruit}s.<br>");
}

?>

prints:

After asort:
There are 20 oranges.
There are 30 pears.
There are 100 apples.
After ksort:
There are 100 apples.
There are 20 oranges.
There are 30 pears.

PHP Arrays

How to create an array ...

<?php

$fruitbasket = array ("Apple", "Orange", "Pear", "Mango", "Strawberry");
$fruitbasket[] = "Rambutan"; // add a fruit to the list

?>

Alternatively, you can use the following code:

<?php

$fruitbasket[] = "Apple";
$fruitbasket[] = "Orange";
$fruitbasket[] = "Pear";
$fruitbasket[] = "Mango";
$fruitbasket[] = "Strawberry";
$fruitbasket[] = "Rambutan";

?>

Note: Use count($arrayName) to count the number of items in the array.

To display the items in an array, do this:

<?php

// display fruits in fruitbasket
for($i=0;$i<count($fruitbasket);$i++) {
print($fruitbasket[$i]."<br>");
}

?>

Alternatively, you can use the following code:

<?php

// display fruits in fruitbasket
foreach ($fruitbasket as $item) {
print($item."<br>");
}

?>

Thursday, November 11, 2004

Punctuate your PHP

Always end your PHP statement with a semicolon (;)

Now, what happens if you write bad grammar ...

PHP parser replies with an typical "unexpected T_PRINT" error message:

Parse error: parse error, unexpected T_PRINT in xxxx\yyyyy\zzzzz\testfile.php on line 4

So remember your semicolons;) even if it is the only statement in the block.

HelloWorld in PHP

Since this is a standard program in any language ... here's the PHP version ...

<?php

print("Hello World");

?>

If you compare this with the JSP version of "Hello World" below, you will see why PHP is so MUCH MORE convenient to code.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    res.getWriter().println("Hello World");
  }
}

PHP Tag Styles

There are 4 ways of specifying PHP code:

1. The usual way ...

<?php
// ... PHP code goes here
?>

2. The shortcut ...

<? /* PHP code goes here ... Beware if you have XML code in same page */ ?>

3. The long-winded way ...

<script language="php">

// ... PHP code goes here

</script>

4. And finally, the ASP way.

<%

// ... PHP code goes here

%>

To discourage you from using the ASP way, asp tags are de-activated by default. You need to change the php.ini file to enable it. Look for asp_tags=off. Turn it on.

Best PHP Editors

Which is your favorite PHP editor?

1. Dreamweaver MX
2. TextPad
3. Notepad
4. Simple Text
5. BBEdit
6. HTMLKit
7. Emacs
8. PHP Studio

My vote goes to TextPad. It is simple. It is fast! It is really good!

Cast your vote now!

PHP: The evolution

Rasmus Lerdorf created the Personal Home Page Tools in 1994. (PHP)

A group of developers created a new parser and improved on PHP. (PHP3)

PHP4 was released next, with the Zend engine at its core.

PHP5 should be out by now ...

Why I chose PHP

1. PHP is MUCH easier to learn compared to other web languages.

2. It takes much fewer lines of code to produce the same results (i.e. Try coding a "HelloWorld" program in JSP, ASP and
PHP and you see what I mean).

3. It is free. So is MySQL, the database. Ah! Not forgetting Apache, the web server. And Linux! Your wallet should be happy!

4. Powerful. PHP has many useful functions ready for use. There is no need to re-write the code to access the database etc.

5. PHP runs on Windows, Linux, Unix etc.

6. Open-source and mainstream ... it is easier to find help if you run into problems.

Tuesday, November 09, 2004

PHP Variables and Datatypes

What is a variable? (You are kidding ... aren't you?)

How to set a variable in PHP?

This is how you do it ...

$variableName = value;

Letters, numbers, underscore (_) are allowed in variable names.
Spaces ( ), non-alphanumeric characters are NOT allowed in variable names.

Variable names CANNOT start with a number!

Here are the basic datatypes in PHP. The value of a variable can be one of these datatypes:

1. Integer eg. 12345

2. Double eg. 123.45

3. String eg. 'string' or "string"

4. Boolean either true or false (PHP4 onwards)

Note that PHP does not impose strong type checking. (i.e. A variable may take on different datatypes at different points of execution.)

<?php

// Defines an integer
$noOfPeople = 12345;

// Defines an double
$priceOfProduct = 123.45;

// Defines a boolean
$userHasRegistered = true;

// Defines a string
$welcomeMessage = "Hello World";

?>

(... You mean you really don't know what a variable is? ... hmmm ... well ... treat it as a box containing a value which may vary. )

PHP Version

All the code snippets in this blog have been tested with PHP Version 4.3.8.

Now how do you know which version you are running?

Simple ...

Run this line in your code:

<?php

phpinfo();

?>

How to comment in PHP

There are 3 ways of commenting in PHP:


# This line is commented out (single line comment).

...
// so is this line (another single line comment).

...

/*

Is this line a comment? Make a guess! ( ... Alright, it is a multi-line comment.)

*/

?>