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

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

Embed Size (px)

Citation preview

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

Server Side Scripting Languages

SE 362:

Copyright © Steven W. JohnsonOctober 1, 2012

Week 3: PHP Tools

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

Update for Sublime TextMore programming problemsFunctions in PHP

SE 362:

Copyright © Steven W. JohnsonOctober 1, 2012

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

Week 3:

Best practices of PHP

Instances, functions, includes

Introduction to tables

Introduction to forms

PHP

Lab assignments

Assignment3

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

“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

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

Best practices:

Vigorous writing is concise. A sentence should contain no unnecessarywords, 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

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

6

/* This program determines which of two variables is largest and prints itfirst. If the variables are the same value, then it errors and re-starts*/

#include <stdio.h>

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(); }}

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

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

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

Good code is:

Maintainable over time

Robust

Scalable

Predicable

Supportable

Extensible

8http://www.terragalleria.com/europe/france/pont-du-gard/picture.fran41426.html

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

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

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

Style:

What ought to be written

Variable names

Function names

Comments

appearance

10

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

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 possible11

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

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

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

PHP’s mission:

Accessing form data on subsequent pages

Insert data into a database

13

<?php ?>

Apple 2 18.95

Cherry 1 16.95

Peach 2 19.95

Total: 94.75

2

1

2

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

PHP’s mission:

Build dynamic web pages

Creates “conditional HTML”

14

PiesApple

Cherry

Peach

18.95

16.95

19.95

<?php ?>

CakesPiesChocolatesSnacks

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

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

<p>Here is some text</p><p>Here is more text</p><?php echo “Here is yet more text”; ?><p>the text is done</p>

Here is some text

Here is more text

Here is yet more text

the text is done

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

Different ways to make PHP tag:

<?php ?> (xml style: recommended)

Not universally supported:

<? ?> (short style: SGML)

<script type=“text/php”> </script>

16

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

First steps:

No ‘main’ (read in document flow)

Functions allowed

“Functions”:

block of code ( function one(){ )

built-in extensions (strtoupper)

Includes

Includes commonly subroutines17

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

First steps:

18

<?php function first() { echo “Text<br />”; } function second() { echo “More text”; } first(); second();//output is:// Text// More text?>

No ‘head’ versus ‘body’ to consider

Text<br />More text<html><head> <title>Untitled Document</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> </body> </html>

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

Includes:

19

<?php include connect.php; include authorize.php; include header.html; include footer.html;?>

Commonly hold a subroutine; code used morethan once

‘include’ or ‘require’; extension not important

Use pathway from originating file

<?php //connect.php# FileName=“Connection_php_mysql.htm”# Type=“MYSQL”# HTTP=“true”$host =“127.0.0.1”;$database =“dbname”;$user =“teacher”;$pass =“xyz123”;$connect = mysql_pconnect($host, $user, $pass) or trigger_error(mysql_error(),E_USER_ERROR); ?>

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

Whitespace:

Ignored by parser; read by humans

Uses HTML rules (one space between characters)

20

<p>text</p><p>more text</p>

<p>text</p>

<p>more text</p>

< p>My text</p> = “My text”

<p>My&nbsp;&nbsp;&nbsp;text</p> = “My text”

Render the same

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

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 sensitive21

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

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”

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

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; //intif(is_int($data)) //true$data = 45.0; //floatif(is_float($data)) //true$data = “45”; //stringif(is_string($data)) //true

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

Constants:

Value cannot be changed

No “$” on the name

Should be in all caps to denote it’s a constant

24

define(“PI”, 3.1415936);

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

Functions:

Like methods in JavaScript

25

$var = “steve”;echo strtoupper($var); //STEVE

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

Functions:

Functions organized by category (type)arraysclasses and objectsdate and timeerrors and loggingmailmathstringstype

26http://w3schools.com/php/php_ref_string.asp

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

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, exponentsif(is_string($data)) //is the data type string?

*be VERY careful about using functions to validate. Regex are always safer

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

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

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

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”;

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

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.“<br />”;}

foreach ($leader as $country => $name) { if ($i==1) echo $name.“ is the leader of ”.$country.“<br />”; $i++;}

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

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.“<br />”;}

//Erdogan is the leader of 0//Obama is the leader of 1//Putin is the leader of 2

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

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.“<br />”;}

//Erdogan is the leader of Turkey//Obama is the leader of United States//Putin is the leader of Russia

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

Introduction to tables

Tables are 2-dimensional organizing tools; matrix

Common in computing (Excel, Database, etc)

33

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

Introduction to tables:

Table: organizes information by adding context

NOT defining regions on a page

34

Jan Feb Mar

Balcova 32.795 33.157 31.824

Karsiyaka 54.874 52.896 55.152

Bornova 35.851 36.742 37.245

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

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

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

36

Tables:

Tables mix table structure with content

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

37

Tables:

Layers do not mix content; no dependencies

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

38

Tables:

Defines sections of the table

Scrolling applied to body of table only

Turn on/off head and foot

<th> is a label while <td> holds data

<caption> (rendered description)

summary attribute (‘hidden’ description)<table> //size, border, spacing, pad<thead> //groups header content<tfoot> //groups footer content<tbody><th> //title for row/column

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

39

Tables:

Tables are still used for forms; dynamic content

Same basic idea as a Word table/spreadsheet

Elements used in dynamic tables: (<table>)

one table is made up of many rows (<tr>)

one row is made up of many columns (<td>)

dynamic tables are invisible: (border=“0”,

cellspacing=“0”)

define <td> attributes as a style

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

40

Tables:

<table> <tr> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> </tr></table>

Basic structure of a table

<table>

<tr>[]

<td>[]<table> for (i=0; i<row.length; i++) { <tr> for (j=0; j<column.length; j++) { <td> </td> } </tr> }</table>

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

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

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

42

Tables for forms:

<table> tag

Maybe 1 row for titles

2 <td>: 1 for label, 1 for text field

Rows as needed for text fields

1row for submit

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

43

Tables:

First Name:

Last Name:

Age:

Name Age

Ali 19

Bahar 23

Use <th> and <td> properly:

<th> is for titles of rows/columns

<td> holds data

Not so important for HTML 4, important now

Table borders/spacing should not be visible*

all <td>

<th><td><td>

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

44

Making forms:

Click on ‘Create form’ icon (forms tab)

Place table inside form (red box)

Place text fields inside table

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

45

Making tables:

Insert table

Set attributes

Header “None”

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

Break

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

47

Forms:

HTML element

Job: gather/pass data to server

Made up of input elements:

text fields

radio buttons

check boxes

menus

submit button

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

48

Forms:

<form name=“login” id=“userlogin” method=“post” action=“welcome.php”></form>

HTML element

name and id: DOM reference

method: how is information sent to server

action: what happens after submission?

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

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

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

Form action:

What to do after submission (leave the page)

50

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

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

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

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:

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

53

Forms:

First Name:

Last Name:

Age:

New with HTML5: placeholders

gray text that is like ‘default value’

used in place of labels

<input type="text" name="username" placeholder="First Name">

First Name

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

name yourfields!! 54

Text field:

Holds text/numbers without pre-selection

Char Width: width of textbox

Init Val: value shown on load/open

Name all elements!!

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

. .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)

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

56

Radio Group:

Label is text on page; value sent by submit

Radio Group: one selection from list

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

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)

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

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”

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

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

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

mailto:[email protected]

Form

Submit Button

60

Submit/Reset buttons:

Submit button executes the action

Action:

send e-mail, use CGI, etc

open a web page

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

61

Quiz:

Legal variable names:

Legal: illegal$one $function (keyword)$skidoo2 1day ($, number)$day_one Day$ ($)$RRR $2skidoo (number)

$interest% (%)$exit (keyword)$test$ (second $)$global (keyword)

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

62

Quiz:

Data type for $x = “45”:

String

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

63

Quiz:

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

<?php ?>

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

64

Quiz:

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

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

65

Quiz:

<p>This is me</p>:

This is me (1 space at most between characters)

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

66

Quiz:

$text= “Roberto “Mr. Fenerbache” Guimarães”:

It will not interpret

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

67

Quiz:

Define(“KDV”, 1.18)

Is correct as written

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

68

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

Is correct as written

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

69

Quiz:

Access all elements in the $city array (above):

Use a ‘foreach’ loop

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

70

Quiz:

Element defining table’s border, padding, spacing:

<table>

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

71

Quiz:

Form’s action:

Defines what happens after form submission

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

Server Side Scripting Languages

SE 362:

Copyright © Steven W. JohnsonOctober 1, 2012

Week 3: PHP Tools

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

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

http://php.net/manual/en/function.strrpos.php

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

74

PHP functions:

Number functions

indexOf == strrpos($string, “search_parameter”)

http://www.w3schools.com/php/php_ref_math.asp

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

75

Open Uniform server/web server:

Start UniServer

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

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

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

77

Prime numbers:2357…

Count: 4Average: 4.25

Lab: prime.php

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

78

Lab: prime.php

Need to do 2 things:

count from 2 to 100

determine if the current number ($n) is prime

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

79

Lab:$n=2 to 100

$n Prime? echo;

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

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 seeif they are factor of $n

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

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 = 26/4 = 1 rem 26%4 = 26/3 = 2 rem 06%3 = 0

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

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

7 i -1 8%7 1

6 i - - 8%6 2

5 i - - 8%5 3

4 i - - 8%4 0

3 i - - 8%3

2 2 8%2

n = 8;for(i=7; i>1; i--) { if(n%i==0) break; if(i==2) prime;}

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

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

7 i -1 n%i 1

6 i - - n%i 2

5 i - - n%i 3

4 i - - n%i 0

3 i - - n%i

2 2 n%i

n = 8;for(i=7; i>1; i--) { if(n%i==0) break; if(i==2) prime;}

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

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

7 i - - 17%7 3

6 i - - 17%6 5

5 i - - 17%5 2

4 i - - n%i 1

3 i - - n%i 2

2 2 n%i 1

n = 17;for(i=7; i>1; i--) { if(n%i==0) break; if(i==2) prime;}

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

85

Lab: prime.php

This is iterative (systematic, design) thinking

Systematic problem solving

Literally all computer solutions are iterative

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

86

$n%$i==0 break;

$n=3 to 100

$i=$n-1; $i>1; $i--

echo $i.“</br />”;$count++;$sum += $n

$n=2;$sum=2;$count++;

$i==2

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

87

Lab: prime.php

1st answer inefficient; tests n from n-1

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

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

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

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

89

Lab: n test value test calculate

100 n/2 50 50 n/2

99 n/2 49.5 50 n/2+.5

98 n/2 49 49 n/2

97 n/2 48.5 49 n/2+.5

6 n/2 3 3 n/2

5 n/2 2.5 3 n/2+.5

4 n/2 2 2 n/2

3 n/2 1.5 2 n/2+.5

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

90

Lab: prime.php

Choices to fix $n:

before the loop

in the ‘for’ statement

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

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

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

92

Lab: prime.php

Think about floats; an approximation

($n%2) = 0.99999999999999 (shown as ‘1’)

if($n%2 == 1) $m=$n+1; //test failsif($n%2 != 0) $m=$n+1; //test passes

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

93

Lab: prime.php

First test: value must equal 1 to be true

1 possible true answer

Second test: value can be any number otherthan zero to be true

1 possible false answer

if($n%2 == 1) $m=$n+1; //test failsif($n%2 != 0) $m=$n+1; //test passes

$n%2 == 00000000 00000000 00000000 00000001

$n%2 != 00000000 00000000 00000000 00000000

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

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 failsif($n%2 != 0) $m=$n+1; //test passes

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

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

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

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

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

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

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

98

$n%$i==0 break;

$n=3 to 100

$i=ceil($n/2); $i>1; $i--

echo $i.“</br />”;$count++;$sum += $n

$i==2

echo 2;$sum=2;$count++;

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

99

$n%$i==0 break;

$n=3 to 100

$i=floor($n/2); $i>1; $i--

echo $i.“</br />”;$count++;$sum += $n

$i==2

3 is a problem

echo 2;$sum=2;$count++;

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

100

$n%$i==0 break;

$n=4 to 100

$i=floor($n/2); $i>1; $i--

echo $i.“</br />”;$count++;$sum += $n

echo 2, 3;$sum=5;$count=2;

$i==2

3 is a problem

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

101

Lab: prime.php

Upload your solution to the web server

http://localhost/prime.php

Blank page: syntax error

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

Break

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

103

Lab: string.php

Open Week 3 folder, ‘string.php’

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

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

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

105

Lab: string.php

Interpolation: using variables to replace text

$who = ‘Kilroy’;$where = ‘here’;

echo “$who was $where”; //Kilroy was hereecho “{$who} was {$where}”; //for complex expressionsecho $who.“ was ”.$where; //‘normal’ wayecho ‘$who was $where’; //echoes: $who was $where

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

106

Lab: string.php

Escape sequences: much like JavaScript/C

Use inside double quotes

\” \’ Double or single quote

\n \r Newline, carriage return; data sent to browser as code. Use <br />

\t tab

\\ Add a backslash

\$ Add dollar sign (used for variables in PHP)

\{ \} Add symbols used in programming

\[ \] Add symbols used in programming

\x50 ASCII character in hexadecimal

\52 ASCII character in octal

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

107

Lab: string.php

4 kinds of print:

echo general printing

print prints single items

printf adds substituted values, formatting

print_r used in debugging

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

108

Lab: string.php

String functions:

$text = “The text is in the page”;$length = strlen($text); //23 chars 0 - 22

for ($i=19; $i<$length; $i++) { printf(“The %dth char is: %s<br />”, $i, $text{$i});}

echo strtoupper($text); //THE TEXT IS IN THE PAGEecho strtolower($text); //the text is in the pageecho ucfirst($text); //The text is in the pageecho ucwords($text); //The Text Is In The Page

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

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

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

110

Lab: string.php

Substrings: extract data from string

$phone = “02328957425”; //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) 895 74 25

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

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<count($explode); $i++) { //array length echo $explode[$i].“<br />”;};

$names = array(“Alican”, “Bahar”, “Canan”, “Deniz”);$implode = implode(“ ”, $names); //$join = join(“, ”, $names);echo $implode; //Alican Bahar Canan Denizecho $join; //Alican, Bahar, Canan, Deniz

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

112

Lab: string.php

String search: strpos

$phone = “02328957425”;

$first = strpos($phone, “2”); //finds first “2”echo $first; //1

$last = strrpos($phone, “2”); //finds last “9”echo $last; //9

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

113

Lab: string.php

Write the code to complete these tasks:1.Find the length of the text2.Capitalize all letters in the array3.Capitalize the first letter of each word4.Print all ‘odd’ words: (text, in, page)

5.Flip the 2nd and 4th words (The in is text) (array) 6.Flip the 2nd and 4th words (The in is text) (substr)

7.Count the number of words 8.Format telephone number: 028745612349.Count the number of ‘h’ in the string

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

114

Assignment: timearray.phpOpen ‘timearray.php’

Your job:1.determine what time it is (in minutes)

2.display one person from array for each 5-minute block entered into3.determine the average pay for the employees shown on page

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

115

Assignment: timearray.phpdisplay one person from array for each 5-minute block entered into

minutes

Number of people shown

0 - 4 1

5 - 9 2

10 - 14 3

15 - 19 4

20 - 24 5

25 - 29 6

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

116

Build associative array $employee

Name Pay

Mehmet 800

Cengiz 5600

Deniz 3500

Sevda 2900

Ferda 3000

Coskun 4200

Ebed 850

Ugur 1325

Ozlem 1910

Mine 675

Canan 1100

Emre 1750

Assignment: timearray.php

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

Mehmet 800Cengiz 5,600Deniz 3,500Sevda 2,900Ferda 3,000

Average: 3,333

117

An example of the output:

Assignment: timearray.php

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

118

1. 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

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

119

<?php for (x; y; z) { ?>

<tr> <td><?php ?></td><td><?php ?></td></tr><?php } ?>

Name Salary

Assignment: timearray.php

Table is located in file

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

120

An example of the final output (yours will be different)

Assignment: timearray.php

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

Server Side Scripting Languages

SE 362:

Copyright © Steven W. JohnsonOctober 1, 2012

Week 3: PHP Tools