Cover | Table of Contents | Colophon
<form> or change how a page is presented
based on user actions.
<form>
widgets collect data, and JavaScript client-side scripts and PHP
server-side scripts perform validation.
if, if...else, and the
switch statements
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<title>Hello, world</title>
</head>
<body bgcolor="#ffffff">
<h1>
<?php
echo "Hello, world";
?>
</h1>
</body>
</html>
<?php echo "Hello, world"; ?>
true or false. There are
two branching statements in PHP: if, with the
optional else clause, and
switch, usually with two or more
case clauses.
if statement
conditionally controls execution and its use in PHP is as in any
other language. The basic format of an if
statement is to test whether a condition is true
and, if so, to execute one or more statements.
if statement executes the
echo statement and outputs the string when the
conditional expression, $var is greater than 5, is
true:
if ($var > 5) echo "The variable is greater than 5";
if statement executes only the one,
immediately following statement.
true, the statements within braces are executed.
If the expression isn't true,
none of the statements are executed. Consider an example in which
three statements are executed if the condition is
true:
if ($var > 5)
{
echo "The variable is greater than 5.";
// So, now let's set it to 5
$var = 5;
echo "In fact, now it is equal to 5.";
}
if statement can have an optional
else clause to execute a statement or block of
statements if the expression evaluates as false.
Consider an example:
if ($var > 5) echo "Variable greater than 5"; else echo "Variable less than or equal to 5";
else
clause to execute a block of statements in braces, as in this
example:
if ($var > 5)
{
echo "Variable is less than 5";
echo "-----------------------";
}
else
{
echo "Variable is equal to or larger than 5";
echo "-------------------------------------";
}true. There are four loop statements in PHP:
while, do...while,
for, and foreach. The first
three are general-purpose loop constructs, and
foreach is used exclusively with arrays.
while
loop is the simplest looping structure but
sometimes the least compact to use. The while loop
repeats one or more statements—the loop body—as long as a
condition remains true. The condition is checked
first, then the loop body is executed. So, the loop never executes if
the condition isn't initially
true. Just as in the if
statement, more than one statement can be placed in braces to form
the loop body.
while
statement by printing out the integers from 1 to 10 separated by a
space character:
$counter = 1;
while ($counter < 11)
{
echo $counter;
echo " ";
// Add one to $counter
$counter++;
}
while and
do...while
is the point at which the condition is
checked. In do...while, the condition is checked
after the loop body is executed. As long as the condition remains
true, the loop body is repeated.
while
example as follows:
$counter = 1;
do
{
echo $counter;
echo " ";
$counter++;
} while ($counter < 11);
while and
do...while can be seen in the following example:
$counter = 100;
do
{
echo $counter;
echo " ";
$counter++;
} while ($counter < 11);
100, because the body of the
loop is executed once before the condition is evaluated as
false.
do...while loop is the least-frequently used
loop construct, probably because executing a loop body once when a
condition is
<html> <head> <title>The Times-Tables</title> </head> <body bgcolor="#ffffff"> <h1>The Times Tables</h1> <p><b>The 1 Times Table</b> <br>1 x 1 = 1 <br><b>2 x 1 = 2</b> <br>3 x 1 = 3 <br><b>4 x 1 = 4</b> <br>5 x 1 = 5
<head> components and the
<h1>The Times Tables</h1> heading at
the top of the web page. Similarly, the last two lines are HTML that
finishes the document: </body> and
</html>.
<?php and finishes with the close tag
?>.
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<title>The Times-Tables</title>
</head>
<body bgcolor="#ffffff">
<h1>The Times Tables</h1>
<?php
// Go through each table
for($table=1; $table<13; $table++)
{
echo "<p><b>The " . $table . " Times Table</b>\n";
// Produce 12 lines for each table
for($counter=1; $counter<13; $counter++)
{
$answer = $table * $counter;
// Is this an even-number counter?
if ($counter % 2 == 0)
// Yes, so print this line in bold
echo "<br><b>$counter x $table = " .
"$answer</b>";
else
// No, so print this in normal face
echo "<br>$counter x $table = $answer";
}
}
?>
</body>
</html>array( )
language construct that creates arrays. The
following examples show how arrays of integers and strings can be
constructed and assigned to variables for later use:
$numbers = array(5, 4, 3, 2, 1);
$words = array("Web", "Database", "Applications");
// Print the third element from the array
// of integers: 3
echo $numbers[2];
// Print the first element from the array
// of strings: "Web"
echo $words[0];
$newArray[0] = "Potatoes"; $newArray[1] = "Carrots"; $newArray[2] = "Spinach"; // Oops, replace the third element $newArray[2] = "Tomatoes";
$numbers = array(1=>"one", "two", "three", "four");
$oddNumbers = array(1=>"one", 3=>"three", 5=>"five");
\' to include a single
quote and \\ to include a backslash.
\t, \n, and
\r, respectively. To include a backslash, a dollar
sign, or a double quote in a double-quoted string, use the escape
sequences \\, \$, or
\".
\366 or the hexadecimal sequence
\xf6 are used:
//Print a string that includes a lowercase //o with the umlaut mark echo "See you at the G\xf6teborg Film Festival";
\000 to
\377 in octal notation or \x00
to \xff in hexadecimal notation.
$var assigned with a string that contains
a newline character:
// This is Ok. $var contains a newline character
$var = 'The quick brown fox
jumps over the lazy dog';ereg()
:
boolean ereg(string pattern, string subject [, array var])
ereg( ) returns true if the
regular expression pattern is found in the
subject string. We discuss how the
ereg( ) function can extract values into the
optional array variable var later in this
section.
ereg()
is called to find the literal pattern "cat" in the
subject string "raining cats and dogs":
// prints "Found a cat"
if (ereg("cat", "raining cats and dogs"))
echo "Found 'cat'";
"cat" matches the
subject string, and the fragment prints
"
$var1 = -2106036000; // 16/08/1902 $var2 = 502808400; // 24/08/1984 // $result is assigned false $result = $var1 < $var2; // $result is assigned true as expected $result = (float) $var1 < (float) $var2;
integer time( )
// prints the current timestamp: e.g., 1008553254 echo time( );
+, -,
/, *, and %,
PHP provides the usual array of mathematical
library
functions. In this section, we present some of the library functions
that are used with integer and float numbers.
abs(
) function:
integer abs(integer number) float abs(float number)
abs( )
on floats and integers:
echo abs(-1); // prints 1 echo abs(1); // prints 1 echo abs(-145.89); // prints 145.89 echo abs(145.89); // prints 145.89
ceil( )
and floor(
)
functions can return the integer value above and below a fractional
value, respectively:
float ceil(float value) float floor(float value)
echo ceil(27.3); // prints 28 echo floor(27.3); // prints 27
round( )
function uses 4/5 rounding rules to round up or down a
value to a given precision:
float round(float value [, integer precision])
echo round(10.4); // prints 10 echo round(10.5); // prints 11 echo round(2.40964, 3); // prints 2.410 echo round(567234.56, -3); // prints 567000 echo round(567234.56, -4); // prints 570000
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Simple Function Call</title>
</head>
<body bgcolor="#ffffff">
<?php
function bold($string)
{
echo "<b>" . $string . "</b>\n";
}
// First example function call (with a static string)
echo "this is not bold\n";
bold("this is bold");
echo "this is again not bold\n";
// Second example function call (with a variable)
$myString = "this is bold";
bold($myString);
?>
</body></html>
bold(
)
, which
takes one parameter, $string, and prints that
string prefixed by a bold <b> tag and
suffixed with a </b> tag. The
bold( ) function, defined here, can be used with
a string literal expression or a variable, as shown.
heading(
)
,
which returns a string using the return statement:
function heading($text, $headingLevel)
{
switch ($headingLevel)
case 1:
$result = "<h1>" . ucwords($text) . "</h1>";
break;
case 2:
$result = "<h2>" . ucwords($text) . "</h2>";
break;
case 3:
$result = "<h3>" . ucfirst($text) . "</h3>";
break;
default:
$result = "<p><b>" . ucfirst($text) . "</b>";
return($result);
}
$test = "user defined functions";
echo heading($test, 2);
$count and
$startPoint—and four functions that use
these member variables. Collectively, the variables and the functions
are members of the class Counter.
<?php
// A class that defines a counter.
class Counter
{
// Member Variables
var $count = 0;
var $startPoint = 0;
// Methods
function startCountAt($i)
{
$this->count = $i;
$this->startPoint = $i;
}
function increment( )
{
$this->count++;
}
function reset( )
{
$this->count = $this->startPoint;
}
function showvalue( )
{
print $this->count;
}
}
?>
new operator. An object of class
Counter can be created and assigned to a
variable as follows:
$aCounter = new Counter;
$aCounter is created, the member
variables and functions of the new object can be used. Members of the
object, both variables and functions, are accessed using the
</table>,
</form>, or </frame>
closing tags are omitted, the page may not be rendered.
http://validator.w3.org retrieves a page,
analyzes the correctness of the HTML, and issues a report.
It's an excellent assistant for debugging and
last-minute compliance checks before delivery of an application.
flush(
) function after echo,
print, or printf statements.
flush( ) empties the output buffer maintained by
the PHP engine, sending all currently buffered output to the web
server. The function has no effect on buffering at the web server or
the web browser, but it ensures that all data output by the script is
available to the web server to be transmitted and rendered by a
browser. Remember to remove the flush(
)
function calls after debugging, because
unnecessary flushing may prevent efficient buffering of output by the
PHP scripting engine.
SELECT statement for querying, with
examples of simple and advanced queries
INSERT, UPDATE,
DELETE, and SELECT, which add,
change, remove, and search data in a database, respectively.
winery
ID, winery
name, address, and
region
ID. A table contains the
data as rows or records, and a row contains attribute values. The
winery table has five rows, one for each winery
managed by the database, and each row has a set of values. For
example, the first winery has a winery
ID value of 1, the winery
name value Moss Brothers, and an
addressgzip -d winestore.database.tar.gz
tar xvf winestore.database.tar
/usr/local/bin/mysqladmin -uroot -ppassword version
root user, and start the MySQL server using:
/usr/local/bin/safe_mysqld --user=mysql &
/usr/local/bin/mysql -uusername -ppassword < winestore.database
/usr/local/bin/mysql -uusername -ppassword
% /usr/local/bin/mysql -uhugh -pshhh
%.
Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 36 to server version: 3.22.38 Type 'help' for help. mysql>
mysql>
prompt and, after executing any command or statement, it redisplays
the prompt. For example, you might issue the statement:
mysql> SELECT NOW( );
+---------------------+ | NOW( ) | +---------------------+ | 2002-01-01 13:48:07 | +---------------------+ 1 row in set (0.00 sec) mysql>
mysql> prompt. We discuss the
SELECT statement later in this chapter.
SELECT
statement ends in a semicolon. Almost all SQL command interpreters
permit any amount of whitespace—spaces, tabs, or carriage
returns—in SQL statements, and they check syntax and execute
statements only after encountering a semicolon that is followed by a
press of the Enter key. We have used uppercase for the SQL statements
throughout this book. However, any mix of upper- and lowercase is
equivalent.
CREATE DATABASE
statement can create a new,
empty database without any tables or data. The following statement
creates a
database
called winestore:
mysql> CREATE DATABASE winestore;
mysql> use winestore
mysql> prompt from the command examples.
use winestore command, you then
usually issue commands to create the tables in the database, as shown
in Example 3-1. (You already created the tables in
the winestore database in Section 3.2 of this chapter).
Let's look at one of these tables, the
customer table. The statement that created this
table is shown in Example 3-2.
CREATE TABLE customer ( cust_id int(5) DEFAULT '0' NOT NULL auto_increment, surname varchar(50) NOT NULL, firstname varchar(50) NOT NULL, initial char(1), title varchar(10), addressline1 varchar(50) NOT NULL, addressline2 varchar(50), addressline3 varchar(50), city varchar(20) NOT NULL, state varchar(20), zipcode varchar(5), country varchar(20) DEFAULT 'Australia', phone varchar(15), fax varchar(15), email varchar(30) NOT NULL, salary int(7), birth_date date( ), PRIMARY KEY (cust_id), KEY names (surname,firstname) );
SELECT, INSERT,
DELETE, and UPDATE. We describe
the last three statements in this section. While
SELECT is also part of DML, we cover it in its own
section, Section 3.6. Longer
worked examples using all the statements can be found in the section
Section 3.8.
INSERT INTO customer
VALUES (NULL,'Marzalla','Dimitria', 'F','Mrs',
'171 Titshall Cl','','','St Albans','WA',
'7608','Australia','(618)63576028','',
'dimitria@lucaston.com','1969-11-08',35000);
NULL—is
inserted into the first attribute of customer.
The first attribute of customer is cust_id
and—because cust_id has the
auto_increment modifier and this is the first
row—a 1 is inserted as the cust_id. The
value "Marzalla" is then inserted
into the second attribute surname,
"Dimitria" into
firstname, and so on. The number of values
inserted must be the same as the number of attributes in the table.
To create an INSERT statement in this format, you
need to understand the ordering of attributes in the table.