News:

GinGly.com - Used by 85,000 Members - SMS Backed up 7,35,000 - Contacts Stored  28,850 !!

Main Menu

Getting Started with PHP - Syntax, Commands, Arrays And Etc......

Started by sivaji, Jan 11, 2008, 02:56 PM

Previous topic - Next topic

sivaji

Getting Started with PHP 3

In Chapter 2, we learned how to use the MySQL database engine to store a list of jokes in a simple database (composed of a single table named joke). To do so, we used the MySQL command-line client to enter SQL commands (queries). In this chapter, we'll introduce the PHP server-side scripting language. In addition to the basic features we'll explore here, this language has full support for communication
with MySQL databases.

Introducing PHP

As we've discussed previously, PHP is a server-side scripting language. This concept is not obvious, especially if you're used to designing pages with just HTML and JavaScript. A server-side scripting language is similar to JavaScript in that it allows you to embed little programs (scripts) into the HTML of a Web page. When executed, such scripts allow you to control what appears in the browser window
more flexibly than straight HTML.

The key difference between JavaScript and PHP is simple. JavaScript is interpreted by the Web browser once the Web page that contains the script has been downloaded. Conversely, server-side scripting languages such as PHP are interpreted by the Web server before the page is even sent to the browser. And, once it's interpreted, the results of the script replace the PHP code in the Web page itself—all the browser sees is a standard HTML file. The script is processed entirely by the server, hence the designation: server-side scripting language.

Let's look back at the today.php example presented in Chapter 1:

File: today.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Today's Date</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<p>Today's Date (according to this Web server) is
<?php
echo date('l, F dS Y.');
?></p>
</body>
</html>

Most of this is plain HTML; however, the line between <?php and ?> is written in PHP. <?php means "begin PHP code," and ?> means "end PHP code." The Web server is asked to interpret everything between these two delimiters, and to convert it to regular HTML code before it sends the Web page to the requesting browser. The browser is presented with something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Today's Date</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<p>Today's Date (according to this Web server) is
Sunday, May 16th 2004.</p>
</body>
</html>

Notice that all signs of the PHP code have disappeared. In its place, the output of the script has appeared, and it looks just like standard HTML. This example demonstrates several advantages of server-side scripting:

No browser compatibility issues
       PHP scripts are interpreted by the Web server alone, so you don't have to worry about whether
       the language you're using is supported by visitors' browsers.

Access to server-side resources
       In the above example, we placed the date, according to the Web server, into the Web page. If we
       had inserted the date using JavaScript, we would only be able to display the date according to the
       computer on which the Web browser was running. Now, while this isn't an especially impressive
       example of the exploitation of server-side resources, we could just as easily have inserted some
       other information that would be available only to a script running on the Web server. An example
       might be information stored in a MySQL database that runs on the Web server computer.

Reduced load on the client
       JavaScript can slow significantly the display of a Web page on slower computers, as the browser  
       must run the script before it can display the Web page. With server-side scripting, this burden is
       passed to the Web server machine.

Basic Syntax and Commands

PHP syntax will be very familiar to anyone with an understanding of C, C++, C#, Java, JavaScript, Perl, or any other C-derived language. A PHP script consists of a series of commands, or statements. Each statement is an instruction that must be followed the Web server before it can proceed to the next. PHP statements, like those in the above-mentioned languages, are always terminated by a semicolon (;).

This is a typical PHP statement:

echo 'This is a test!';

This is an echo statement, which is used to send output to the browser. An echo statement simply takes the text it's given, and places it into the page's HTML code at the current location.

In this case, we have supplied a string of text to be output: 'This is a test!'. Notice that the string of text contains HTML tags ( and ), which is perfectly acceptable. So, if we take this statement and put it into a complete PHP script (echo.php in the code archive), here's the code we get:

File: echo.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Simple PHP Example</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<p><?php echo 'This is a test!'; ?></p>
</body>
</html>

If you place this file on your Web server, a browser that views the page will see this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Simple PHP Example</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<p>This is a test!</p>
</body>
</html>

Our today.php example contained a slightly more complex echo statement:

File: today.php (excerpt)

echo date('l, F dS Y.');

Instead of giving echo a simple string of text to output, this statement invokes a built-in function called date and passes it a string of text: 'l, F ds Y.'. Built-in functions can be thought of as things that PHP knows how to do without our needing to spell out the details. PHP has many built-in functions that let us
do everything from sending email, to working with information stored in various types of databases. In this case, the date function produces a text representation of the current date, using the string it is given to determine the format.

You may wonder why we need to surround the string of text with both parentheses (()) and single quotes (''). Quotes are used to mark the beginning and end of strings of text in PHP, so their presence is fully justified. The parentheses serve two purposes. First, they indicate that date is a function that you want to call. Second, they mark the beginning and end of a list of parameters that you wish to provide, in order to tell the function what to do. In the case of the date function, you need to provide a string of text that describes the format in which you want the date to appear.1 Later on, we'll look at functions that take more than one parameter, and we'll separate those parameters with commas. We'll also consider functions that take no parameters at all. These functions will still need the parentheses, though we won't type anything between them.

Variables and Operators

Variables in PHP are identical to variables in most other programming languages. For the uninitiated, a variable can be thought of as a name that's given to an imaginary box into which any value may be placed. The following statement creates a variable called $testvariable (all variable names in PHP begin with a dollar sign) and assigns it a value of 3:

$testvariable = 3;

PHP is a loosely typed language. This means that a single variable may contain any type of data, be it a number, a string of text, or some other kind of value, and may change types over its lifetime. So the following statement, if it appears after the statement above, assigns a new value to our existing $testvariable. In the process, the variable changes type: where it used to contain a number, it now contains a string of text:

$testvariable = "Three";

The equals sign we used in the last two statements is called the assignment operator, as it is used to assign values to variables. Other operators may be used to perform various mathematical operations on values:

$testvariable = 1 + 1; // Assigns a value of 2
$testvariable = 1 - 1; // Assigns a value of 0
$testvariable = 2 * 2; // Assigns a value of 4
$testvariable = 2 / 2; // Assigns a value of 1

Each of the lines above ends with a comment. Comments are a way to describe what your code is doing—they insert explanatory text into your code, and tell the PHP interpreter to ignore it. Comments begin with // and they finish at the end of the same line. You might be familiar with the /* */ style of comment used in other languages—these work in PHP as well. I'll be using comments throughout the rest of this book to help explain the code I present.

Now, let's get back to the four statements above. The operators we used are called the arithmetic operators, and allow you to add, subtract, multiply, and divide numbers. Among others, there is an operator that sticks strings of text together, called the concatenation operator:

$testvariable = "Hi " . "there!";
// Assigns a value of "Hi there!"

Variables may be used almost anywhere that you use an actual value. Consider these examples:

$var1 = 'PHP'; // Assigns a value of 'PHP' to $var1
$var2 = 5; // Assigns a value of 5 to $var2
$var3 = $var2 + 1; // Assigns a value of 6 to $var3
$var2 = $var1; // Assigns a value of 'PHP' to $var2
echo $var1; // Outputs 'PHP'
echo $var2; // Outputs 'PHP'
echo $var3; // Outputs '6'
echo $var1 . ' rules!'; // Outputs 'PHP rules!'
echo "$var1 rules!"; // Outputs 'PHP rules!'
echo '$var1 rules!'; // Outputs '$var1 rules!'

Notice the last two lines in particular. You can include the name of a variable right inside a text string, and have the value inserted in its place if you surround the string with double quotes instead of single quotes. This process of converting variable names to their values is known as variable interpolation. However, as the last line demonstrates, a string surrounded with single quotes will not interpolate the variable names it contains.

Arrays

An array is a special kind of variable that contains multiple values. If you think of a variable as a box that contains a value, then an array can be thought of as a box with compartments, where each compartment is able to store an individual value.

The simplest way to create an array in PHP is to use the built-in array function:

$myarray = array('one', 2, '3');

This code creates an array called $myarray that contains three values: 'one', 2, and 'three'. Just like an ordinary variable, each space in an array can contain any type of value. In this case, the first and third spaces contain strings, while the second contains a number.

To get at a value stored in an array, you need to know its index. Typically, arrays use numbers, starting with zero, as indices to point to the values they contain. That is, the first value (or element) of an array has index 0, the second has index 1, the third has index 2, and so on. In general, therefore, the index of the nth element of an array is n–1. Once you know the index of the value you're interested in, you can get that value by placing that index in square brackets after the array variable name:

echo $myarray[0]; // Outputs 'one'
echo $myarray[1]; // Outputs '2'
echo $myarray[2]; // Outputs '3'

You can also use the index in square brackets to create new elements, or assign new values to existing array elements:

$myarray[1] = 'two'; // Assign a new value
$myarray[3] = 'four'; // Create a new element

You can add elements to the end of an array using the assignment operator as usual, but leaving empty the square brackets that follow the variable name:

$myarray[] = 'the fifth element';
echo $myarray[4]; // Outputs 'the fifth element'

Array indices don't always have to be numbers; that's just the most commonchoice. You can also use strings as indices to create what is called an associative array. This type of array is called associative because it associates values with meaningful indices. In this example, we associate a date with each of three names:

$birthdays['Kevin'] = '1978-04-12';
$birthdays['Stephanie'] = '1980-05-16';
$birthdays['David'] = '1983-09-09';

The array function also lets you create associative arrays, if you prefer that method. Here's how we'd use it to create the $birthdays array:

$birthdays = array('Kevin' => '1978-04-12', 'Stephanie' =>
'1980-05-16', 'David' => '1983-09-09');

Now, if we want to know Kevin's birthday, we look it up using the name as the index:

echo 'My birthday is: ' . $birthdays['Kevin'];

This type of array is especially important when it comes to user interaction in PHP, as we'll see in the next section. I'll demonstrate other uses of arrays throughout this book.
Am now @ Chennai