PHP Code Syntax

Chapter 9 - Hand Coding Within Dreamweaver MX
byGareth Downes-Powellet al.
Wrox Press 2003

As we said above, we'll start with an overview of PHP syntax. So far in this book, you'll have seen many examples of PHP code, as added by Dreamweaver MX into your pages. However, you haven't really had to write any yourself, or understand exactly what the code does. While you can do a lot using Dreamweaver MX in this way, it is also useful to have a basic knowledge of PHP syntax in order to edit the PHP code that Dreamweaver MX adds or to write your own.

PHP is similar to other server-side technologies, in that the PHP code has to be placed between special tags, to delimit it from the rest of the HTML markup in the page. There are four types of PHP tag you can use for delimiting the code. These are:

Tag Type

Opening Tag

Closing Tag

Standard PHP syntax

<?php

?>

Shorthand style

<?

?>

ASP Style

<%

%>

Script style

<script language="PHP">

</script>

Anything between the above PHP tags will be interpreted as PHP code by the PHP compiler. You can use any of the above styles of tag syntax, although we will be sticking with the standard style throughout this chapter.

Statements

Now to the PHP code itself. Much of the code consists of single statements. These are written on a single line, and are followed by a semicolon, ;, as shown in the example below:

    <?php      echo "This is a test line showing PHP syntax" ;    ?> 

This statement prints the text This is a test line showing PHP syntax to the page.

Variables

In the above section, we mentioned the use of variables. These are ways of storing pieces of information for future use. They consist of a name and a value.

Variable Names

Variable names in PHP always start with the $ character, and can be any combination of letters or numbers, as long as the rules below are followed.

  • The variable name must always start with either a letter, or an underscore character (_).

  • The first character can be followed by any combination of letters, numbers, or underscore characters.

Examples of valid variable names are:

    $total    $_cell1    $length_of_string 

Examples of invalid variable names are:

    total    $1_total    $2_length    $!total 

Variable Values

PHP is what is known as a "loosely typed" language. This means that a variable can hold any type of data (for example a number or a string of characters) - you don't have to specifically assign a data type to a variable. You can change the data type for a variable at any time.

For example, a variable called $myVariable could contain the string value "hello" at one point in the code, and could store the number 10 later on, without having to tell PHP that you're changing the data type of the variable.

Note that strings are always surrounded by quote marks, so "123" and ' 123' are string values, but 123 is a numeric value.

Assigning Variables

In PHP, to assign a value to a variable, you use the = operator. For example, to assign the integer value 10 to a variable called $total, you would use:

    <?php      $total = 10;    ?> 

Assigning Strings To Variables

To assign a string to a variable, you can use double quotes (") or single quotes ('), as shown in the example below:

    <?php      $example1 = 'This is a single quoted string';      $example2 = "This is a double quoted string";    ?> 

So what's the difference between single- and double-quoted strings?

Take a look at the next example:

    <php      $total = 10;      $example1 = 'The total is $total';      $example2 = "The total is $total";    ?> 

The contents of the variables will now be:

Variable

Value

$example1

The total is $total

$example2

The total is 10

As you can see, text enclosed between single quotes is taken literally by PHP, and is put straight in the string without processing.

For $example2, where the text is enclosed in double quotes, the value of $total is substituted into the text.

Appending Strings To Strings

PHP has a handy way of appending one string to another using the concatenation operator".", for example:

    <php    $a = 'apples';    $b = 'bananas';    $c = ' ' ;    $c = $a . ' and ' . $b;    ?> 

In this example, $c would have the value "apples and bananas".

You can also quickly append one string to another using ".=", for example:

    <php    $a = 'apples';    $a . = ' and bananas';    ?> 

$a would now have the value "apples and bananas".

Escaping Characters

Escaping a character tells PHP to ignore it. Why would we want to do this? Imagine we want to print the following text to the screen:

This is an example showing double quotes (" ")

If we try and insert this into a variable, and print it to the screen, as in the following example, we will get an error:

    <?php      $example = "This is an example showing double quotes (" ")";      echo "$example";    ?> 

This causes an error, because the PHP parser gets confused where the string starts and finishes - there are too many quote marks in the string. To stop this from happening, we have to escape the quotes we want to write to the screen using the backslash character (\). Change the example to the following:

     <?php       $example = "This is an example showing double quotes (\" \")";       echo "$example";     ?> 

As we have preceded the quotes in the string with the backslash, they are ignored by the PHP engine and printed to the screen, as we intended. This method should also be used if you want to include some quotes in a string that is to be inserted into a database.

Below is a list of the characters that need to be escaped in this way.

Character

Escaped Character

Description

not applicable

\n

Adds a linefeed

not applicable

\r

Adds a carriage return

not applicable

\t

Adds a tab

\

\\

Backslash

$

\$

Dollar Sign

"

\"

Double Quote

Arrays

Arrays are similar to variables, in that they are used to store pieces of data. However, unlike variables, arrays are useful because they can hold more than one piece of data at a time. For example, imagine that you wanted to store all the items in a shopping list. You could use an array to store these items. To create an array in PHP you use the array() function. Each item in the array is identified by a key. So to create an array for our shopping list, we could use the following code:

    $shoppingList  = array( 1 => "toothpaste", 2 => "sun cream", 3 => "band-aids"); 

To retrieve an element (a specific bit of data) from the array, we use the name of the array followed by the key in square brackets. So, to get the third item from our array, we can use the following piece of code:

    echo "The third item in the shopping list is $shoppingList[3];" 

This would display "The third item in the shopping list is band-aids" on the screen.

Control Structures

PHP uses a variety of control structures to affect which code is executed, when, and for how long. We'll cover two types here, if and foreach. There are other statements, like do. .while, which we won't cover here. More details and useful examples can be found in the online PHP manual.

If

If you've used any other programming language, then you'll be familiar with the if statement. It's used to conditionally execute some code: if a condition is met, then run a section of code.

For example, if we have two variables, $apples and $bananas, and we want to print a message on the screen if the value of $apples is greater than $bananas, we could use the following code:

    if ($apples > $bananas)        echo "You have more apples than bananas!"; 

Here the code checks to see whether a condition is met: whether $apples is greater than $bananas, using the > operator. If so, then the second line is executed, and the message is displayed. There are several conditional operators that you can use in your code:

Operator

Meaning

==

Equal to

!=

Not equal to

<>

Not equal to

<

Less than

>

Greater than

<=

Less than or equal to

>=

Greater than or equal to

Be careful when comparing two variables for equality. The correct operator to use is == (two equals signs). This is because = (one equals sign) is the assignment operator, for setting the value of variables.

If you want the if statement to conditionally execute more than one line of code, then you can enclose the block of code that you want to execute with curly braces, {}. So, for example, you could make the example we used above set the number of bananas to zero as well as displaying the message by using the following code:

    if ($apples > $bananas)    {        echo "You have more apples than bananas, so I'm taking away your bananas!";        $bananas = 0;    } 

foreach

The foreach statement is used to loop through an array, looking at all of the elements in the array in turn. For example, if I wanted to display all the contents of an array:

    <?php    $numbers = array(2,3,4,2);    foreach ( $numbers as $v)    {        echo "Current value of \$v: $v <BR>";    }    ?> 

this would produce the following result:

Current value of $v: 2

Current value of $v: 3

Current value of $v: 4

Current value of $v: 2

Functions

You may have noticed the use of some of PHP's own functions in the code produced by Dreamweaver in previous chapters. They encapsulate a task that can then be called and run from elsewhere in your code.

It's possible to write your own functions in PHP and use them in a similar manner, allowing you to reuse a piece of useful code without constantly retyping it. For example, you could write the following function that checks the length of a certain piece of data:

     <?php       function check_length($data)       {         if (strlen($data) < 6)           return "The data was too small";         else           return "That data was fine";       }     ?> 

If the length of the data passed to the function as a parameter between its parentheses is less than 6, then the string "The data was too small" is returned by the function to wherever it was called from. If the length of the string wasn't less than 6, then the string "That data was fine" is returned.

The function can then be called anywhere in your code. For example:

    <?php    $example = "qwertyuiop";    echo check_length($example);    ?> 

In this case, the data was fine is printed to the page, since the value "qwertyuiop" has more than 6 characters.

PHP Resources

If you find that you need more information about the PHP commands we use in the hand coding examples in this chapter, you may find the following two web sites useful.

First, there is PHP.net - http://www.php.net/. This is the home of PHP and contains a huge amount of useful information, including online PHP manuals, searchable by function.

Second, there is Zend - http://www.zend.com/. The Zend founders created PHP 4 and the Zend Engine, on which all PHP site and applications are run. Their web site contains many articles, code fragments, and tutorials, which can help you to learn and use PHP 4.

When you're hand coding in PHP, it's very useful to have a browser open at the above web sites, so you can quickly check PHP syntax, for example the parameters for a function. It's definitely worth adding them to your browser's bookmarks.

If you prefer to learn from a book, we recommend Professional PHP4 (Harish Rawat et al., Wrox Press, ISBN 1-861006-91-8). This is an excellent PHP resource, and covers the whole PHP 4 language in detail.

Why Hand Code within Dreamweaver MX?

Although Dreamweaver MX contains a range of built-in PHP server behaviors to perform various operations, if you're building a complex site, you'll soon find that you want to do something for which there isn't a built-in server behavior.

Since PHP is an open-source product, it is widely supported by a range of open-source developers and a huge user community. As a result PHP evolves much faster than other commercial languages, and the code is continuously updated with bug fixes, enhancements, and language extensions, which extend its capabilities.

Hand coding allows you to implement the latest PHP developments in your code as soon as they are released. It offers you total freedom to ensure that your web site does exactly what you want it to, and you are not just limited to the built-in code generated by your development program.

Code that you've written yourself can also interact with the Dreamweaver MX-generated code, so you can create standard code quickly using the Dreamweaver MX server behaviors, and then modify it yourself to perform extra functions.



Dreamweaver MX PHP Web Development
Dreamweaver Mx: Advanced Php Web Development
ISBN: 1904151191
EAN: 2147483647
Year: 2001
Pages: 88

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net