Server-Side Scripting with PHP ISYS 475. PHP Manual Website

Preview:

Citation preview

Server-Side Scripting with PHP

ISYS 475

PHP Manual Website

• http://www.php.net/manual/en/

Hyper Text Transfer Protocol: Request & Response

Web ServerBrowser

HTTP Request

HTTP Response

Web Application

Data Sent with Request and Response

• Request: – requested URL, cookies, queryString, data from a

form, etc.

• Response:– Web page content in HTML code– Cookies– Etc.

PHP Language Syntax

PHP Variables• Variables in PHP are represented by a dollar

sign followed by the name of the variable. • The variable name is case-sensitive.• Variable names can contain letters, numbers,

and underscores.For examples: $num1, $_mySalary

• Variable names can’t begin with a digit or two underscores.

• Variables do not have intrinsic types – it depends on the first data assigned to it.

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

Syntax rules PHP statements end with a semicolon.

PHP ignores extra whitespace in statements.

Basic Data Types• Integers • Doubles: are floating-point numbers• Booleans: two possible values either true or false.• NULL: is a special type that only has one value: NULL.• Strings: are sequences of characters• Arrays: are named and indexed collections of other

values.• Objects: are instances of programmer-defined classes• Resources: are special variables that hold references

to resources external to PHP (such as database connections).

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, or off

String values 'Ray Harris' // a string with single quotes "Ray Harris" // a string with double quotes '' // an empty string null // a NULL value

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 $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

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; not working for single quotes $name = "Name: $first_name"; // Name: Bob

$name1 = 'Name: $first_name'; // Name: $first_name ***********

$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."

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

$name="$first_name $last_name";echo $name;echo "My name is $name "

Without using concatenation:

The syntax for the echo statement echo string_expression;

How to use an echo statement within HTML <p>Name: <?php echo $name; ?></p>

How to use an echo statement to output HTML tags and data

<?php echo '<p>Name: ' . $name . '</p>'; ?>

Note: echo and print have the same function.

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

Math Functions:http://www.php.net/manual/en/ref.math.php

Examples:

pow ( number $base , number $exp)

echo pow(2, 3);

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

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

The compound assignment operators .=

+=

-=

*=

/=

%=

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

Difference between these functions:http://techtalk.virendrachandak.com/php-isset-vs-empty-vs-is_null/

PHP Superglobal variables• Superglobals are built-in variables that are always

available in all scopes

$_GET

• An associative array of variables passed to the current script via the URL parameters (queryString).

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>&nbsp;</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'];

An <a> tag that performs an HTTP GET request <a href="display.php?first_name=Joel&last_name=Murach"> Display Name </a>

$_POST

• An associative array of variables passed to the current script via the HTTP POST method.

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'];

Example: Compute Sum

<div> <form name="sumForm" method="post" action="computeSum.php"> <label>Value 1:</label> <input type="text" name="num1" value="" /><br><br> <label>Value 2:</label><input type="text" name="num2" value="" /><br><br> <label>Sum:</label> <input type="text" name="sum" value="" /><br><br> <input type="submit" value="Compute Sum" name="btnSubmit" /> </form> </div>

Example: computeSum.php

<body> <?php $num1=$_POST["num1"]; $num2=$_POST["num2"]; $sum=$num1+$num2; echo "<label>Value 1:</label> <input type='text' name='num1' value='$num1'/><br><br>"; echo "<label>Value 2:</label> <input type='text' name='num2' value='$num2' /><br><br>"; echo "<label>Sum:</label> <input type='text' name='sum' value='$sum' /><br><br>";

?> </body>

Embed PHP code in HTMLUsing PHP Expression: <?php ?>

<body> <?php $num1=$_POST["num1"]; $num2=$_POST["num2"]; $sum=$num1+$num2; ?> <label>Value 1:</label> <input type="text" name="num1" value="<?php echo $num1;?>" /><br><br> <label>Value 2:</label><input type="text" name="num2" value="<?php echo $num2;?>" /><br><br> <label>Sum:</label> <input type="text" name="sum" value="<?php echo $sum;?>" /><br><br> </body>

Compute Future Value:Process form with various controls

Form Code<form name="fvForm" method="post" action="computeFV.php"> Enter present value: <input type="text" name="PV" value="" /><br><br> Select interest rate: <select name="Rate"> <option value=.04>4%</option> <option value=.05>5%</option> <option value=.06>6%</option> <option value=.07>7%</option> <option value=.08>8%</option> </select><br><br> Select year: <br> <input type="radio" name="Year" value="10" />10-year<br> <input type="radio" name="Year" value="15" />15-year<br> <input type="radio" name="Year" value="30" />30-year<br><br>

<input type="submit" value="ComputeFV" name="btnCompute" /> </form>

PHP Code Example

<?php $myPV=$_POST["PV"]; $myRate=$_POST["Rate"]; $myYear=$_POST["Year"]; $FV=$myPV*pow(1+$myRate,$myYear); echo "FutureValue is:" . $FV; ?>

number_format — Format a number with grouped thousands

• If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.

• If two parameters are given, number will be formatted with decimals with a dot (".") in front, and a comma (",") between every group of thousands.

Examples: Comma and Currency format

$number = 1234.56;$formated_number = number_format($number);// 1,235

$formated_number = number_format($number,2);// 1,235.56

$formated_number = “$” . number_format($number,2);// $1,235.56

echo "FutureValue is: $" . number_format($FV,2);

NOTE: money_format() is undefined in Windows.

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

The logical operators in order of precedence

Operator Example ! !is_numeric($age)

&& $age > 17 && $score < 70

|| !is_numeric($rate) || $rate < 0

Decision with If statement

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.'!';

}

Note: { } is optional if only one statement

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!'; }

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|

PHP Loops

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|

Compute future value uses formula or a loop$FV = $myPV;for ($i = 1; $i <= $myYear; $i++) { $FV= $FV + $FV * $myRate; }

<form name="fvForm" method="post" action="computeFVloop.php"> Enter present value: <input type="text" name="PV" value="" /><br><br> Select interest rate: <select name="Rate"> <option value=.04>4%</option> <option value=.05>5%</option> <option value=.06>6%</option> <option value=.07>7%</option> <option value=.08>8%</option> </select><br><br> Select year: <br> <input type="radio" name="Year" value="10" />10-year<br> <input type="radio" name="Year" value="20" />20-year<br> <input type="radio" name="Year" value="30" />30-year<br><br> Compute using loop:<input type="checkbox" name="chkLoop" value="ON" /><br><br> Future value is :<input type="text" name="FV" value="" /><br><br>

<input type="submit" value="ComputeFV" name="btnCompute" /> </form>

PHP Code <?php $myPV=$_POST["PV"]; $myRate=$_POST["Rate"]; $myYear=$_POST["Year"]; if (isset($_POST["chkLoop"])) { $FV = $myPV; for ($i = 1; $i <= $myYear; $i++) { $FV= $FV + $FV * $myRate; }} else $FV=$myPV*pow(1+$myRate,$myYear); echo "FutureValue is: $" . number_format($FV,2); ?>

Note: Without checking isset($_POST["chkLoop"]) the IF statement will cause error if the checkbox is not checked.

Depreciation Table

Straight Line Depreciation Table <form name="depForm" method="post" action="createDepTable.php"> Enter Property Value: <input type="text" name="pValue" value="" /><br> Enter Property Life: <input type="text" name="pLife" value="" /><br> <input type="submit" value="Show Depreciation Table" name="btnShowTable" /> </form>

Output

<?php $value=$_POST["pValue"]; $life=$_POST["pLife"]; echo "Straight Line Depreciation Table <br>"; echo "Property Value: <input type='text' name='pValue' value='$value' /><br>"; echo "Property Life: <input type='text' name='pLife' value='$life' /><br>"; $depreciation=$value/$life; $totalDepreciation=$depreciation; echo "<table border='1' width='400' cellspacing=1>"; echo "<thead> <tr> <th>Year</th> <th>Value at BeginYr</th>"; echo "<th>Dep During Yr</th> <th>Total to EndOfYr</th></tr> </thead>"; echo "<tbody>"; for ($count = 1; $count <= $life; $count++) { echo "<tr>"; echo "<td width='25%'>$count</td>"; echo "<td width='25%'>$" . number_format($value,2) . "</td>"; echo "<td width='25%'>$" . number_format($depreciation,2) . "</td>"; echo "<td width='25%'>$" . number_format($totalDepreciation,2) . "</td>"; $value -= $depreciation; $totalDepreciation+=$depreciation; } ?>

Alternating Row Color<?php $value=$_POST["pValue"]; $life=$_POST["pLife"]; echo "Straight Line Depreciation Table <br>"; echo "Property Value: <input type='text' name='pValue' value='$value' /><br>"; echo "Property Life: <input type='text' name='pLife' value='$life' /><br>"; $depreciation=$value/$life; $totalDepreciation=$depreciation; echo "<table border='1' width='400' cellspacing=1>"; echo "<thead> <tr> <th>Year</th> <th>Value at BeginYr</th>"; echo "<th>Dep During Yr</th> <th>Total to EndOfYr</th></tr> </thead>"; echo "<tbody>"; for ($count = 1; $count <= $life; $count++) { if ($count%2==0) $color="blue"; else $color="red"; // echo "<tr style='color:$color'>"; echo "<tr style='background-color:$color'>"; echo "<td width='25%'>$count</td>"; echo "<td width='25%'>$" . number_format($value,2) . "</td>"; echo "<td width='25%'>$" . number_format($depreciation,2) . "</td>"; echo "<td width='25%'>$" . number_format($totalDepreciation,2) . "</td>"; $value -= $depreciation; $totalDepreciation+=$depreciation; } ?>

Using PHP Expression <?php $value=$_POST["pValue"]; $life=$_POST["pLife"]; echo "Straight Line Depreciation Table <br>"; echo "Property Value: <input type='text' name='pValue' value='$value' /><br>"; echo "Property Life: <input type='text' name='pLife' value='$life' /><br>"; $depreciation=$value/$life; $totalDepreciation=$depreciation; ?> <table border='1' width='400' cellspacing=1> <thead> <tr> <th>Year</th> <th>Value at BeginYr</th> <th>Dep During Yr</th> <th>Total to EndOfYr</th></tr> </thead> <tbody> <?php for ($count = 1; $count <= $life; $count++) { ?> <tr> <td width='25%'><?php echo $count;?></td> <td width='25%'><?php echo '$'. number_format($value,2)?></td> <td width='25%'><?php echo '$'. number_format($depreciation,2)?></td> <td width='25%'><?php echo '$'. number_format($totalDepreciation,2)?></td> </tr> <?php $value -= $depreciation; $totalDepreciation+=$depreciation; } ?> </tbody></table>

Display output with inputs on the same page:Example: sum of two numbers

• Method 1: – The page should be a php file, not a html page.– The page calls itself to process the data.

• 2. the php file specified by the action attribute is called to compute the sum and use the include statement to display the sum with the input page

Method 1: The PHP page, SumPage.php, calls itself<?php if (!empty($_POST)) //if (count($_POST)>0) { $num1=$_POST["num1"]; $num2=$_POST["num2"]; $sum=$num1+$num2; ?> <form name="sumForm" method="post" action="SumPage.php"> Value 1: <input type="text" name=num1 value="<?php echo $num1;?>" /><br><br> Value 2: <input type="text" name="num2" value="<?php echo $num2;?>" /><br><br> Sum: <input type="text" name="sum" value="<?php echo $sum;?>" /><br><br> <input type="submit" value="Compute Sum" name="btnSubmit" /> </form> <?php } else { ?> <form name="sumForm" method="post" action="SumPage.php"> Value 1: <input type="text" name="num1" value="" /><br><br> Value 2: <input type="text" name="num2" value="" /><br><br> Sum: <input type="text" name="sum" value="" /><br><br> <input type="submit" value="Compute Sum" name="btnSubmit" /> </form> <?php } ?>

Note: This program uses empty($_POST) to test if the page is loaded for the first time.

Display output with inputs on the same page:Example: sum of two numbers

• Method 2: – The page should be a php file, not a html page.– The page calls a PHP page to process the data

which uses an include statement to include the calling page for output

PHP include and require Statements:include 'filename';require 'filename';

• In PHP, you can insert the content of one PHP file into another PHP file. The include and require statements are used to insert useful codes written in other files, in the flow of execution.

• Include and require are identical, except upon failure:– require will produce a fatal error (E_COMPILE_ERROR) and

stop the script– include will only produce a warning (E_WARNING) and the

script will continue

Method 2: The page calls a PHP page with an include statement to process the data

<?php if (isset($sum)) { ?> <form name="sumForm" method="post" action="computeSum.php"> Value 1: <input type="text" name=num1 value="<?php echo $num1;?>" /><br><br> Value 2: <input type="text" name="num2" value="<?php echo $num2;?>" /><br><br> Sum: <input type="text" name="sum" value="<?php echo $sum;?>" /><br><br> <input type="submit" value="Compute Sum" name="btnSubmit" /> </form> <?php } else { ?> <form name="sumForm" method="post" action="computeSum.php"> Value 1: <input type="text" name="num1" value="" /><br><br> Value 2: <input type="text" name="num2" value="" /><br><br> Sum: <input type="text" name="sum" value="" /><br><br> <input type="submit" value="Compute Sum" name="btnSubmit" /> </form> <?php } ?>

Note: This program use isset() function to test if the page is loaded for the first time.

computeSum.php

<body> <?php $num1=$_POST["num1"]; $num2=$_POST["num2"]; $sum=$num1+$num2; include ("sumForm.php"); exit(); /?></body>

Display future value with the inputs, fvForm2.php<?php if (!empty($_POST)){ $myPV=$_POST["PV"]; $myRate=$_POST["Rate"]; $myYear=$_POST["Year"]; $FV=$myPV*pow(1+$myRate,$myYear); echo "<form name='fvForm' method='post' action='fvForm2.php'>"; echo "Enter present value: <input type='text' name='PV' value='$myPV' /><br><br>"; echo "Select interest rate: <select name='Rate'>"; for ($v=.04; $v<=.08;$v+=.01){ $display=$v*100; if ($v==$myRate) echo "<option selected value=$v>$display%</option>"; else echo "<option value=$v>$display%</option>"; } echo "</select><br><br>"; echo "Select year: <br>"; for ($v=10; $v<=30;$v+=10){ $display=$v . '-year'; if ($v==$myYear) echo "<input type='radio' name='Year' checked value='$v' />$display<br>"; else echo "<input type='radio' name='Year' value='$v' />$display<br>"; } $CFV="$" . number_format($FV,2); echo "Future value is :<input type='text' name='FV' value='$CFV' /><br><br>"; echo "<input type='submit' value='ComputeFV' name='btnCompute' />"; } else { ?> <form name="fvForm" method="post" action="fvForm2.php"> Enter present value: <input type="text" name="PV" value="" /><br><br> Select interest rate: <select name="Rate"> <option value=.04>4%</option> <option value=.05>5%</option> <option value=.06>6%</option> <option value=.07>7%</option> <option value=.08>8%</option> </select><br><br> Select year: <br> <input type="radio" name="Year" value="10" />10-year<br> <input type="radio" name="Year" value="20" />20-year<br> <input type="radio" name="Year" value="30" />30-year<br><br> Future value is :<input type="text" name="FV" value="" /><br><br>

<input type="submit" value="ComputeFV" name="btnCompute" /> <?php } ?> </form>

2. Display future value with the inputs, fvForm.php<?php if (isset($FV)){ echo "<form name='fvForm' method='post' action='computeFV.php'>"; echo "Enter present value: <input type='text' name='PV' value='$myPV' /><br><br>"; echo "Select interest rate: <select name='Rate'>"; for ($v=.04; $v<=.08;$v+=.01){ $display=$v*100; if ($v==$myRate) echo "<option selected value=$v>$display%</option>"; else echo "<option value=$v>$display%</option>"; } echo "</select><br><br>"; echo "Select year: <br>"; for ($v=10; $v<=30;$v+=10){ $display=$v . '-year'; if ($v==$myYear) echo "<input type='radio' name='Year' checked value='$v' />$display<br>"; else echo "<input type='radio' name='Year' value='$v' />$display<br>"; } $CFV="$" . number_format($FV,2); echo "Future value is :<input type='text' name='FV' value='$CFV' /><br><br>"; echo "<input type='submit' value='ComputeFV' name='btnCompute' />"; } else { ?> <form name="fvForm" method="post" action="computeFV.php"> Enter present value: <input type="text" name="PV" value="" /><br><br> Select interest rate: <select name="Rate"> <option value=.04>4%</option> <option value=.05>5%</option> <option value=.06>6%</option> <option value=.07>7%</option> <option value=.08>8%</option> </select><br><br> Select year: <br> <input type="radio" name="Year" value="10" />10-year<br> <input type="radio" name="Year" value="20" />20-year<br> <input type="radio" name="Year" value="30" />30-year<br><br> Future value is :<input type="text" name="FV" value="" /><br><br>

<input type="submit" value="ComputeFV" name="btnCompute" /> <?php } ?> </form>

ComputeFV.php

<body> <?php $myPV=$_POST["PV"]; $myRate=$_POST["Rate"]; $myYear=$_POST["Year"]; $FV=$myPV*pow(1+$myRate,$myYear); // echo "FutureValue is: $" . number_format($FV,2); include 'fvForm.php'; ?> </body>

Recommended