Presentation is loading. Please wait.

Presentation is loading. Please wait.

Server Side Scripting Languages SE 362: Copyright © Steven W. Johnson October 1, 2012 Week 3: PHP Tools.

Similar presentations


Presentation on theme: "Server Side Scripting Languages SE 362: Copyright © Steven W. Johnson October 1, 2012 Week 3: PHP Tools."— Presentation transcript:

1 Server Side Scripting Languages SE 362: Copyright © Steven W. Johnson October 1, 2012 Week 3: PHP Tools

2 Update for Sublime Text More programming problems Functions in PHP SE 362: Copyright © Steven W. Johnson October 1, 2012

3 Week 3: Best practices of PHP Instances, functions, includes Introduction to tables Introduction to forms PHP Lab assignments Assignment 3

4 “Best practices” as defined by: Strunk & White (1918) “The Elements of Style” Kernighan & Plauger (1978) “The Elements of Programming Style” Kernighan & Ritchie (1978) “C Programming Language” 4

5 Best practices: Vigorous writing is concise. A sentence should contain no unnecessary words, a paragraph no unnecessary sentences, for the same reason that a drawing should have no unnecessary lines and a machine no unnecessary parts. This requires not that the writer make all his sentences short, or that the avoid all detail and treat his subjects only in outline, but that every word tell. 5 - E. B. White

6 6 /* This program determines which of two variables is largest and prints it first. If the variables are the same value, then it errors and re-starts*/ #include int main() { int numone = 0; int numtwo = 0; printf ("Please enter a number: "); scanf ("%d", &numone); printf ("Please enter another number: "); scanf ("%d", &numtwo); if (numone != numtwo) { if (numone > numtwo) printf ("\n%d is greater than %d\n\n", numone, numtwo); else printf ("\n%d is greater than %d\n\n", numtwo, numone); } else { printf ("\nPlease enter numbers that are different\n\n"); system ("pause"); main(); }

7 Software: Proper syntax (follows the rules) Good use of semantics (proper command choices) Follow a style (write what should be written) Proper documentation (comments) 7

8 Good code is: Maintainable over time Robust Scalable Predicable Supportable Extensible 8http://www.terragalleria.com/europe/france/pont-du-gard/picture.fran41426.html

9 Coding considerations: Initialize variables to 0 Handle true/false consistently Consistent indention (3 spaces) Closing brackets line up with command 9http://whfrtc.ky.gov/facilities/barracks.htm

10 Style: What ought to be written Variable names Function names Comments appearance 10

11 Iteration: Use iteration Use the correct form For: used when number is known While: unknown loops, test before use Do: unknown loops, test after use Best practice: use ‘for’ whenever possible 11

12 What does PHP do? Solve logical problems using deductive thinking (typical imperative language) PHP used to write: server side scripts Command line scripts Client side GUI apps 12

13 PHP’s mission: Accessing form data on subsequent pages Insert data into a database 13 Apple Cherry Peach Total:

14 PHP’s mission: Build dynamic web pages Creates “conditional HTML” 14 Pies Apple Cherry Peach Cakes Pies Chocolates Snacks

15 Different ways to make PHP tag: PHP code placed in ‘script’ tags in document flow Document flow: the order as it is written in code 15 Here is some text Here is more text the text is done Here is some text Here is more text Here is yet more text the text is done

16 Different ways to make PHP tag: ( xml style: recommended) Not universally supported: ( short style: SGML) 16

17 First steps: No ‘main’ (read in document flow) Functions allowed “Functions”: block of code ( function one(){ ) built-in extensions (strtoupper) Includes Includes commonly subroutines 17

18 First steps: 18 No ‘head’ versus ‘body’ to consider Text More text Untitled Document

19 Includes: 19 Commonly hold a subroutine; code used more than once ‘include’ or ‘require’; extension not important Use pathway from originating file

20 Whitespace: Ignored by parser; read by humans Uses HTML rules (one space between characters) 20 text more text text more text My text = “My text” My text = “My text” Render the same

21 Whitespace: ‘variable name’ is an identifier Naming rules: any length no spaces letters, numbers, underscores cannot begin with a digit case sensitive PHP and html generally NOT case sensitive 21

22 String literals: Single or double quotes Escape sequence on special characters Nested quotes 22 $text = “Steve”;//Steve $text = ‘Steve’;//Steve $text = “\“Izmir\””;//“Izmir” $text = ‘Hello “Izmir”’;//Hello “Izmir”

23 Data types: Loosely typed; changes to support current value 4 scalar (single value): int, float, string, boolean 2 compound (multi-value): object, array 23 $data = 45;//int if(is_int($data))//true $data = 45.0;//float if(is_float($data))//true $data = “45”;//string if(is_string($data))//true

24 Constants: Value cannot be changed No “$” on the name Should be in all caps to denote it’s a constant 24 define(“PI”, );

25 Functions: Like methods in JavaScript 25 $var = “steve”; echo strtoupper($var);//STEVE

26 Functions: Functions organized by category (type) arrays classes and objects date and time errors and logging mail math strings type 26

27 Functions: Can be used in validation* 27 $data = ???; if(is_set($data)) if(is_int($data))//is the data type int? if(is_empty($data)) if(is_numeric($data))//signs, numbers, decimal, exponents if(is_string($data))//is the data type string? *be VERY careful about using functions to validate. Regex are always safer

28 Arrays: Must be defined before used Used when one variable holds many values Array values are indexed Index value changed by using loops 28 $month[1] = “January” ;//$month[0]=January $month[2] = “February” ; … $month=array(“January”, “February”, …);//$month[0]=January

29 Associative arrays: Each ID key has a value ID => value (Russia gets Putin) 29 $leader = array(‘Russia’ => ‘Putin’, ‘Turkey’ => ‘Erdogan’, ‘United States’ => ‘Obama’); $leader[‘Russia’] = “Putin”; $leader[‘Turkey’] = “Erdogan”; $leader[‘United States’] = “Obama”;

30 Associative arrays: Use ‘foreach’ command to extract 30 $leader = array(‘Russia’ => ‘Putin’, ‘Turkey’ => ‘Erdogan’, ‘United States’ => ‘Obama’); foreach ($leader as $country => $name) { echo $name.“ is the leader of ”.$country.“ ”; } foreach ($leader as $country => $name) { if ($i==1) echo $name.“ is the leader of ”.$country.“ ”; $i++; }

31 Associative arrays: Sorting the array output 31 $leader = array(‘Russia’ => ‘Putin’, ‘Turkey’ => ‘Erdogan’, ‘United States’ => ‘Obama’); sort($leader); foreach ($leader as $country => $name) { echo $name.“ is the leader of ”.$country.“ ”; } //Erdogan is the leader of 0 //Obama is the leader of 1 //Putin is the leader of 2

32 Associative arrays: Sorting the array output 32 $leader = array(‘Russia’ => ‘Putin’, ‘Turkey’ => ‘Erdogan’, ‘United States’ => ‘Obama’); asort($leader); foreach ($leader as $country => $name) { echo $name.“ is the leader of ”.$country.“ ”; } //Erdogan is the leader of Turkey //Obama is the leader of United States //Putin is the leader of Russia

33 Introduction to tables Tables are 2-dimensional organizing tools; matrix Common in computing (Excel, Database, etc) 33

34 Introduction to tables: Table: organizes information by adding context NOT defining regions on a page 34 JanFebMar Balcova Karsiyaka Bornova

35 Introduction to tables: Page layout tools in HTML 4: tables layers (not part of this course) frames/iframes (deprecated) HTML5: organizes data with a common theme* 35*there’s exceptions to all rules, including this one

36 36 Tables: Tables mix table structure with content

37 37 Tables: Layers do not mix content; no dependencies

38 38 Tables: Defines sections of the table Scrolling applied to body of table only Turn on/off head and foot is a label while holds data (rendered description) summary attribute (‘hidden’ description) //size, border, spacing, pad //groups header content //groups footer content //title for row/column

39 39 Tables: Tables are still used for forms; dynamic content Same basic idea as a Word table/spreadsheet Elements used in dynamic tables: ( ) one table is made up of many rows ( ) one row is made up of many columns ( ) dynamic tables are invisible: (border=“0”, cellspacing=“0”) define attributes as a style

40 40 Tables: Basic structure of a table [] for (i=0; i

41 41 Tables: Table definitions: border: width of outside line (visibility) spacing: width of internal lines (visibility) padding: space inside cell that is empty table will collapse on itself if undefined

42 42 Tables for forms: tag Maybe 1 row for titles 2 : 1 for label, 1 for text field Rows as needed for text fields 1row for submit

43 43 Tables: First Name: Last Name: Age: NameAge Ali19 Bahar23 Use and properly: is for titles of rows/columns holds data Not so important for HTML 4, important now Table borders/spacing should not be visible* all

44 44 Making forms: Click on ‘Create form’ icon (forms tab) Place table inside form (red box) Place text fields inside table

45 45 Making tables: Insert table Set attributes Header “None”

46 Break

47 47 Forms: HTML element Job: gather/pass data to server Made up of input elements: text fields radio buttons check boxes menus submit button

48 48 Forms: HTML element name and id: DOM reference method: how is information sent to server action: what happens after submission?

49 Form methods: How is the form data sent to the next page? $_POST (invisible in the URL) $_GET (visible in the URL) 49 thanks.php?name=Steve&age=54 thanks.php

50 Form action: What to do after submission (leave the page) 50

51 51 Designing a form: Use a table; one cell holds one thing Right align your text; justify your fields Distance between text and field Distance between submit and form Set field widths to hold maximum value* Consistent width of fields looks nicer

52 Student ID: Surname: First Name: Department: School Year: GPA: Clubs: Touring: Jazz: Dance: Art: (merge cells) 52 Designing a form: Address: City: Zip Code: Phone: GSM: Password: Verify: password:

53 53 Forms: First Name: Last Name: Age: New with HTML5: placeholders gray text that is like ‘default value’ used in place of labels First Name

54 name your fields!! 54 Text field: Holds text/numbers without pre-selection Char Width: width of textbox Init Val: value shown on load/open Name all elements!!

55 .. 55 Password: A textfield with an attribute Text entered in field appears as circles/stars Does not secure the password; sent cleartext Passwords sent via SSL encryption (https)

56 56 Radio Group: Label is text on page; value sent by submit Radio Group: one selection from list

57 57 Radio button: Manual tool for creating radio groups For a group; name of button must be the same Make individual radio buttons (not a good idea)

58 58 Yes/No check box: General rule: Radio is group, Yes/No is button Check is “yes” Same name: group. Different names, buttons Can be set up as button or group (button) Options must be inclusive; add “other”

59 59 Text area: Generalized comments, if you like to read Infers a written response Data gathered is not queryable Last resort Char Width: width of box; Num Lines: height

60 Form Submit Button 60 Submit/Reset buttons: Submit button executes the action Action: send , use CGI, etc open a web page

61 61 Quiz: Legal variable names: Legal:illegal $one$function (keyword) $skidoo21day ($, number) $day_oneDay$ ($) $RRR$2skidoo (number) $interest% (%) $exit (keyword) $test$ (second $) $global (keyword)

62 62 Quiz: Data type for $x = “45”: String

63 63 Quiz: Preferred script tag for PHP? (all legal but “D”)

64 64 Quiz: Include: A line of code that calls a file which holds a block of code that is used on many pages

65 65 Quiz: This is me : This is me (1 space at most between characters)

66 66 Quiz: $text= “Roberto “Mr. Fenerbache” Guimarães”: It will not interpret

67 67 Quiz: Define(“KDV”, 1.18) Is correct as written

68 68 Quiz: $city = array(‘Izmir’ => ‘3 million’, ‘Istanbul’ => ’12 million’, ‘Ankara’ => ‘4.5 million’, ‘Bursa’ => ‘2.75 million’); Is correct as written

69 69 Quiz: Access all elements in the $city array (above): Use a ‘foreach’ loop

70 70 Quiz: Element defining table’s border, padding, spacing:

71 71 Quiz: Form’s action: Defines what happens after form submission

72 Server Side Scripting Languages SE 362: Copyright © Steven W. Johnson October 1, 2012 Week 3: PHP Tools

73 73 PHP functions: Similar to JavaScript, but different in appearance indexOf == strrpos($string, “search_parameter”) String Functions addcslashes addslashes bin2hex chop chr chunk_ ​ split convert_ ​ cyr_ ​ string convert_ ​ uudecode convert_ ​ uuencode count_ ​ chars crc32 crypt echo explode fprintf get_ ​ html_ ​ translation_ ​ table hebrev hebrevc hex2bin html_ ​ entity_ ​ decode htmlentities htmlspecialchars_ ​ decode htmlspecialchars implode join lcfirst levenshtein localeconv ltrim md5_ ​ file md5 metaphone money_ ​ format nl_ ​ langinfo nl2br number_ ​ format ord parse_ ​ str print printf quoted_ ​ printable_ ​ decode quoted_ ​ printable_ ​ encode quotemeta rtrim setlocale sha1_ ​ file sha1 similar_ ​ text soundex sprintf sscanf str_ ​ getcsv str_ ​ ireplace str_ ​ pad str_ ​ repeat str_ ​ replace str_ ​ rot13 str_ ​ shuffle str_ ​ split str_ ​ word_ ​ count strcasecmp ion.strrpos.php

74 74 PHP functions: Number functions indexOf == strrpos($string, “search_parameter”) /php_ref_math.asp

75 75 Open Uniform server/web server: Start UniServer

76 76 Lab: prime.php Open Week 3 folder, ‘prime.php’ Calculate all prime numbers between 2 and 100 Comments: describe process used to solve the problem name, assignment number define each variable used Change/fix title (Your_Name) Find count of prime numbers, average

77 77 Prime numbers: … Count: 4 Average: 4.25 Lab: prime.php

78 78 Lab: prime.php Need to do 2 things: count from 2 to 100 determine if the current number ($n) is prime

79 79 Lab: $n=2 to 100 $n Prime? echo;

80 80 Lab: prime.php Prime number: only 2 unique factors 6 has four factors (1, 2, 3 and 6); not prime 5 has two factors (1, 5); it is prime How to check 47 for “primeness”? Check all numbers between 2 and 46 to see if they are factor of $n

81 81 Lab: prime.php Prime number definition: divisible (can be divided with no remainder) (kalan) by 2 factors (faktör) only : n and 1 Tool/operation tests for a remainder? modulo 5/3 = 1 rem 2 5%3 = 2 6/4 = 1 rem 26%4 = 2 6/3 = 2 rem 06%3 = 0

82 82 Lab: prime.php Test for prime for a number (n = 8) Numbers to test: n-1 (7) to 2 If any remainder is zero, n is not prime 7i -18%71 6i - -8%62 5i - -8%53 4i - -8%40 3i - -8%3 228%2 n = 8; for(i=7; i>1; i--) { if(n%i==0) break; if(i==2) prime; }

83 83 Lab: prime.php Test for prime for a number (n = 8) Numbers to test: n-1 (7) to 2 If any remainder is zero, n is not prime 7i -1n%i1 6i - -n%i2 5i - -n%i3 4i - -n%i0 3i - -n%i 22 n = 8; for(i=7; i>1; i--) { if(n%i==0) break; if(i==2) prime; }

84 84 Lab: prime.php Test for prime for a number (n = 17) Numbers to test: n-1 (16) to 2 If any remainder is zero, n is not prime 7i - -17%73 6i - -17%65 5i - -17%52 4i - -n%i1 3i - -n%i n = 17; for(i=7; i>1; i--) { if(n%i==0) break; if(i==2) prime; }

85 85 Lab: prime.php This is iterative (systematic, design) thinking Systematic problem solving Literally all computer solutions are iterative

86 86 $n%$i==0 break; $n=3 to 100 $i=$n-1; $i>1; $i-- echo $i.“ ”; $count++; $sum += $n $n=2; $sum=2; $count++; $i==2

87 87 Lab: prime.php 1 st answer inefficient; tests n from n is tested for 99, 98, 97, 96, 95, etc First possible factor of 100 is 50 ($n/2) $n=3 to 100 $i=$n-1; $i>1; $i--

88 88 Lab: prime.php How to determine the test: pick several cases and test; look for pattern start easy to gain understanding test your understanding apply to most extreme example

89 89 Lab: ntestvaluetestcalculate 100n/250 n/2 99n/ n/ n/249 n/2 97n/ n/2+.5 6n/ n/2+.5 4n/ n/2+.5

90 90 Lab: prime.php Choices to fix $n: before the loop in the ‘for’ statement

91 91 Lab: prime.php if($n%2 == 1) $m=$n+1; if($n%2 != 0) $m=$n+1; Fix before the loop: test: is ‘$n’ odd (tek sayı) ? First test: exclusive Second test: inclusive (generally the better test) $n=3 to 100 $i=$m/2; $i>1; $i--

92 92 Lab: prime.php Think about floats; an approximation ($n%2) = (shown as ‘1’) if($n%2 == 1) $m=$n+1;//test fails if($n%2 != 0) $m=$n+1;//test passes

93 93 Lab: prime.php First test: value must equal 1 to be true 1 possible true answer Second test: value can be any number other than zero to be true 1 possible false answer if($n%2 == 1) $m=$n+1;//test fails if($n%2 != 0) $m=$n+1;//test passes $n%2 == $n%2 !=

94 94 Lab: prime.php Modulo is an Integer test. Floats are trouble if you treat them like ints if($n%2 == 1) $m=$n+1;//test fails if($n%2 != 0) $m=$n+1;//test passes

95 95 Lab: prime.php Fix $n in the ‘for’ statement use ceil or floor: ceil($n/2) to define $i $n = 100 ceil($n/2) = 50 $n = 99 ceil($n/2) = 49.5↑ $n=3 to 100 $i=ceil($n/2); $i>1; $i--

96 96 Lab: prime.php Ceiling or floor? Either is okay here Ceil is more inclusive; safer Floor leaves float values unchecked, problem is integer level $n = 89;//first factor: 44.5 $i = ceil($n/2);//45 $i = floor($n/2);//44

97 97 Lab: prime.php Secure answer with extra processing, use ceil More efficient, not totally inclusive, use floor $n = 89;//first factor: 44.5 $i = ceil($n/2);//45 $i = floor($n/2);//44

98 98 $n%$i==0 break; $n=3 to 100 $i=ceil($n/2); $i>1; $i-- echo $i.“ ”; $count++; $sum += $n $i==2 echo 2; $sum=2; $count++;

99 99 $n%$i==0 break; $n=3 to 100 $i=floor($n/2); $i>1; $i-- echo $i.“ ”; $count++; $sum += $n $i==2 3 is a problem echo 2; $sum=2; $count++;

100 100 $n%$i==0 break; $n=4 to 100 $i=floor($n/2); $i>1; $i-- echo $i.“ ”; $count++; $sum += $n echo 2, 3; $sum=5; $count=2; $i==2 3 is a problem

101 101 Lab: prime.php Upload your solution to the web server Blank page: syntax error

102 Break

103 103 Lab: string.php Open Week 3 folder, ‘string.php’

104 104 Lab: string.php String in PHP: Strings can be ‘ ‘, “ “, and heredoc (Unix shell) General rule: least powerful method single quote first double quote: add escape or interpolate heredoc: multi-line strings

105 105 Lab: string.php Interpolation: using variables to replace text $who = ‘Kilroy’; $where = ‘here’; echo “$who was $where”;//Kilroy was here echo “{$who} was {$where}”;//for complex expressions echo $who.“ was ”.$where;//‘normal’ way echo ‘$who was $where’;//echoes: $who was $where

106 106 Lab: string.php Escape sequences: much like JavaScript/C Use inside double quotes \” \’Double or single quote \n \rNewline, carriage return; data sent to browser as code. Use \ttab \\Add a backslash \$Add dollar sign (used for variables in PHP) \{ \}Add symbols used in programming \[ \]Add symbols used in programming \x50ASCII character in hexadecimal \52ASCII character in octal

107 107 Lab: string.php 4 kinds of print: echogeneral printing printprints single items printfadds substituted values, formatting print_rused in debugging

108 108 Lab: string.php String functions: $text = “The text is in the page”; $length = strlen($text); //23 chars for ($i=19; $i<$length; $i++) { printf(“The %dth char is: %s ”, $i, $text{$i}); } echo strtoupper($text);//THE TEXT IS IN THE PAGE echo strtolower($text);//the text is in the page echo ucfirst($text);//The text is in the page echo ucwords($text);//The Text Is In The Page

109 109 Lab: string.php Text comparisons: $text = “Alice”; $text2 = “Bob” ; //tests: =, ==, ===, =, > $text < $text2;//true $comp = strcmp($text, $text2);//<0 if 1 before 2 //>0 if 2 before 1 //0 if same

110 110 Lab: string.php Substrings: extract data from string $phone = “ ”; //local exchange: 895 $comp = substr($phone, 4, 3); //var, start, length $num = “(”.substr($phone, 0, 4).“) ”.substr($phone, 4, 3).“ ”.substr($phone, 7, 2).“ ”.substr($phone, 9, 2); echo $num; //(0232)

111 111 Lab: string.php Strings to and from array: explode & implode $text = “The text is in the page”; $explode = explode(‘ ’, $text); //makes 6-element array $split = split(‘ ’, $text); //DEPRECATED!!! for ($i=0; $i

112 112 Lab: string.php String search: strpos $phone = “ ”; $first = strpos($phone, “2”); //finds first “2” echo $first; //1 $last = strrpos($phone, “2”); //finds last “9” echo $last; //9

113 113 Lab: string.php Write the code to complete these tasks: 1. Find the length of the text 2. Capitalize all letters in the array 3. Capitalize the first letter of each word 4. Print all ‘odd’ words: (text, in, page) 5. Flip the 2 nd and 4 th words (The in is text) (array) 6. Flip the 2 nd and 4 th words (The in is text) (substr) 7. Count the number of words 8. Format telephone number: Count the number of ‘h’ in the string

114 114 Assignment: timearray.php Open ‘timearray.php’ Your job: 1. determine what time it is (in minutes) 2. display one person from array for each 5- minute block entered into 3. determine the average pay for the employees shown on page

115 115 Assignment: timearray.php display one person from array for each 5-minute block entered into minutes Number of people shown

116 116 Build associative array $employee NamePay Mehmet800 Cengiz5600 Deniz3500 Sevda2900 Ferda3000 Coskun4200 Ebed850 Ugur1325 Ozlem1910 Mine675 Canan1100 Emre1750 Assignment: timearray.php

117 Mehmet 800 Cengiz5,600 Deniz3,500 Sevda2,900 Ferda3,000 Average:3, An example of the output: Assignment: timearray.php

118 All numbers are to be displayed with a thousand separator and rounded to zero decimal places 2. Place the data in a table and right align all the salaries 3. Separate name and salary appropriately 4. Align the average with the numbers in the tables Assignment: timearray.php

119 119 NameSalary Assignment: timearray.php Table is located in file

120 120 An example of the final output (yours will be different) Assignment: timearray.php

121 Server Side Scripting Languages SE 362: Copyright © Steven W. Johnson October 1, 2012 Week 3: PHP Tools


Download ppt "Server Side Scripting Languages SE 362: Copyright © Steven W. Johnson October 1, 2012 Week 3: PHP Tools."

Similar presentations


Ads by Google