Basic PHP

Team-Fly    

Macromedia® DreamWeaver® MX Unleashed
By Matthew Pizzi, Zak Ruvalcaba
Table of Contents
Chapter 24.  PHP and MySQL


PHP stands for Personal Home Page. It was first developed in the early 1990s as a quick, lightweight scripting language for building dynamic Web pages. The inventors of the lan guage originally modeled PHP on Perl and C, so programmers familiar with these languages will have absolutely no problem with PHP.

In this section of the chapter, I'll discuss basic syntax, variables, arrays, expressions and operators, and control structures. By the end of this section, you'll have the basics down, and that will give you enough background for the sections that follow, which discuss creating custom functions and working with MySQL.

Basic Syntax

All PHP code is placed between <? and ?> tags directly in HTML markup. The PHP parser ignores everything outside of these PHP tags and processes whatever is inside them. Here's a basic, simple PHP command inserted inside HTML:

 <p>Hello, my name is <? echo $name ?>.  

Whatever value has been assigned to the variable $name appears after "Hello, my name is" when the page is rendered for the visitor.

As in other scripting languages, if all you're doing with a block of code is generating output, you can use an expression. An expression is a shortcut; basically, it means that you can use the <?= symbol instead of typing echo to generate output. Like this:

 <p>Hello, my name is <?= $name ?>.  

PHP doesn't care about whitespace or line endings within the <? and ?> blocks, so you can create code blocks, or scriptlets, that look like this:

 <?  if ($expression) {     echo "$expression must be true!"; } else {     echo "$expression must not be true!"; } ?> 

Each line must have an instruction separation; in most cases, this means putting a semicolon at the end of a command. However, a closing brace (}) or end of block (?>) also serves the same purpose. The following statements all have proper instruction separations:

 <?= $name; ?>  <? echo $name ?> <? if ($test) { echo $one } else { echo $two } ?> 

You can add comments to your code in various ways. Comments are ignored by the PHP parser, but they make it much easier for you to understand your code especially if you don't come back to it for several months.

You can use Perl-style hashes (#) anything after the # is a comment:

 <?  echo $name; #this is a comment ?> 

You can also use C and C++ style one-line comments (//):

 <?  echo $name; //this is a comment ?> 

If you have a lot of comments, you can embed them between multiline comments using /* and */, as in C and C++:

 <?  /* the following piece of code generates output from the variable $name */ echo $name; ?> 

WARNING

If you are using the C/C++ multiline comments, don't nest them, because this can cause problems. For example, don't do this:

 /*  some comments /* this will cause problems */ */ 


Variables

Variables are the simplest data container in PHP. They are known as scalars and are one dimensional. PHP is not strongly typed, so a variable can hold any kind of value you want and can even switch between types. For example, the same variable can start out holding a person's name (characters), and then numbers, a Boolean value, or a date.

Variable names are case sensitive and always start with a dollar sign ($) followed by a letter or underscore, followed by any number of other letters, underscores, and numbers. Variable names that start with a number are not valid.

Here are some examples of variables:

 $variable; //valid  $Variable; //valid, different from the one above $VaRIAble; //also valid, also different from both above $_variable; //also valid $4variable; //not valid $!variable; //not valid 

You can assign a value to a variable when you create it, but you don't have to. Use the = operator to assign a value to a variable:

 $variable = "some random text";  $Variable = 1234; //treated as numbers $VaRIAble = "1234"; //treated as text, at least for now 

You can copy the contents of one variable to another, like this:

 $cowsays = "moo";  $newcowsays = $cowsays; 

Now both variables have a value of "moo." Assigning a value to a variable is known as using an expression. I'll cover expressions in more depth in a later section.

Arrays

Variables are very useful data containers. However, they're one-dimensional. What happens when you want to store a number of related items in the same container, like a shopping list?

You could certainly try to put all items from a shopping list into a variable, but it would look like this:

 $shoppinglist = "eggs cheese bread soup jelly";  

What now? How can you break this value apart and do something useful with it? You can, but not easily. The smarter approach is to use an array.

PHP provides two types of arrays: simple arrays and associative arrays.

Simple Arrays

The simple array (or list) is just a list of scalars. You can build a simple array using the array() function. To continue the shopping list example:

 $grocerylist = array("eggs", "cheese", "bread", "soup", "jelly");  

Elements in simple arrays are indexed by number. The first element is numbered 0, the second element is numbered 1, and so on. To access elements in an array, you use bracket notation, placing the index value within brackets, like this:

 $grocerylist[0]; //eggs  $grocerylist[5]; //jelly 

If you wanted to, you could use the = expression to build an array one line at a time:

 $grocerylist[0] = "eggs";  $grocerylist[1] = "cheese"; 

You can overwrite an existing element by reassigning the value it previously had:

 $grocerylist[0] = "chicken"; //no more eggs!  
Associative Arrays

The second type of array is known as an associative array. Whereas a simple array is indexed by number, the associate array is indexed by keys. Therefore, an associative array describes a relationship between keys and their values.

For example, if you were running a dog owner's club, you could use an associative array to describe relationships between people and the dog they own:

 $kennelclub = array(      "Tom" => "Kafka",     "Jane" => "Snuggles",     "Mitch" => "Fido" ); 

Each key-value pair is separated by an arrow (=>) and represents the relationship. To access an element's value, all you'd have to do is use bracket notation with the name of the key inside the brackets:

 $tomsdog = $kennelclub["Tom"]; //$tomsdog now holds "Kafka"  $tomsdog = $kennelclub[Tom]; //same thing 

PHP allows you to create multidimensional associative arrays. For example, for your $kennelclub array, you may want to list more information than just the dog's name. Simply use another array() for each value in a key-value pair:

 $kennelclub = array(      "Tom" => array("name" => "Kafka", "age" => "5"),     "Jane" => array("name" => "Snuggles", "age" => "10"),     "Mitch" => array("name" => "Fido", "age" => "3") ); 

Although getting the value of an element is trickier (you have to be more specific), you'd use the same bracket notation:

 $kafka_age = $kennelclub[Tom][age];  

NOTE

Earlier I stated that associative arrays use keys as indexes. Don't be misled by this statement an associative array could certainly use numbers as keys (an ID, for example). The difference is that the index for an element in a simple array is assigned programmatically. For example, if you reverse the order of elements in an array, element 6 (the last element) would become element 0 (the first element). That's not true with associative arrays.


Array Functions in PHP

PHP has many built-in functions that help you work with arrays.

array_pop Enables you to remove the last element from an array and place it in a variable:

 $grocerylist = array("eggs", "cheese", "bread", "soup", "jelly"); graphics/ccc.gif  $last = array_pop($grocerylist); //$grocerylist is now: eggs, cheese, bread, soup 

array_push Enables you to add an element to the end of an array:

 $grocerylist = array("eggs", "cheese", "bread", "soup");  array_push($grocerylist, "tomatoes"); //$grocerylist is now: eggs, cheese, bread, soup, tomatoes 

array_reverse Enables you to reverse the order of elements in an array:

 $grocerylist = array("eggs", "cheese", "bread", "soup",  graphics/ccc.gif"tomatoes");  $reverselist = array_reverse($grocerylist); //$grocerylist is now: tomatoes, soup, bread, cheese, eggs 

count Returns the number of elements in an array:

 $grocerylist = array("eggs", "cheese", "bread", "soup",  graphics/ccc.gif"tomatoes");  $numberofelements = count($grocerylist); //$count should be 5 

sort Enables you to place the elements of an array in alphabetical order:

 $grocerylist = array("eggs", "cheese", "bread", "soup",  graphics/ccc.gif"tomatoes");  sort($grocerylist); //$grocerylist is now: bread, cheese, eggs, soup, tomatoes 

For a complete list of array functions, be sure to visit http://www.php.net, the home page for the PHP community. The site includes complete online documentation.

Expressions and Operators

Expressions and operators form the basic building blocks of PHP. With expressions and operators, you can perform tasks on data stored in variables and arrays, and much more.

The basic expression is called an assignment, which you've already seen. To recap, you can assign a value to a variable using the = operator:

 $variable = 1;  

Other assignment operators are available, the most common being the .= operator. This operator enables you to add (or concatenate) a value to the end of an existing value. It's a handy operator when you're running out of room in a line or want to programmatically add more information to the end of a value:

 $name = "John";  $name .= " Smith"; //$name is now "John Smith" 

Another good operator to know is the . operator, which allows you to piece together different strings to produce a value:

 $a = 123;  $b = $a . " Main Street"; //$b is now: "123 Main Street" 

The . operator is typically used to construct HTML markup strings that contain PHP variables and other code:

 echo "<a href=\"my.php?\">" . $linktext . "</a>";  

Other extremely common expressions involve comparisons. These expressions evaluate either to 0 (false) or 1 (true). You can use the following comparison expressions:

  • > (greater than)

  • >= (greater than or equal to)

  • == (equal to)

  • != (not equal to)

  • < (less than)

  • <= (less than or equal to)

These comparisons are usually used in if statements, so I'll cover them in more detail in the next section, "Control Structures."

The most common operators involve simple arithmetic:

 $first = 1;  $second = 2; $sum = $first + $second; //1 plus 2 $difference = $first - $second; //1 minus 2 $product = $first * $second; // 1 times 2 $quotient = $first / $second; // 1 divided by 2 $modulus = $first % $second // the remainder of 1 divided by 2 

You can also increment and decrement a variable using the ++ and operators. Depending on whether you put the increment/decrement operators before or after the variable gives you a different returned value:

 $first = 1;  echo $first++; //returns value of $first, then increments it by 1 (should be 1) echo $first; //now it's 2 echo ++$first; //increments value by 1, then returns value of $first (should be 3) echo $first; //still 3 echo $first--; //returns value of $first, then decrements it by 1 (should be 3) echo $first; //should be 2 --$first; //decrements value by 1, then returns value of $first (now it's 1) echo $first; // back to 1 

Control Structures

One of the most common tasks you'll perform in your code is making decisions based on some condition. In PHP and other languages, you use a control structure (also called a branching statement or loop) to determine what code to run.

if

The most common control structure is the if statement. The if statement allows conditional execution of code based on an initial test of a condition. The if statement is usually a comparison. If the comparison evaluates to true, the block of code within the if statement is executed. Otherwise, the statement evaluates to false and the code is not executed.

For example, you might run a block of code if a returned variable has a certain value (say the value 3). In PHP, this example would look like the following:

 if ($value == 3) {     echo "value is $value!";     //execute block of code } 

By itself, this is a useful test because it keeps code from executing if $value is not 3. However, what if you want to execute another block of code if $value is not set to 3? In PHP, you can add an else statement to the end of the if statement to define what happens if the initial comparison evaluates to false.

 if ($value == 3) {     echo "value is $value!";     //execute block of code } else {     echo "value is something else, unfortunately"; } 

Now you know when $value is set to 3 and when it isn't. If you wanted even more detail than that, you can add elseif statements before the else. In this case, each elseif statement represents a specific test and the else statement becomes the default answer if no other statement before it evaluates to true.

For example, we can add an elseif statement that checks to see if $value is less than 3:

 if ($value == 3) {     echo "value is $value!";     //execute block of code } elseif ($value < 3) {     echo "value is less than 3"; } else {     echo "value is greater than 3, apparently"; } 

You can continue adding elseif statements for each value you want to test, but at some point, it becomes easier to use a switch statement instead.

switch

A switch statement consists of a series of cases that are evaluated line by line against a variable being tested. Switch statements are fast, easy to read, and a good alternative to an if statement with a lot of branching.

For example, you might have an instance in which you are testing to see what item from a drop-down list was selected. The drop-down list has three selections from a dinner menu: steak, salad, and soup.

An if statement for testing what selection was made would look like this:

 if ($selection == "steak") {     echo "Steak was selected."; } elseif ($selection == "salad") {     echo "Is a salad really all you want?"; } else {     echo "You ordered soup."; } 

Here's that same functionality done with a switch statement. The break statements are used to "break out" of the switch statement in other words, to stop evaluation of the $selection variable.

 switch ($selection) {     case steak:     echo "Steak was selected.";     break;     case salad:     echo "Is a salad really all you want?";     break;     case soup:     echo "You ordered soup.";     break; } 
for

The for loop allows you to loop over a block of code and perform repetitious work. The for loop uses a value (usually an integer) to initialize itself; a second variable to test whether it should continue looping; and finally, an increment or decrement to adjust the value.

For example, the following for loop prints out the numbers 1 through 10:

 for ($x = 1; $x <= 10; $x++) {     echo "$x<br>"; } 
foreach

The foreach loop is similar to the for loop, but it allows you to iterate over an array. You use the name of the array and then name a substitute variable used by the foreach to iterate over each element of the array:

 foreach ($grocerylist as $item) {     echo "current item is $item<br>"; } 

A variant of this syntax is used to iterate over an associative array:

 foreach ($kennelclub as $key => $value) {    echo "$key is the owner of $value<br>"; } 
while

The while loop is similar to the for loop, except it has only one test. If the test evaluates to true, the block of code is executed and the test is evaluated again.

For example, the following block of code is executed until the value of $variable is 10 or greater:

 $variable = 1;  while ($variable <= 10) {     echo "value is still less than or equal to 10!<br>";     $variable++; } 

while loops are extremely useful for reading in the entire contents of a file (the loop continues to execute code until the last line of the file is reached) or a recordset returned by a query.


    Team-Fly    
    Top


    Macromedia Dreamweaver MX Unleashed
    Macromedia Dreamweaver MX 2004 Unleashed
    ISBN: 0672326310
    EAN: 2147483647
    Year: 2002
    Pages: 321

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