590 likes | 605 Views
Learn the basics of PHP programming and combining it with HTML to create functional web applications. Develop PHP files that correctly apply syntax, use variables and expressions, and generate HTML output.
E N D
A Web-Based Introduction to Programming Chapter 05 Creating a Working Program Basics of PHP Chapter 05
Intended Learning Outcomes • Distinguish between markup and programming languages. • Develop .php files that combine PHP instructions with HTML. • Write PHP instructions that correctly apply basic PHP syntax. • Create and use variables in PHP instructions. • Use the $_POST array to receive form input. • Create expressions that perform basic arithmetic in PHP. • Create expressions that use common PHP functions. • Use print statements to generate HTML output from PHP. • Use the number_format() function to format numeric output. Chapter 05
Why HTML and PHP? • HTML is a markup language, used to render the appearance of data. • PHP is a programming language, used to process data: • Use variables to store values. • Perform calculations and comparisons. • Use selection and loop structures. • Work with files and databases. • We combine HTML markup and PHP processing to create Web applications. Chapter 05
About PHP • PHP is a "scripting" programming language designed for dynamic Web site development • Used extensively world-wide. • Fully functional programming language. • Easy to learn. • Can be combined with HTML to provide a Web-based graphical user interface. • PHP files (.php) are located on Web servers (same as HTML files, and processed when requested. Chapter 05
PHP Example: wage1 • Recall the wages1 application (no user input): Chapter 05
Algorithms for wage1 wage1.html algorithm: Display Submit button to execute Wage1.php END wage1.php algorithm: hourlyWage = 15.75 hourlyWage = 19 hourlyWage = hourlyWage * hoursWorked Display hourlyWage, hourlyWage, hourlyWage END Chapter 05
Code for wage1.html PHP program that will process the form <body> <h1>Wage Report</h1> <p> This page will provide your current wage report. <form action = "wage1.php" method = "post" > <input type = "submit" value = "Get Your Wage Report Now" /> </form> </p> </body> </html> Chapter 05
Code for wage1.php <html> <head> <title>Wage Report</title> <link rel ="stylesheet" type="text/css" href="sample.css" /> </head> <body> <h1>WAGE REPORT</h1> <?php $hourlyWage = 15.75; $hoursWorked = 19; $wage = $hourlyWage * $hoursWorked; print("<p>Your hourly wage is $$hourlyWage and you worked $hoursWorked hours.</p>"); print("<p>You wages are $$wage.</p>"); ?> </body> </html> PHP code is enclosed inside <?php and ?> Chapter 05
Code for wage1.php • Note that wage1.php contains HTML code, just like an HTML document. • But wage1.php also contains PHP code • The PHP code must be located within PHP sections: <?php … php code goes here … ?> • A PHP file can contain HTML code and any number of PHP sections containing PHP code. Chapter 05
Processing wage1.php • When the processor opens a .php file it constructs a new HTML document, line by line: • Any HTML code is added to the new HTML page. • The processor executes any PHP sections found in in the .php file. If the PHP instructions generate HTML code, the HTML code is also added to the new HTML document. • When the entire file has been processed, the new HTML document contains the HTML that was in the original .php file, as well as any HTML generated by the PHP code. • The newly created HTML document is then sent back to the Web browser. Chapter 05
Processing wage1.php Step-by-Step • Any HTML before the PHP section will be added to the new HTML page: <html> <head> <title>Wage Report</title> <link rel ="stylesheet" type="text/css" href="sample.css" > </head> <body> <h1>WAGE REPORT</h1> Chapter 05
Processing wage1.php Step-by-Step • Next the 5 instructions in the PHP section are executed: <?php $hourlyWage = 15.75; $hoursWorked = 19; $wage = $hourlyWage * $hoursWorked; print("<p>Your hourly wage is $ $hourlyWage and you worked $hoursWorked hours.</p>"); print("<p>Your wages are $ $wage.</p>"); ?> • Let's look at the first three instructions… Chapter 05
Processing wage1.php step by step $hourlyWage = 15.75; $hoursWorked = 19; $wage = $hourlyWage * $hoursWorked; • $hourlyWage, $hoursWorked and $wage are variables • In PHP, all variable names begin with $ • Variables are used to store values • These three instructions are executed inorder • Every PHP statement ends with a semi-colon Chapter 05
Processing wage1.php step by step $hourlyWage = 15.75; $hoursWorked = 19; $wage = $hourlyWage * $hoursWorked; • The 1st statement assigns 15.75 to $hourlyWage • The 2nd statement assigns 19 to $hoursWorked • The 3rd statement multiplies the value stored in $hourlyWage by the value stored in $hoursWorked and stores the result in $wage • So $wage now contains 299.25 Chapter 05
Processing wage1.php Step-by-Step print("<p>Your hourly wage is $$hourlyWage and you worked $hoursWorked hours.</p>"); • The PHP printfunction produces HTML output. This output will be added to the new HTML page. • This statement generates a "<p>Your hourly wage is $", followed by the value stored in $hourlyWage, followed by "and you worked ", followed by the value stored in $hoursWorked, followed by "hours. </p>". • The HTML output from this statement is: <p>Your hourly wage is $15.75 and you worked 19 hours.</p> Chapter 05
Processing wage1.php Step-by-Step print("<p>Your wages are $$wage.</p>"); • Here the PHP print function produces another line of output to be added to the new HTML page. • This statement generates: "<p>"Your wages are $" , followed by the value stored in $wage, followed by ".</p>". • The HTML output is therefore: <p>Your wages are $299.25.</p> Chapter 05
Processing wage1.php Step-by-Step • After the PHP section, there is more HTML: </body> </html> • This HTML is added to the new HTML document. • The entire .php file has now been processed – what does the new HTML document contain? Chapter 05
Processing wage1.php Step-by-Step • The new HTML document contains: <html> <head> <title>Wage Report</title> <link rel ="stylesheet" type="text/css" href="sample.css" > </head> <body> <h1>WAGE REPORT</h1> <p>Your hourly wage is $15.75 and you worked 19 hours.</p> <p>Your wages are $299.25.</p> </body> </html> Chapter 05
Features of Client/Server Design • The user clicks a Submit button to submit an action to the server (in this case to process a .php file): • The server processes the .php file and generates a new HTML document, which is sent back to the browser by the server. • HTML files are static(always the same content). • PHP files are dynamic(content is generated at the time the file is processed, and may be different each time depending on the program instructions). Chapter 05
Client/Server Characteristics • A single copy of the .phpfile is stored on the server. • This single copy can be accessed by many users using their Web browsers. • The program is executed separately for each user. • If the .php file is changed, all users now access the new version. • The PHP code remains secure, hidden from the user. Chapter 05
PHP Example: wage2 • Recall the wage2 application (receives user input): Chapter 05
Algorithms wage2.html algorithm: Prompt user for hourly wage Get hourlyWage Prompt user for hours worked Get hoursWorked Submit hourlyWage, hoursWorked to wage2.php END wage2.php algorithm: Receive hourlyWage, hoursWorked from wage2.html weeklyWage = hourlyWage * hoursWorked Display hourlyWage, hoursWorked, weeklyWage END Chapter 05
Code for wage2.html Names to identify the input values passed to wage2.php PHP program that Will process the form <body> <h1>Wage Report</h1> <p> <form action = "wage2.php" method = "post" > <p>Please enter your hourly wage: <input type = "text" size = "20" name = "hourlyWage" > </p> <p>And the hours you have worked: <input type = "text" size = "20" name = "hoursWorked" > </p> <input type = "submit" value = "Get Your Wage Report Now" > <input type = "reset" value = "Clear and start again" > </form> </p> </body> </html> Chapter 05
Code for wage2.php <html> <head> <title>Wage Report</title> <link rel ="stylesheet" type="text/css" href="sample.css" > </head> <body> <h1>WAGE REPORT</h1> <?php $hourlyWage = $_POST['hourlyWage']; $hoursWorked = $_POST['hoursWorked']; $wage = $hourlyWage * $hoursWorked; print("<p>Your hourly wage is $ $hourlyWage and you worked $hoursWorked hours.</p>"); print("<p>You wages are $ $wage.</p>"); ?> </body> </html> Chapter 05
Receiving values from the form • The form field inputs are named hourlyWageand hoursWorked. • The values from these fields are received in the PHP $_POST array • Each value is identified by name. • The value named hourlyWage is retrieved from the $_POST array and assigned to a PHP variable: $hourlyWage = $_POST['hourlyWage']; • Similarly: $hoursWorked = $_POST['hoursWorked']; Chapter 05
Processing wage2.php • The next statement calculates the wage: $wage = $hourlyWage * $hoursWorked; • The two print statements work the same as in wage1.php to generate HTML output: print("<p>Your hourly wage is $$hourlyWage and you worked $hoursWorked hours.</p>"); print("<p>You wages are $$wage.</p>"); Chapter 05
Wage 2 in Action.. • Assume the user enters 10.75 for hourly wage and 25 for hours worked: • These values are submitted to wage2.php, which receives them as $_POST [‘hourlyWage’] and $_POST [‘hoursWorked’] • The values are assigned to $hourlyWage and $hoursWorked. • 268.75 is calculated, then stored in $wage • The two print statements generate: <p>Your hourly wage is $10.75 and you worked 25 hours.</p> <p>Your wages are $268.75.</p> Chapter 05
Wage 2 in Action.. • The new HTML document contains: <html> <head> <title>Wage Report</title> <link rel ="stylesheet" type="text/css" href="sample.css" /> </head> <body> <h1>WAGE REPORT</h1> <p>Your hourly wage is $10.75 and you worked 25 hours.</p> <p>Your wages are $268.75.</p> </body> </html> Chapter 05
Smoking Survey Example • Review smoking.html and smoking.php: Chapter 05
Learning PHP Syntax • All PHP statements must end with a semi-colon ; • Variable names must follow PHP naming rules: • 1st character is always the $ sign. • 2nd character must be a letter a-z, A-Z, or an underscore. • Remaining characters can be any combination of letters, numeric digits or other characters. • Spaces are not allowed anywhere in variable names! VALID: $userName $employee1 $averageSalary INVALID: $My Salary $1stProgram mySalary Chapter 05
Learning PHP Syntax • PHP is case sensitive • $salary is a different variable than $Salary or $SALARY (be careful!) • Variable names should be meaningful • $averageSalary is a good name • $avS is not • $c1 is a terrible name! Chapter 05
Learning PHP Syntax • Variable naming conventions: • The firstletter of a variable name is lower-case. • Distinct English words within the variable name should each start with an uppercase letter (camelback notation), or else be separated by underscores: $distanceToMoon or $distance_to_moon But not $distancetomoon (hard to read) Chapter 05
Learning PHP Syntax • In PHP, variables are created automatically the first time they appear in the code. • You can create as many variables as your program needs. • Once a variable has been created you can refer to it as often as needed: • To assign a value to the variable • To use the value in a calculation • To test the value stored in the variable • To output the value (for example in a print statement) Chapter 05
Learning PHP Syntax • Be careful not to making typing errors: $hourlyWage = 15.75; $hoursWorked = 19; $weeklyWage = $hourlyWage * $housrWorked; • The processor creates a new variable named $housrWorked and assigns the value 0 • The expression 15.75 * 0 evaluates to 0, so 0 is stored in $weeklyWage! Chapter 05
Learning PHP Syntax • Be careful - PHP allows you to mix data types: $firstName = "Mary"; $age = 30; $result = $firstName * $age; • Do you really want to multiple "Mary" * 30? (The result will be 0, since "Mary" will be given the numeric value 0). Chapter 05
Learning PHP Syntax • As we have seen, PHP variables can receive values from HTML forms: • The values are received into the PHP $_POST array. • The values can be extracted from the $_POST array by referencing the name of the appropriate form field, and assigned to PHP variables. • These variables can be used in the PHP code just like any other variable. Chapter 05
Learning PHP Syntax • Values can be assigned to variables using the syntax: <variable> = expression; • Examples: • $retailPrice = 20.56; • $tax = $retailPrice * 0.07; • $total = $retailPrice + $tax; • $firstName = "Mary"; • $lastName = "Jones"; • $fullName = "$firstName $lastName"; Chapter 05
Learning PHP Syntax • A value that has been stored in a variable can be replaced by a new value: $retailPrice = 20.56; (… other code here …) $retailPrice = 75.50; • First 20.56 is assigned to $retailPrice • Later in the code 75.50 is assigned to $retailPrice • The new value replaces the previous value Chapter 05
Learning PHP Syntax • Variables can appear on both sides of an assignment operation: $total = 225.25; $nextPurchase= 14.75; $total = $total + $nextPurchase; • These statements are executed in order: • 225.25 is assigned to $total • 14.75 is assigned to $nextPurchase • The value stored in $total is added to the value stored in $nextPurchase and the result is stored in $total • $total now contains 240.00 Chapter 05
Incrementing and Decrementing • To add 1 to the value already stored in a variable: $numberOf students = $numberOf students + 1; • To subtract 1 from the value already stored in a variable: $numberOf students = $numberOf students – 1; • These are such common operations, most languages provide special increment and decrement operators: $numberOf students ++; // to increment $numberOf students --; // to decrement Chapter 05
Arithmetic Expressions • The arithmetic operators are: + (addition) - (subtraction) * (multiplication) / (division) % (modulus) • Arithmetic expressions are evaluated following the rules of precedence: • First multiplication and division operation are evaluated, in order of occurrence from left to right. • Next addition and subtraction operations are evaluated, from left to right. • Parentheses can be used to change the precedence. Chapter 05
Arithmetic Expressions • Examples: • 1 + 2 * 3 – 4 evaluates to 1 + 6 – 4 which evaluates to 7 – 4 which evaluates to 3 • (1 + 2) * (3 – 4) evaluates to 3 * (3 - 4 ) which evaluates to 3 * -1 which evaluates to -3 • (1 + 2) * (3 / (4 – 1)) evaluates to (1 + 2) * (3 / 3) which evaluates to 3 * (3 / 3) which evaluates to 3 * 1, which evaluates to 3 Chapter 05
Arithmetic Expressions • Arithmetic expressions can combine variables and literal values as needed: • $weeklyWage = $hourlyWage * 40; • $areaOfCircle = 3.1412 * $radius * $radius; • $totalWithDeduction = ($itemCost – 2.50) * $qtyOrdered; Chapter 05
Modulus Operator • % is a division operator used with integer division to calculate remainders: • The result of 7 % 2 is 1 since 2 divides 7 three times with a remainder of 1 • The result of 10 % 5 is 0 since 5 divides 10 two times with a remainder of 0 • The result of 67 % 60 is 7 since 60 divides 67 onetime with a remainder of 7 Chapter 05
Using Arithmetic Functions • PHP provides many arithmetic functions for use in your code as needed: pow() • $result = pow(2,3) raises 2 to the power of 3, to yield 8, which is then stored in $result. • $answer = pow($number, 5) raises the value stored in $number to the power of 5. The result is then stored in $answer. • $value = pow ($number, $exponent) raises the value stored in $number to the power of the value stored in $exponent. The result is then stored in $value. Chapter 05
Using Arithmetic Functions pi() • pi() returns the value of pi, a accurately as PHP allows. • $areaOfCircle = pi() * pow($radius, 2); multiplies the value of pi by the square of the value stored in the $radius, and stores the result in $areaOfCircle sqrt() • sqrt(9) will yield the square root of 9, which is 3 • $result = sqrt($number); will obtain the square root of the value stored in $number and store the answer in $result Chapter 05
Using Arithmetic Functions round() rounds upordownto the closest integer • round(3.25) returns 3 • round(3.65) returns 4 ceil() always rounds upto the closest integer • ceil(3.25) returns 4 • ceil(3.65) returns 4 floor() always rounds downto the closest integer • floor(3.25) returns 3 • floor(3.65) returns 3 Chapter 05
Using Arithmetic Functions rand() can be used to generate a random number in any range • rand (1, 10) returns a random value between 1 and 10 • rand (25, 75) returns a random value between 25 and 75 • rand() generates a random value between 0 and 1 Example: assign a random number of gold pieces to a game player between 0 and 1000: $startingGold = rand(0, 1000); Chapter 05
White Space in PHP • The PHP processor ignores white space so this version of wage1.php will execute correctly.. ….. but it is VERY hard to read! <html><head> <title>Wage Report</title><link rel = "stylesheet" type="text/css" ref="sample.css" ></head> <body><h1>WAGE REPORT</h1><?php $hourlyWage = 15.75; $hoursWorked = 19; $wage = $hourlyWage * $hoursWorked; print("<p>Your hourly wage is $ $hourlyWage and you worked $hoursWorked hours.</p>"); print("<p>Your wages are $ $wage.</p>");?></body></html> Chapter 05
Generating HTML Output from PHP • HMTL output in a .php file can be typed directly, outside the <?php ?> tags: • This is HTML output that will always be the same. • Some HTML output in a .php file is dependent on the values of PHP variables or functions: • This output mustbe generated by PHP print statements insidethe PHP sections. (PHP also provides an echo statement, similar to print) Chapter 05