Sunday, May 24, 2009

What Does PHP Do?

PHP can be used in three primary ways:

Server-side scripting

PHP was originally designed to create dynamic web content, and it is still best suited for that task. To generate HTML, you need the PHP parser and a web server to send the documents. Lately, PHP has also become popular for generating XML documents, graphics, Flash animations, PDF files, and more.

Command-line scripting

PHP can run scripts from the command line, much like Perl, awk, or the Unix shell. You might use the command-line scripts for system administration tasks, such as backup and log parsing.

Client-side GUI applications

Using PHP-GTK (http://gtk.php.net), you can write full-blown, cross-platform GUI applications in PHP.

In this book, we'll concentrate on the first item, using PHP to develop dynamic web content.

PHP runs on all major operating systems, from Unix variants including Linux, FreeBSD, and Solaris to such diverse platforms as Windows and Mac OS X. It can be used with all leading web servers, including Apache, Microsoft IIS, and the Netscape/iPlanet servers.

The language is very flexible. For example, you aren't limited to outputting just HTML or other text files—any document format can be generated. PHP has built-in support for generating PDF files, GIF, JPG, and PNG images, and Flash movies.

One of PHP's most significant features is its wide-ranging support for databases. PHP supports all major databases (including MySQL, PostgreSQL, Oracle, Sybase, and ODBC-compliant databases), and even many obscure ones. With PHP, creating web pages with dynamic content from a database is remarkably simple.

Finally, PHP provides a library of PHP code to perform common tasks, such as database abstraction, error handling, and so on, with the PHP Extension and Application Repository (PEAR). PEAR is a framework and distribution system for reusable PHP components. You can find out more about it at http://php.baggyspace.com/

Introduction to PHP


PHP is a simple yet powerful language designed for creating HTML content. This chapter covers essential background on the PHP language. It describes the nature and history of PHP; which platforms it runs on; and how to download, install, and configure it. This chapter ends by showing you PHP in action, with a quick walkthrough of several PHP programs that illustrate common tasks, such as processing form data, interacting with a database, and creating graphics.

Saturday, May 23, 2009

Variables

Variables

Variables hold the data that your program manipulates while it runs, such as information about a user that you've loaded from a database or entries that have been typed into an HTML form. In PHP, variables are denoted by $ followed by the variable's name. To assign a value to a variable, use an equals sign (=). This is known as the assignment operator.

$plates = 5;

$dinner = 'Beef Chow-Fun';

$cost_of_dinner = 8.95;

$cost_of_lunch = $cost_of_dinner;


Assignment works with here documents as well:

$page_header = <<

Menu

Dinner

HTML_HEADER;

$page_footer = <<

HTML_FOOTER;


Variable names must begin with letter or an underscore. The rest of the characters in the variable name may be letters, numbers, or an underscore. Table 2-2 lists some acceptable variable names.

Table 2-2. Acceptable variable names >>>>>>>mor


Variable names are case-sensitive. This means that variables named $dinner, $Dinner, and $DINNER are separate and distinct, with no more in common than if they were named $breakfast, $lunch, and $supper. In practice, you should avoid using variable names that differ only by letter case. They make programs difficult to read and debug.

2.3.1 Operating on Variables
Arithmetic and string operators work on variables containing numbers or strings just like they do on literal numbers or strings. Example 2-17 shows some math and string operations at work on variables.

Example 2-17. Operating on variables

$price = 3.95;

$tax_rate = 0.08;

$tax_amount = $price * $tax_rate;

$total_cost = $price + $tax_amount;

$username = 'james';

$domain =

$email_address = $username . $domain;

print 'The tax is ' . $tax_amount;

print "\n"; // this prints a linebreak

print 'The total cost is ' .$total_cost;

print "\n"; // this prints a linebreak

print $email_address;

?>


Example 2-17 prints:

The tax is 0.316

The total cost is 4.266


The assignment operator can be combined with arithmetic and string operators for a concise way to modify a value. An operator followed by the equals sign means "apply this operator to the variable." Example 2-18 shows two identical ways to add 3 to $price.

Example 2-18. Combined assignment and addition
// Add 3 the regular way

$price = $price + 3;

// Add 3 with the combined operator

$price += 3;


Combining the assignment operator with the string concatenation operator appends a value to a string. Example 2-19 shows two identical ways to add a suffix to a string. The advantage of the combined operators is that they are more concise.

Example 2-19. Combined assignment and concatenation
$username = 'james';

$domain =

// Concatenate $domain to the end of $username the regular way

$username = $username . $domain;

// Concatenate with the combined operator

$username .= $domain;


Incrementing and decrementing variables by 1 are so common that these operations have their own operators. The ++ operator adds 1 to a variable, and the -- operator subtracts 1. These operators are usually used in for( ) loops, which are detailed in Chapter 3. But you can use them on any variable holding a number, as shown in Example 2-20.

Example 2-20. Incrementing and decrementing
// Add one to $birthday

$birthday = $birthday + 1;

// Add another one to $birthday

++$birthday;

// Subtract 1 from $years_left

$years_left = $years_left - 1;

// Subtract another 1 from $years_left

--$years_left;


2.3.2 Putting Variables Inside Strings
Frequently, you print the values of variables combined with other text, such as when you display an HTML table with calculated values in the cells or a user profile page that shows a particular user's information in a standardized HTML template. Double-quoted strings and here documents have a property that makes this easy: you can interpolate variables into them. This means that if the string contains a variable name, the variable name is replaced by the value of the variable. In Example 2-21, the value of $email is interpolated into the printed string.

Example 2-21. Variable interpolation
$email =

print "Send replies to: $email";


Example 2-21 prints:

Send replies to: This e-mail address is being protected from spambots. You need JavaScript enabled to view it


Here documents are especially useful for interpolating many variables into a long block of HTML, as shown in Example 2-22.

Example 2-22. Interpolating in a here document
$page_title = 'Menu';

$meat = 'pork';

$vegetable = 'bean sprout';

print <<

$page_title

  • Barbecued $meat

  • Sliced $meat

  • Braised $meat with $vegetable

MENU;


Example 2-22 prints:

Menu

  • Barbecued pork

  • Sliced pork

  • Braised pork with bean sprout


When you interpolate a variable into a string in a place where the PHP interpreter could be confused about the variable name, surround the variable with curly braces to remove the confusion. Example 2-23 needs curly braces so that $preparation is interpolated properly.

Example 2-23. Interpolating with curly braces
$preparation = 'Braise';

$meat = 'Beef';

print "{$preparation}d $meat with Vegetables";


Example 2-23 prints:

Braised Beef with Vegetables


Without the curly braces, the print statement in Example 2-23 would be print "$preparationd $meat with Vegetables";. In that statement, it looks like the variable to interpolate is named $preparationd. The curly braces are necessary to indicate where the variable name stops and the literal string begins. The curly brace syntax is also useful for interpolating more complicated expressions and array values, discussed in Chapter 4.


Last Updated on Friday, 01 May 2009 22:09



more >>>>>>>>
php




Wednesday, May 20, 2009

Retrieving Data from the Database

Retrieving Data from the Database

The query( ) function can also be used to retrieve information from the database. The syntax of query( ) is the same, but what you do with the object that query( ) returns is new. When it successfully completes a SELECT statement, query( ) returns an object that provides access to the retrieved rows. Each time you call the fetchRow( ) function of this object, you get the next row returned from the query. When there are no more rows left, fetchRow( ) returns a false value, making it perfect to use in a while( ) loop. This is shown in Example 7-31.

Example 7-31. Retrieving rows with query( ) and fetchRow( )
require 'DB.php';

$db = DB::connect('mysql://hunter:w) restaurant');

$q = $db->query('SELECT dish_name, price FROM dishes');

while ($row = $q->fetchRow( )) {

print "$row[0], $row[1] \n";

}


Example 7-31 prints:

Walnut Bun, 1.00

Cashew Nuts and White Mushrooms, 4.95

Dried Mulberries, 3.00

Eggplant with Chili Sauce, 6.50


The first time through the while( ) loop, fetchRow( ) returns an array containing Walnut Bun and 1.00. This array is assigned to $row. Since an array with elements in it evaluates to true, the code inside the while( ) loop executes, printing the data from the first row returned by the SELECT query. This happens three more times. On each trip through the while( ) loop, fetchRow( ) returns the next row in the set of rows returned by the SELECT query. When it has no more rows to return, fetchRow( ) returns a value that evaluates to false, and the while( ) loop is done.

To find out the number of rows returned by a SELECT query (without iterating through them all), use the numrows( ) function of the object returned by query( ). Example 7-32 reports how many rows are in the dishes table.

Example 7-32. Counting rows with numrows( )
require 'DB.php';

$db = DB::connect('mysql://hunter:w) restaurant');

$q = $db->query('SELECT dish_name, price FROM dishes');

print 'There are ' . $q->numrows( ) . ' rows in the dishes table.';


With four rows in the table, Example 7-32 prints:

There are 5 rows in the dishes table.


Because sending a SELECT query to the database program and retrieving the results is such a common task, DB provides ways that collapse the call to query( ) and multiple calls to fetchRow( ) into one step. The getAll( ) function executes a SELECT query and returns an array containing all the retrieved rows. Example 7-33 uses getAll( ) to do the same thing as Example 7-31.

Example 7-33. Retrieving rows with getAll( )
require 'DB.php';

$db = DB::connect('mysql:/hunter:w) restaurant');

$rows = $db->getAll('SELECT dish_name, price FROM dishes');

foreach ($rows as $row) {

print "$row[0], $row[1] \n";

}


Example 7-33 prints:

Walnut Bun, 1.00

Cashew Nuts and White Mushrooms, 4.95

Dried Mulberries, 3.00

Eggplant with Chili Sauce, 6.50


SQL Lesson: ORDER BY and LIMIT
As mentioned earlier in this chapter in Section 7.1, rows in a table don't have any inherent order. A database server doesn't have to return rows from a SELECT query in any particular pattern. To force a certain order on the returned rows, add an ORDER BY clause to your SELECT. Example 7-41 returns all the rows in the dishes table ordered by price, lowest to highest.
Example 7-41. Ordering rows returned from a SELECT query
SELECT dish_name FROM dishes ORDER BY price

To order from highest to lowest value, add DESC after the column that the results are ordered by. Example 7-42 returns all the rows in the dishes table ordered by price, highest to lowest.
Example 7-42. Ordering from highest to lowest
SELECT dish_name FROM dishes ORDER BY price DESC

You can specify multiple columns to order by. If two rows have the same value for the first ORDER BY column, they are sorted by the second. The query in Example 7-43 orders rows in dishes by price (highest to lowest). If multiple rows have the same price, then they are ordered alphabetically by name.
Example 7-43. Ordering by multiple columns
SELECT dish_name FROM dishes ORDER BY price DESC, dish_name

Using ORDER BY doesn't change the order of the rows in the table itself (remember, they don't really have any set order) but rearranges the results of the query. This affects only the answer to the query. If you hand someone a menu and ask them to read you the appetizers in alphabetical order, it doesn't affect the printed menu—just the response to your query ("Read me all the appetizers in alphabetical order").
Normally, a SELECT query returns all rows that match the WHERE clause (or all rows in a table if there is no WHERE clause). Sometimes it's helpful to just get a certain number of rows back. You may want to find the lowest priced dish available or just print 10 search results. To restrict the results to a specific number of rows, add a LIMIT clause to the end of the query. Example 7-44 returns the row from dishes with the lowest price.
Example 7-44. Limiting the number of rows returned by SELECT
SELECT * FROM dishes ORDER BY price LIMIT 1

Example 7-45 returns the first (sorted alphabetically by dish name) 10 rows from dishes.
Example 7-45. Still limiting the number of rows returned by SELECT
SELECT dish_name, price FROM dishes ORDER BY dish_name LIMIT 10

In general, you should only use LIMIT in a query that also has ORDER BY. If you leave out ORDER BY, the database program can return rows in any order. So, the "first" row one time a query is executed might not be the "first" row another time the same query is executed.


3.6 Exercises

3.6 Exercises


Without using a PHP program to evaluate them, determine whether each of these expressions is true or false:

100.00 - 100

"zero"

"false"

0 + "true"

0.000

"0.0"

strcmp("false","False")

Without running it through the PHP interpreter, figure out what this program prints.

$age = 12; $shoe_size = 13; if ($age > $shoe_size) { print "Message 1."; } elseif (($shoe_size++) && ($age > 20)) { print "Message 2."; } else { print "Message 3."; } print "Age: $age. Shoe Size: $shoe_size";


Use while( ) to print out a table of Fahrenheit and Celsius temperature equivalents from -50 degrees F to 50 degrees F in 5-degree increments. On the Fahrenheit temperature scale, water freezes at 32 degrees and boils at 212 degrees. On the Celsius scale, water freezes at 0 degrees and boils at 100 degrees. So, to convert from Fahrenheit to Celsius, you subtract 32 from the temperature, multiply by 5, and divide by 9. To convert from Celsius to Fahrenheit, you multiply by 9, divide by 5, and then add 32.

Modify your answer to Exercise 3 to use for( ) instead of while( ).



Free Join


Numbers

Numbers

Numbers in PHP are expressed using familiar notation, although you can't use commas or any other characters to group thousands. You don't have to do anything special to use a number with a decimal part as compared to an integer. Example 2-15 lists some valid numbers in PHP.

Numbers
print 56; print 56.3; print 56.30; print 0.774422; print 16777.216; print 0; print -213; print 1298317; print -9912111; print -12.52222; print 0.00;

Using Different Kinds of Numbers
Internally, the PHP interpreter makes a distinction between numbers with a decimal part and those without one. The former are called floating-point numbers and the latter are called integers. Floating-point numbers take their name from the fact that the decimal point can "float" around to represent different amounts of precision.

The PHP interpreter uses the math facilities of your operating system to represent numbers so the largest and smallest numbers you can use, as well as the number of decimal places you can have in a floating-point number, vary on different systems.

One distinction between the PHP interpreter's internal representation of integers and floating-point numbers is the exactness of how they're stored. The integer 47 is stored as exactly 47. The floating-point number 46.3 could be stored as 46.2999999. This affects the correct technique of how to compare numbers. Section 3.3 explains comparisons and shows how to properly compare floating-point numbers.

Arithmetic Operators
Doing math in PHP is a lot like doing math in elementary school, except it's much faster. Some basic operations between numbers are shown in Example 2-16.

Math operations
print 2 + 2; print 17 - 3.5; print 10 / 3; print 6 * 9;


The output of Example 2-16 is:

4 13.5 3.3333333333333 54


In addition to the plus sign (+) for addition, the minus sign (-) for subtraction, the forward slash (/) for division, and the asterisk (*) for multiplication, PHP also supports the percent sign (%) for modulus division. This returns the remainder of a division operation:

print 17 % 3;


This prints:

2


Since 17 divided by 3 is 5 with a remainder of 2, 17 % 3 equals 2. The modulus operator is most useful for printing rows whose colors alternate in an HTML table, as shown in Example 4-12.

The arithmetic operators, as well as the other PHP operators that you'll meet later in the book, fit into a strict precedence of operations. This is how the PHP interpreter decides in what order to do calculations if they are written ambiguously. For example, "3 + 4 * 2" could mean "add 3 and 4 and then multiply the result by 2," which results in 14. Or, it could mean "add 3 to the product of 4 and 2," which results in 11. In PHP (as well as the math world in general), multiplication has a higher precedence than addition, so the second interpretation is correct. First, the PHP interpreter multiplies 4 and 2, and then it adds 3 to the result.

The precedence table of all PHP operators is part of the online PHP Manual at php.baggyspace.com. You can avoid memorizing or repeatedly referring to this table, however, with a healthy dose of parentheses. Grouping operations inside parentheses unambiguously tells the PHP interpreter to do what's inside the parentheses first. The expression "(3 + 4) * 2" means "add 3 and 4 and then multiply the result by 2." The expression "3 + (4 * 2)" means "multiply 4 and 2 and then add 3 to the result."

Like other modern programming languages, you don't have to do anything special to ensure that the results of your calculations are properly represented as integers or floating-point numbers. Dividing one integer by another produces a floating-point result if the two integers don't divide evenly. Similarly, if you do something to an integer that makes it larger than the maximum allowable integer or smaller than the minimum possible integer, the PHP interpreter converts the result into a floating-point number so you get the proper result for your calculation.


free join