Advanced Prog Lec 2

26
CvSU – CCC (Lec Manual) (COSC111 – Advanced Programming) 1 CHAPTER 1: PHP Introduction Objectives: At the end of the chapter, students must be able to: defy what is PHP; know the Pros, Cons and strengths of PHP; and be familiar with the origin of PHP. PHP: Hypertext Preprocessor PHP: Hypertext Preprocessor is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. PHP is a widely-used, open source scripting language PHP files have a default file extension of ".php" The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases. The Origin of PHP This software, originally known as Personal Home Pages, was developed in 1997 and is currently being used in over 10 million domains. Before PHP, developers used CGI (Common Gateway Interface) scripts for interacting with users, querying databases, etc. However, since CGI applications are separate, stand-alone programs, scalability is missing because multiple CGI applications running concurrently can quickly consume all available memory. To avoid this problem, PHP was developed using a three layer architecture. The first layer is the client also known as the browser. The second layer is the server (including both the web server and PHP interpreter). The third layer is the database system. Using this approach, it avoids the forking of external programs found in CGI applications which can quickly consume all available memory. With PHP you write HTML script with embedded code defined with special start and end tags. The embedded code is executed on the server and then sent to your browser. What is displayed in the browser is the result from the code's execution. This is very different from other scripting languages like Perl and C where code is written to output HTML commands. While similar to JavaScript, the main difference with PHP is the code is executed on the servers, whereas with JavaScript the code is executed on the client-side. With Dept. of ICT & Computer Studies 1 st Sem. A.Y. 2013- 2014 T. Baylon

description

Advanced Programming Lectures

Transcript of Advanced Prog Lec 2

Page 1: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

1

CHAPTER 1: PHP Introduction

Objectives:At the end of the chapter, students must be able to:

defy what is PHP; know the Pros, Cons and strengths of PHP; and be familiar with the origin of PHP.

PHP: Hypertext Preprocessor

PHP: Hypertext Preprocessor is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

PHP is a widely-used, open source scripting language PHP files have a default file extension of ".php" The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers

to create dynamic content that interacts with databases.

The Origin of PHP

This software, originally known as Personal Home Pages, was developed in 1997 and is currently being used in over 10 million domains. Before PHP, developers used CGI (Common Gateway Interface) scripts for interacting with users, querying databases, etc. However, since CGI applications are separate, stand-alone programs, scalability is missing because multiple CGI applications running concurrently can quickly consume all available memory. To avoid this problem, PHP was developed using a three layer architecture. The first layer is the client also known as the browser. The second layer is the server (including both the web server and PHP interpreter). The third layer is the database system. Using this approach, it avoids the forking of external programs found in CGI applications which can quickly consume all available memory.

With PHP you write HTML script with embedded code defined with special start and end tags. The embedded code is executed on the server and then sent to your browser. What is displayed in the browser is the result from the code's execution. This is very different from other scripting languages like Perl and C where code is written to output HTML commands. While similar to JavaScript, the main difference with PHP is the code is executed on the servers, whereas with JavaScript the code is executed on the client-side. With JavaScript it is possible to determine the underlying code, whereas with PHP the underlying code is hidden from the user.

How PHP works?

Every time a visitor goes to your site to read your content, a request is made that is sent to a host server. The PHP programming language receives that request, makes a call to the MySQL database, obtains the requested information from the database, and then presents the requested information to your visitor via his web browser.

Content   refers to the data stored in the MySQL database which includes blog posts, pages, comments, links, and options. The theme (or design) you choose to use for your site isn't part of the database content. Themes files are considered the presentation layer and are essential to user friendly website display. Theme files are part of the file system and aren't stored in the database. So creating and keeping a backup of any theme files that you're currently using are good ideas.

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 2: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

2

Hardware and Software requirements and installation

install a web browser (Google Chrome, Mozilla Firefox, Internet explorer) install PHP install a database, such as MySQL

PHP Pros and Cons

Pros It's a quick and easy server side scripting language. It works well with databases, file systems, images It is widely available with the apache web server, meaning cheap hosting and many people

already have access to it. It's popular and common PHP runs on different platforms (Windows, Linux, Unix, Mac OS X, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP has support for a wide range of databases PHP is free. PHP is easy to learn and runs efficiently on the server side

Cons Constantly changing. There hasn't been a release of PHP that didn't have a number of problems.

The only way to get rid of them is to upgrade, but then you get new problems, because they don't have separate stable and development branches. 

Strength of PHP

Supports database connectivity. PHP can access over 20 different databases including MySql, Oracle, and MS Access. 

Supports sessions. PHP can generate unique session IDs. The ID follows the user during a single session on a web site.

Eliminates client configuration problems. With PHP there is no need to worry if the client has the appropriate software installed, since the application is executed on the server. 

Reduces development time. Even a newcomer can begin developing PHP applications in hours. Yet PHP contains many advanced features for professional programmers. 

Maintains source code security. The user does not see your source code as they do with JavaScript.

CHAPTER 2: Basic PHP Development

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 3: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

3

Objectives:At the end of the chapter, students must be able to:

be familiar with the basic PHP syntax; recognize PHP variables; and understand PHP operations.

Basic PHP Syntax

A PHP script starts with <?php and ends with ?>: The default file extension for PHP files is ".php". A PHP file normally contains HTML tags, and some PHP scripting code. Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to

distinguish one set of instructions from another. With PHP, there are two basic statements to output text in the browser: echo and print.

PHP Variables

PHP variables can be used to hold values (x=5) or expressions (z=x+y). Variable can have short names (like x and y) or more descriptive names (age, carname,

totalvolume).

Example:$X=2;$Y=10;

Rules for PHP variables:

A variable starts with the $ sign, followed by the name of the variable A variable name must begin with a letter or the underscore character A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) A variable name should not contain spaces Variable names are case sensitive ($y and $Y are two different variables)

Variables are "containers" for storing information: A variable is created the moment you first assign a value to it. When you assign a text value to a variable, put a quotation around the value, it is now called a

String variable.

Example:$stringVar=”variable_content”;

Activity no.1

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 4: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

4

Topic: Creating and using variables

Direction:

1. Echo the following statement to the browser:

“Twinkle, Twinkle little star.”

2. Create two variables, one for the word “Twinkle” and one for the word “star”. Echo the statement to the browser, this time substituting the variables for the relevant words. Change the value of each variable to whatever you like, and echo the statement a third time. Remember to include code to show your statements on different lines.

Sample Output:

Twinkle, Twinkle little star. Twinkle, Twinkle little star.

Thunder, Thunder little elephant.

Sample script:

<html><head><title>Twinkle Twinkle</title></head>   <body>   <?php echo"Twinkle, Twinkle little star. <br/>"; //Note that html tags can be included along with the text to be echoed.    $twinkle="Twinkle"; $star="star";    //This will print out exactly the same as the first echo statement.echo"$twinkle, $twinkle little $star.<br/>";    $twinkle="Thunder"; $star="elephant";    /*This one will be different. Exactly what prints will depend on what valued you assigned to the variables.*/echo"$twinkle, $twinkle little $star.";    ?>   </body></html>    

PHP Operators

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 5: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

5

The assignment operator = is used to assign values to variables in PHP. The arithmetic operator + is used to add values together in PHP.

PHP Arithmetic Operators

Operator Name Description Example Result

x + y Addition Sum of x and y 2 + 2 4

x - y Subtraction Difference of x and y 5 - 2 3

x * y Multiplication Product of x and y 5 * 2 10

x / y Division Quotient of x and y 15 / 5 3

x % y Modulus Remainder of x divided by y

5 % 210 % 810 % 2

120

- x Negation Opposite of x - 2  

a . b Concatenation Concatenate two strings "Hi" . "Ha" HiHa

PHP Assignment Operators

The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the expression on the right. That is, the value of "$x = 5" is 5.

Assignment Same as... Description

x = y x = y The left operand gets set to the value of the expression on the right

x += y x = x + y Addition

x -= y x = x - y Subtraction

x *= y x = x * y Multiplication

x /= y x = x / y Division

x %= y x = x % y Modulus

a .= b a = a . b Concatenate two strings

PHP Incrementing/Decrementing Operators

Operator

Name Description

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 6: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

6

++ x Pre-increment Increments x by one, then returns x

x ++ Post-increment Returns x, then increments x by one

-- x Pre-decrement Decrements x by one, then returns x

x -- Post-decrement Returns x, then decrements x by one

PHP Comparison Operators

The comparison operators allows you to compare two values.

Operator Name Description Example

x == y Equal True if x is equal to y 5==8 returns false

x === y Identical True if x is equal to y, and they are of same type

5==="5" returns false

x != y Not equal True if x is not equal to y 5!=8 returns true

x <> y Not equal True if x is not equal to y 5<>8 returns true

x !== y Not identical True if x is not equal to y, or they are not of same type

5!=="5" returns true

x > y Greater than True if x is greater than y 5>8 returns false

x < y Less than True if x is less than y 5<8 returns true

x >= y Greater than or equal to True if x is greater than or equal to y

5>=8 returns false

x <= y Less than or equal to True if x is less than or equal to y

5<=8 returns true

PHP Logical Operators

Operator

Name Description Example

x and y And True if both x and y are true x=6

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 7: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

7

y=3 (x < 10 and y > 1) returns true

x or y Or True if either or both x and y are true

x=6y=3 (x==6 or y==5) returns true

x xor y Xor True if either x or y is true, but not both

x=6y=3 (x==6 xor y==3) returns false

x && y And True if both x and y are true x=6y=3(x < 10 && y > 1) returns true

x || y Or True if either or both x and y are true

x=6y=3(x==5 || y==5) returns false

! x Not True if x is not true x=6y=3!(x==y) returns true

PHP Array Operators

Operator

Name Description

x + y Union Union of x and y

x == y Equality True if x and y have the same key/value pairs

x === y Identity True if x and y have the same key/value pairs in the same order and are of the same type

x != y Inequality True if x is not equal to y

x <> y Inequality True if x is not equal to y

x !== y Non-identity

True if x is not identical to y

Activity no.2

Topic: Arithmetic Operations and Variables

Direction:

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 8: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

8

PHP includes all the standard arithmetic operators. For this PHP exercise, you will use them along with variables to print equations to the browser.

1. In your script, create the following variables:$x=10;$y=7;

2. Write code to print out the following:

10 + 7 = 1710 – 7 = 310 * 7 = 7010 / 7 = 1.428571428571410 % 7 = 3

Use numbers only in the above variable assignments, not in the echo statements. You will need a third variable as well.

NOTE: Use numbers only in the above variable assignments, not in the echo statements. You will need a third variable as well.

Sample script:  <html> <head> <title>Arithmetic Operators</title> </head>    <body>    <?php    $x=10; $y=7;    $result=$x+$y; echo "$x + $y = $result<br/>";    $result=$x-$y; echo "$x - $y = $result<br/>";    $result=$x*$y; echo "$x * $y = $result<br/>";    $result=$x/$y; echo "$x / $y = $result<br/>";    $result=$x%$y; echo "$x % $y = $result<br/>";    ?>    </body> </html>

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 9: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

9

CHAPTER 3: Control Structures

Objectives:At the end of the chapter, students must be able to:

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 10: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

10

recognize the basic conditional statements in PHP; be familiar with the basic structure of the PHP conditional statements; and use PHP conditional statements in formulating a program.

PHP Conditional Statements

PHP conditional statements are used for performing different actions for different operations. In PHP we have the following conditional statements:

if statement - executes some code only if a specified condition is true

If (condition) {

Code to be executed if the condition is true;}

if...else statement - executes some code if a condition is true and another code if the condition is false.

If (condition){Code to be executed if the condition is true;}

else{Code to be executed if the condition is false;}

if...else if....else statement - selects one of several blocks of code to be executed.

if (condition){Code to be executed if the condition is true;}

else if (condition){Code to be executed if the condition is true;}

else{Code to be executed if the condition is false;}

switch statement - selects one of many blocks of code to be executed. The switch statement is used to perform different actions based on different conditions.

Switch (n){Case label 1:

Code to be executed if n=label1;Break;

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 11: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

11

Case label 2: Code to be executed if n=label2;

Break;Default:

Code to be executed if n is different from both label1 and label2;}

For the switch statement, we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

CHAPTER: PHP ArraysObjectives:

At the end of the chapter, students must be able to: distinguish the function of arrays in PHP; categorize the types PHP arrays; and utilize PHP arrays in a program.

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 12: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

12

PHP Arrays

An array stores multiple values in one single variable: An array is a special variable, which can hold more than one value at a time. An array can hold many values under a single name, and you can access the values by referring

to an index number.

In PHP, there are three types of arrays:

Indexed arrays - Arrays with numeric index Associative arrays - Arrays with named keys Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays

There are two ways to create indexed arrays: The index can be assigned automatically (index always starts at 0):

$cars=array("Volvo","BMW","Toyota");

or the index can be assigned manually:

$cars[0]="Volvo";$cars[1]="BMW";

$cars[2]="Toyota";

The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values:

Example:

<?php$cars=array("Volvo","BMW","Toyota");echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";?>

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them. There are two ways to create an associative array: 

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

or

$age['Peter']="35";$age['Ben']="37";$age['Joe']="43";

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 13: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

13

The named keys can then be used in a script:

Example

<?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");echo "Peter is " . $age['Peter'] . " years old.";?>

PHP Sorting Functions

sort() - sort arrays in ascending order rsort() - sort arrays in descending order asort() - sort associative arrays in ascending order, according to the value ksort() - sort associative arrays in ascending order, according to the key arsort() - sort associative arrays in descending order, according to the value krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order - sort()

The following example sorts the elements of the $cars array in ascending alphabetical order:

Example

<?php$cars=array("Volvo","BMW","Toyota");sort($cars);?>

Sort Array in Descending Order - rsort()

The following example sorts the elements of the $cars array in descending alphabetical order:

Example

<?php$cars=array("Volvo","BMW","Toyota");rsort($cars);?>

Sort Array in Ascending Order, According to Value - asort()

The following example sorts an associative array in ascending order, according to the value:

Example

<?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");asort($age);?>

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 14: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

14

Sort Array in Ascending Order, According to Key - ksort()

The following example sorts an associative array in ascending order, according to the key:

Example

<?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");ksort($age);?>

Sort Array in Descending Order, According to Value - arsort()

The following example sorts an associative array in descending order, according to the value:

Example

<?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");arsort($age);?>

Sort Array in Descending Order, According to Key - krsort()

The following example sorts an associative array in descending order, according to the key:

Example

<?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");krsort($age);?>

CHAPTER: PHP Looping

PHP Looping Statements

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 15: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

15

Loops in PHP are used to execute the same block of code a specified number of times.

FOR Loop

- it loops through a block of code a specified number of times.

Syntax:

for (initialization; condition; increment){ code to be executed;}

Sample Program:

<?php$a = 0;$b = 0;

for( $i=0; $i<5; $i++ ){ $a += 10; $b += 5;}echo ("At the end of the loop a=$a and b=$b" );?>

Output:

At the end of the loop a=50 and b=25

WHILE Loop

- It loops through a block of code if and as long as a specified condition is true.it loops through a block of code a specified number of times.

Syntax:

while (condition){ code to be executed;}

Sample Program:

<?php$i = 0;

$num = 50;

while( $i < 10){ $num--; $i++;}

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 16: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

16

echo (" i = $i and num = $num" );?>

Output:

i = 10 and num = 40

DO – WHILE Loop

- The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.

Syntax:do{ code to be executed;} while (condition);Sample Program:

<?php$i = 11;

do{

$i++;}

while( $i < 10 );

echo ("Loop stopped at i = $i" );

?>

Output:

Loop stopped at i = 12

Activity no.4

Topic: Simple Loops

Direction:

1. Write a script that will print the following to the browser

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 17: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

17

abc abc abc abc abc abc abc abc abc

xyz xyz xyz xyz xyz xyz xyz xyz xyz

1 2 3 4 5 6 7 8 9

1. Item A2. Item B3. Item C4. Item D5. Item E6. Item F

2. Create the 'abc' row with a while loop, the 'xyz' row with a do-while loop, and the last two sections with for loops. Remember to include HTML and source code line breaks in your output. No arrays allowed in this solution.

Sample script:

<html><head><title>Simple Loops</title></head> <body><h2>Simple Loops</h2> <?php echo"<p>\n"; $counter= 1;while($counter< 10){ echo'abc '; $counter++;} echo"</p>\n";echo"<p>\n"; $counter= 1;do{ echo'xyz '; $counter++;}while($counter< 10) ; echo"</p>\n"; for($x=1;$x<10;$x++){ echo"$x ";}

//The space inside the "" is necessary to separate the numbers.

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 18: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

18

//Generate ordered list.

echo"\n<ol>";for($x='A';$x<'G';$x++){ echo"<li>Item $x</li>\n"; }echo"\n</ol>";

//Note that letters may be used in the for loop in place of numbers. ?> </body></html>

Activity no.5

Topic: Simple For Loops

Direction:

Loops are very useful in creating lists and tables.

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 19: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

19

1. Using a for loop, write a script that will send to the browser a list of squares for the numbers 1-12.Use the format,” 1 * 1 = 1” and be sure to include code to print each formula on a different line.

Sample output:

Squares for the Numbers 1-12

1 * 1 = 1 2 * 2 = 4 3 * 3 = 9 4 * 4 = 16 5 * 5 = 25 6 * 6 = 36 7 * 7 = 49 8 * 8 = 64 9 * 9 = 81 10 * 10 = 100 11 * 11 = 121 12 * 12 = 144

Sample script:

<html><head><meta http-equiv="content-type"content="text/html;charset=iso-8859-1"/><title>Squares for the Numbers 1-12</title></head> <body><h2>Squares for the Numbers 1-12</h2> <?php for($x=1;$x<=12;$x++){ $result=$x*$x; echo"$x * $x = $result <br />\n";} ?> </body></html>

Activity no.6

Topic: Nested For Loops

Direction:

1. Use two for loops, one nested inside another. Create the following multiplication table:

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon

Page 20: Advanced Prog Lec 2

(COSC111 – Advanced Programming)

20

1 2 3 4 5 6 7

2 4 6 8 10 12 14

3 6 9 12 15 18 21

4 812

16 20 24 28

5 1015

20 25 30 35

6 1218

24 30 36 42

7 1421

28 35 42 49

Sample script:

<html><head><title>Nested Loop Multiplication Table</title></head> <body><h2>Nested Loop Multiplication Table</h2> <?php//Generate an HTML tableecho"<table border=\"1\">"; //Generate table data showing the numbers 1-7 multiplied by each other,//starting with the rows.for($row=1;$row<=7;$row++){ echo"<tr>\n"; //Generate each entry in the row to create the columns. for($col=1;$col<=7;$col++){ //First, do the math. $x=$col*$row; //Then send the value to the table with the table data tags. echo"<td>$x</td>\n"; } echo"</tr>";}echo"</table>";?> </body> </html>

Dept. of ICT & Computer Studies 1st Sem. A.Y. 2013-2014 T. Baylon