Workshop 2
How to code
a PHP application
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, 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 intdiv(), number_format(), date(), isset(),
empty(), and is_numeric() functions
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 2
Objectives (continued)
Applied (continued)
Using the htmlspecialchars() function to escape special
characters on a page
Using the filter_input() function to filter input from the $_GET
and $_POST arrays
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.
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 3
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>
<html>
<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>
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 4
The PHP file displayed in a browser
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 5
PHP code: comments and statements
<?php
/*********************************************
* This program calculates the discount for a
* price that's entered by the user
********************************************/
// get the data from the form
$list_price = $_GET['list_price'];
// calculate the discount
$discount_percent = .20; // 20% discount
$discount_amount =
$subtotal * $discount_percent;
$discount_price =
$subtotal - $discount_amount;
?>
Another way to code single-line comments
# calculate the discount
$discount_percent = .20; # 20% discount
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 6
Syntax rules
PHP statements end with a semicolon.
PHP ignores extra whitespace in statements.
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 7
The six PHP data types
integer
double
boolean
string
array
object
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 8
Integer values (whole numbers)
15 // an integer
-21 // a negative integer
Double values (numbers with decimal positions)
21.5 // a floating-point value
-124.82 // a negative floating-point value
The two Boolean values
true // equivalent to true, yes, or on
false // equivalent to false, no, off, or 0
String values
'Ray Harris' // a string with single quotes
"Ray Harris" // a string with double quotes
'' // an empty string
null // a NULL value
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 9
Double values that use scientific notation
3.7e9 // equivalent to 3700000000
4.5e-9 // equivalent to 0.0000000037
-3.7e9 // equivalent to -3700000000
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 10
Using the assignment operator (=)
as you declare a variable and assign 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
$product_count = $count; // $product_count is 10
$price = $list_price; // $price is 9.50
$name = $first_name; // $name is "Bob"
$is_new = $is_valid; // $is_new is FALSE
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 11
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.
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 12
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
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 13
Activity 1
Fill in the blanks
1. To embed PHP within HTML, you start a tag with
________________, you code the embedded PHP
statements, and you end the tag with ?>.
2. The ________________ in a block of PHP code are ignored.
3. The ________________ data type is used to store a true or
false value.
4. The variables in PHP are easy to spot because they always
start with ________________.
5. A variable name in PHP can only contain letters, numbers,
and ________________.
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 14
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>
The URL for the HTTP GET request
//localhost/.../display.php?first_name=Ray&last_name=Harris
Getting the data and storing it in variables
$first_name = $_GET['first_name'];
$last_name = $_GET['last_name'];
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 15
An <a> tag that performs an HTTP GET request
<a href="display.php?first_name=Joel&last_name=Murach">
Display Name
</a>
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 16
A PHP page for an HTTP POST request
An HTML form that specifies the POST method
<form action="display.php" method="post">
Code that gets the data from the $_POST array
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 17
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.
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 18
When to use the HTTP POST method
When the request is for a page that writes data to a database server.
When executing the request multiple times may cause problems.
When you don’t want to include the parameters in the URL for
security reasons.
When you don’t want users to be able to include parameters when
they bookmark a page.
When you need to transfer more than 4 KB of data.
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 19
How to assign string expressions
Use single quotes to improve PHP efficiency
$first_name = 'Bob';
$last_name = 'Roberts';
Assign NULL values and empty strings
$address2 = ''; // an empty string
$address2 = null; // a NULL value
Use double quotes for variable substitution
$name = "Name: $first_name"; // Name: Bob
$name = "$first_name $last_name"; // Bob Roberts
Mix single and double quotes for special purposes
$last_name = "O'Brien"; // O'Brien
$line = 'She said, "Hi."'; // She said, "Hi."
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 20
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
How to join a number to a string
$price = 19.99;
$price_string = 'Price: ' . $price; // Price: 19.99
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 21
The syntax for the echo statement
echo string_expression;
How to use an echo statement
<p>Name: <?php echo $name; ?></p>
How to use an echo statement
with the htmlspecialchars() function
<p>Name: <?php echo htmlspecialchars($name); ?></p>
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 22
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
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 23
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
$x--; // 14
A statement that uses the intdiv() function
(PHP 7 and later)
$result = intdiv($x, $y); // 1
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 24
Statements that calculate a discount
$list_price = 19.95;
$discount_percent = 20;
$discount_amount = $list_price * $discount_percent * .01;
$discount_price = $list_price - $discount_amount;
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 25
The order of precedence
Order Operators Direction
1 ++ Left to right
2 -- Left to right
3 * / % Left to right
4 + - Left to right
Order of precedence and the use of parentheses
3 + 4 * 5 // 23
(3 + 4) * 5 // 35
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 26
The compound assignment operators
.=
+=
-=
*=
/=
%=
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 27
Two ways to append string data to a variable
The standard assignment operator
$name = 'Ray ';
$name = $name . 'Harris'; // 'Ray Harris'
A compound assignment operator
$name = 'Ray ';
$name .= 'Harris'; // 'Ray Harris'
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 28
Three ways to increment a counter variable
The standard assignment operator
$count = 1;
$count = $count + 1;
The compound assignment operator
$count = 1;
$count += 1;
The increment operator
$count = 1;
$count++;
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 29
More examples
How to append numeric data to a string variable
$message = 'Months: ';
$months = 120;
$message .= $months; // 'Months: 120'
How to work with numeric data
$subtotal = 24.50;
$subtotal += 75.50; // 100
$subtotal *= .9; // 90 (100 * .9)
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 30
A function for formatting numbers
number_format($number[, $decimals])
Statements that format numbers
$nf = number_format(12345); // 12,345
$nf = number_format(12345, 2); // 12,345.00
$nf = number_format(12345.674, 2); // 12,345.67
$nf = number_format(12345.675, 2); // 12,345.68
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 31
A function for getting the current date
date($format)
Commonly used characters for date formatting
Character Description
Y A four-digit year such as 2017.
y A two-digit year such as 17.
m Numeric representation of the month with leading
zeros (01-12).
d Numeric representation of the day of the month with
leading zeros (01-31).
Statements that format a date
$date = date('Y-m-d'); // 2017-09-12
$date = date('m/d/y'); // 09/12/17
$date = date('m.d.Y'); // 09.12.2017
$date = date('Y'); // 2017
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 32
Three functions for checking variable values
isset($var)
empty($var)
is_numeric($var)
Function calls that check variable values
isset($name) // TRUE if $name has been set
// and is not NULL
empty($name) // TRUE if $name is empty
is_numeric($price) // TRUE if $price is a number
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 33
Two functions for converting user-entered data
for display
Name Description
htmlspecialchars($string) Converts certain HTML special
characters (&, ', ", <, and >) to their
corresponding HTML entities and
returns the resulting string.
htmlentities($string) Converts all HTML characters that
have corresponding HTML entities
and returns the resulting string.
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 34
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
=== $investment === FALSE
$years === NULL
!== $investment !== FALSE
$years !== NULL
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 35
The logical operators in order of precedence
Operator Example
! !is_numeric($age)
&& $age > 17 && $score < 70
|| !is_numeric($rate) || $rate < 0
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 36
Activity 2 Fill in the blanks
1. In a simple assignment statement, you code the variable name
followed by the ________________ operator.
2. To get the data that is submitted with an HTTP GET request,
you use PHP to get the data from the built-in
________________ array.
3. To use PHP to send data to the browser, you use the
________________ statement.
4. In an arithmetic expression, division is done before
multiplication, but you can override that by using
________________.
5. When you call a function like the number_format() function
that returns a value, you usually ________________ the result
of the function to a variable.
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 37
An if statement with no other clauses
if ( $price <= 0 ) {
$message = 'Price must be greater than zero.';
}
An if statement with an else clause
if ( empty($first_name) ) {
$message = 'You must enter your first name.';
} else {
$message = 'Hello ' . $first_name . '!';
}
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 38
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!';
}
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 39
A compound conditional expression
if ( empty($investment) || !is_numeric($investment) ||
$investment <= 0 ) {
$message = 'Investment must be a valid number greater than
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.';
}
}
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 40
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|
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 41
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|
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 42
The include function
include 'index.php'; // parentheses are optional
include('index.php'); // index.php in the current
// directory
The require function
require('index.php'); // index.php in the current
// directory
The exit function
exit; // parentheses are optional
exit();
exit('Unable to connect to DB.');
// passes a message to the browser
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 43
How to pass control to another PHP file
in the current directory
if ($is_valid) {
include('process_data.php');
exit();
}
How to navigate up and down directories
include('view/header.php'); // down one directory
include('./error.php'); // in the current directory
include('../error.php'); // up one directory
include('../../error.php'); // up two directories
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 44
The URL for the PHP documentation
http://php.net/docs.php
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 45
Documentation for the isset() function
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 46
How to access the PHP manual
On the first page of the website, click on the name of the language
that you want to use. That will access the first page of the PHP
manual, which includes a table of contents.
How to use the PHP manual
Scroll down the contents until you find the link you’re looking for,
click on it, and continue this process until the right information is
displayed.
As you display information, you can use the links in the right pane
of the window to display other topics at the same level.
How to find the documentation for a function
when you know its name
Type the function name in the Search text box and select from the
autocomplete list.
© 2017, Mike Murach & Associates, Inc.
Murach's PHP and MySQL (3rd Ed.) C2, Slide 47