Chapter 02
Chapter 02
Chapter 02
How to code
a PHP application
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 1
Objectives
Applied
1. Given the specifications for a PHP application that requires only
the skills and language elements presented in this chapter, code,
test, and debug the application. That includes these skills:
Creating variables with valid names and assigning values to
them
Using literals and concatenating strings
Using the built-in $_GET and $_POST arrays
Using echo statements to display data on a page
Coding string and numeric expressions
Using compound assignment operators
Using the built-in number_format, date, isset, empty, and
is_numeric functions
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 2
Objectives (continued)
Applied (continued)
Coding conditional expressions
Coding if, while, and for statements
Using built-in functions like include and require to pass
control to another page
2. Access and use the online PHP documentation.
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 3
Objectives (continued)
Knowledge
1. Explain how PHP is embedded within an HTML document.
2. Distinguish between PHP statements and comments.
3. Describe these PHP data types: integer, double, Boolean, and
string.
4. List the rules for creating a PHP variable name.
5. Describe the code for declaring a variable and assigning a value to
it.
6. Describe the use of the built-in $_GET and $_POST arrays.
7. Describe the use of the echo statement.
8. Describe the rules for evaluating an arithmetic expression,
including order of precedence and the use of parentheses.
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 4
Objectives (continued)
Knowledge (continued)
9. Describe the use of these built-in functions: number_format, date,
isset, is_numeric, include, and require.
10. Describe the rules for evaluating a conditional expression,
including order of precedence and the use of parentheses.
11. Describe the flow of control of an if, while, or for statement.
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 5
A PHP file that includes HTML and embedded PHP
<?php
// get the data from the request
$first_name = $_GET['first_name'];
$last_name = $_GET['last_name'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional
...>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Name Test</title>
<link rel="stylesheet" type="text/css"
href="main.css"/>
</head>
<body>
<h2>Welcome</h2>
<p>First name: <?php echo $first_name; ?></p>
<p>Last name: <?php echo $last_name; ?></p>
</body>
</html>
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 6
The PHP file displayed in a browser
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 7
PHP code: comments and statements
<?php
/*********************************************
* This program calculates the discount for a
* price that's entered by the user
********************************************/
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 8
Syntax rules
PHP statements end with a semicolon.
PHP ignores extra whitespace in statements.
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 9
Integer values (whole numbers)
15 // an integer
-21 // a negative integer
String values
'Ray Harris' // a string with single quotes
"Ray Harris" // a string with double quotes
'' // an empty string
null // a NULL value
Double values that use scientific notation
3.7e9 // equivalent to 3700000000
4.5e-9 // equivalent to 0.0000000037
-3.7e9 // equivalent to -3700000000
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 10
How assign string expressions
Use single quotes to improve PHP efficiency
$first_name = 'Bob';
$last_name = 'Roberts';
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 11
Using the assignment operator (=)
as you declare a variable and give it a value
$count = 10; // an integer literal
$list_price = 9.50; // a double literal
$first_name = 'Bob'; // a string literal
$first_name = "Bob"; // a string literal
$is_valid = false; // a Boolean literal
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 12
Rules for creating variable names
Variable names are case-sensitive.
Variable names can contain letters, numbers, and underscores.
Variable names can’t contain special characters.
Variable names can’t begin with a digit or two underscores.
Variable names can’t use names that are reserved by PHP such as
the variable named $this that’s reserved for use with objects.
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 13
How to declare a constant
define('MAX_QTY', 100); // an integer constant
define('PI', 3.14159265); // a double constant
define('MALE', 'm'); // a string constant
Using a constant
Since the value of a constant can’t be changed, don’t code the $
when you declare it or use it.
Most programmers use all caps for constants.
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 14
How to use the concatenation operator (.)
How to use the concatenation operator for simple joins
$first_name = 'Bob';
$last_name = 'Roberts';
$name = 'Name: ' . $first_name; // Name: Bob
$name = $first_name . ' ' . $last_name; // Bob Roberts
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 15
The syntax for the echo statement
echo string_expression;
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 16
Common arithmetic operators
Operator Example Result
+ 5 + 7 12
- 5 - 12 -7
* 6 * 7 42
/ 13 / 4 3.25
% 13 % 4 1
++ $counter++ adds 1 to counter
-- $counter-- subtracts 1 from counter
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 17
Some simple numeric expressions
$x = 14;
$y = 8;
$result = $x + $y; // 22
$result = $x - $y; // 6
$result = $x * $y; // 112
$result = $x / $y; // 1.75
$result = $x % $y; // 6
$x++; // 15
$y--; // 7
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 18
The order of precedence
Order Operators Direction
1 ++ Left to right
2 -- Left to right
3 * / % Left to right
4 + - Left to right
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 20
Three ways to increment a counter variable
The standard assignment operator
$count = 1;
$count = $count + 1;
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 21
More examples
How to append numeric data to a string variable
$message = 'Months: ';
$months = 120;
$message .= $months; // 'Months: 120'
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 22
A function for formatting numbers
number_format($number[, $decimals])
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 23
A function for getting the current date
date($format)
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 24
An HTML form that does an HTTP GET request
<form action="display.php" method="get">
<label>First name: </label>
<input type="text" name="first_name"/><br />
<label>Last name: </label>
<input type="text" name="last_name"/><br />
<label> </label>
<input type="submit" value="Submit"/>
</form>
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 25
A PHP page for an HTTP POST request
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 26
When to use the HTTP GET method
When the request is for a page that gets data from a database
server.
When the request can be executed multiple times without causing
any problems.
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 27
The first page (index.html)
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 28
The second page (product_discount.php)
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 29
The code for the form on the first page
<form action="display_discount.php" method="post">
<div id="data">
<label>Product Description:</label>
<input type="text"
name="product_description"/><br />
<label>List Price:</label>
<input type="text" name="list_price"/><br />
<label>Discount Percent:</label>
<input type="text" name="discount_percent"/>%<br />
</div>
<div id="buttons">
<label> </label>
<input type="submit" value="Calculate Discount" />
<br />
</div>
</form>
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 30
The PHP file (display_discount.php)
<?php
// get the data from the form
$product_description = $_POST['product_description'];
$list_price = $_POST['list_price'];
$discount_percent = $_POST['discount_percent'];
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 31
The PHP file (display_discount.php) (continued)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional
...>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Product Discount Calculator</title>
<link rel="stylesheet" type="text/css"
href="main.css"/>
</head>
<body>
<div id="content">
<h1>Product Discount Calculator</h1>
<label>Product Description:</label>
<span><?php echo $product_description; ?>
</span><br />
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 32
The PHP file (display_discount.php) (continued)
<label>List Price:</label>
<span><?php echo $list_price_formatted; ?>
</span><br />
<label>Standard Discount:</label>
<span><?php echo $discount_percent_formatted; ?>
</span><br />
<label>Discount Amount:</label>
<span><?php echo $discount_formatted; ?>
</span><br />
<label>Discount Price:</label>
<span><?php echo $discount_price_formatted; ?>
</span><br />
</div>
</body>
</html>
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 33
The relational operators
Operator Example
== $last_name == "Harris"
$test_score == 10
!= $first_name != "Ray"
$months != 0
< $age < 18
<= $investment <= 0
> $test_score > 100
>= $rate / 100 >= 0.1
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 34
Three functions for checking variable values
isset($var)
empty($var)
is_numeric($var)
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 35
An if statement with no other clauses
if ( $price <= 0 ) {
$message = 'Price must be greater than zero.';
}
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 36
An if statement with else if and else clauses
if ( empty($investment) ) {
$message = 'Investment is a required field.';
} else if ( !is_numeric($investment) ) {
$message = 'Investment must be a valid number.';
} else if ( $investment <= 0 ) {
$message = 'Investment must be greater than zero.';
} else {
$message = 'Investment is valid!';
}
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 37
A compound conditional expression
if ( empty($investment) || !is_numeric($investment)
|| $investment <= 0 ) {
$message =
'Investment must be a valid number > zero.';
}
A nested if statement
if ( empty($months) || !is_numeric($months)
|| $months <= 0 ) {
$message = 'Please enter a number of months > zero.';
} else {
$years = $months / 12;
if ( $years > 1 ) {
$message = 'A long-term investment.';
} else {
$message = 'A short-term investment.';
}
}
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 38
A while loop that stores the numbers 1 through 5
$counter = 1;
while ($counter <= 5) {
$message = $message . $counter . '|';
$counter++;
}
// $message = 1|2|3|4|5|
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 39
A for loop that stores the numbers 1 through 5
for ($counter = 1; $counter <= 5; $counter++) {
$message = $message . $counter . '|';
}
// $message = 1|2|3|4|5|
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 40
A while loop that calculates the future value
of a one-time investment
$investment = 1000;
$interest_rate = .01;
$years = 25;
$future_value = $investment;
$i = 1;
while ($i <= $years) {
$future_value =
($future_value + ($future_value * $interest_rate);
$i++;
}
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 41
A for loop that calculates the future value
of a one-time investment
$investment = 1000;
$interest_rate = .01;
$years = 25;
$future_value = $investment;
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 42
Built-in functions that pass control
include($path)
• Inserts and runs the specified file. If this functions fails, it
causes a warning that can allow the script to continue.
include_once($path)
• Same as include, but it makes sure the file is included only
once.
require($path)
• Same as include, but if it fails it causes a fatal error that
stops the script.
require_once($path)
exit([$status])
• Exits the current php script
die([$status])
• Same as exit
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 43
The include function
include 'index.php'; // parentheses are optional
include('index.php'); // index.php in the current
// directory
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 44
How to pass control to another PHP file in the
current directory
if ($is_valid) {
include('process_data.php');
exit();
}
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 45
The first page
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 46
The second page
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 47
The first page with an error message
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 48
The index.php file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional
...>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" type="text/css" href="main.css"/>
</head>
<body>
<div id="content">
<h1>Future Value Calculator</h1>
<?php if (!empty($error_message)) { ?>
<p class="error"><?php echo $error_message; ?></p>
<?php } ?>
<form action="display_results.php" method="post">
<div id="data">
<label>Investment Amount:</label>
<input type="text" name="investment"
value="<?php echo $investment; ?>"/><br />
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 49
The index.php file (continued)
<label>Yearly Interest Rate:</label>
<input type="text" name="interest_rate"
value="<?php echo $interest_rate; ?>"/><br />
<label>Number of Years:</label>
<input type="text" name="years"
value="<?php echo $years; ?>"/><br />
</div>
<div id="buttons">
<label> </label>
<input type="submit" value="Calculate"/><br />
</div>
</form>
</div>
</body>
</html>
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 50
The display_results.php file
<?php
// get the data from the form
$investment = $_POST['investment'];
$interest_rate = $_POST['interest_rate'];
$years = $_POST['years'];
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 51
The display_results.php file (continued)
// validate interest rate entry
} else if ( empty($interest_rate) ) {
$error_message =
'Interest rate is a required field.';
} else if ( !is_numeric($interest_rate) ) {
$error_message =
'Interest rate must be a valid number.';
} else if ( $interest_rate <= 0 ) {
$error_message =
'Interest rate must be greater than zero.';
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 52
The display_results.php file (continued)
// if no invalid entries,
// set error message to empty string
} else {
$error_message = '';
}
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 53
The display_results.php file (continued)
// apply currency and percent formatting
$investment_f = '$'.number_format($investment, 2);
$yearly_rate_f = $interest_rate.'%';
$future_value_f = '$'.number_format($future_value, 2);
?>
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 54
The display_results.php file (continued)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional
...>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" type="text/css"
href="main.css"/>
</head>
<body>
<div id="content">
<h1>Future Value Calculator</h1>
<label>Investment Amount:</label>
<span><?php echo $investment_f; ?></span><br />
<label>Yearly Interest Rate:</label>
<span><?php echo $yearly_rate_f; ?></span><br />
<label>Number of Years:</label>
<span><?php echo $years; ?></span><br />
<label>Future Value:</label>
<span><?php echo $future_value_f; ?></span><br />
</div>
</body>
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 55
The URL for the PHP documentation
http://php.net/docs.php
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 56
Documentation for the if statement
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 57
How to access the PHP manual
On the first page of the web site, click on the name of the language
that you want to use. That will access the first page of the PHP
manual.
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 58