V 1.0 OE NIK 2013 1 PHP+SQL 2. PHP Introduction Control structures, operators Functions Practice ,

Preview:

Citation preview

V 1.0 OE NIK 2013 1

PHP+SQL2.

PHP IntroductionControl structures, operatorsFunctionsPractice

www.w3schools.com,http://www.tizag.com/phpT/index.php

V 1.0 OE NIK 2013 2

PHP+SQL2.

PHP IntroductionControl structures, operatorsFunctionsPractice

V 1.0

PHP• PHP = „PHP: Hypertext

Preprocessor” („recursive acronym” : GNU, LAME, WINE)

• Serverside programming language

• In a .php file, we can mix HTML code/text and PHP code – we will try to avoid heavily mixing those

• The output is typically HTML code (but it can be anything)

3OE NIK 2013

V 1.0

Server side?• Request Web server php module source file

parser generate output Web server Reply• The web server (Apache, IIS) handles the HTTP

communication, but parts of the communication (headers, content, error codes) can be changed from the PHP code

• HTTP methods: GET, POST, Connect, Trace, Put, Head• 2 main drawbacks of the HTTP:

– Stateless session management– Insecure HTTPS + coding security:

https://www.owasp.org/index.php/

OWASP_PHP_Security_Project4OE NIK 2013

V 1.0

Server side?• Request Web server php module source file

parser generate output Web server Reply• In the beginning: interpreter languages, CGI approach.

PHP is still interpreted, but not necessarily CGI• Easy-to-use and easy-to-learn programming language

with VERY loose rules and some strange features "Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live."

• JSP, ASP – "more professional", better for bigger projects (ORM, MVC, object persistence, cache, team work support, developing tools – PHP is getting better!)

5OE NIK 2013

V 1.0

Server side?• Request Web server php module source file

parser generate output Web server Reply• The parser reads the whole source file, but only the

marked parts are interpreted, the rest is forwarded into the output without any modification

• <html><body> UNPARSED CONTENT, YAY<?phpecho "Hello World ... ";echo 22+20;?><hr> THIS IS HTML TOO </body></html>

• Errrr, what about fatal parser errors?• Notice/warning/error, display_errors vs error_reporting

6OE NIK 2013

V 1.0

PHP vs Javascript

<html><body>

<?phpecho "Hello World";?>

</body></html>

<html><body>

<script type="text/javascript">document.write("Hello World!")</script>

</body></html>

7OE NIK 2013

V 1.0

Installation, LAMP/WAMP/XAMP

• http://users.nik.uni-obuda.hu/szabozs/install/• Linux/Windows, Apache>=2, MySQL>=5, PHP>=5• Use a simplified installer: WAMP,XAMP• Editor: Notepad++

(eclipse/dreamweaver/phpstorm/zend studio/php designer/phped)

• We will not use any OO/MVC frameworks this semester

• During the tests, one may not use: PEAR, Symfony, CodeIgniter, Joomla, Drupal, Wordpress, etc

• During the project: anything, but do X hours of work!8OE NIK 2013

V 1.0 OE NIK 2013 9

PHP+SQL2.

PHP IntroductionControl structures, operatorsFunctionsPractice

V 1.0

Statements• A program is a sequence of statements• Simple statements

– Declarations, expressions or function calls– Every statement must be closed with a semicolon „ ; ”

• Compound statements– A coherent block of several simple statements– No semicolon at the end– Other names: "block", "code block" it must be

surrounded with { and } characters

10OE NIK 2013

V 1.0

Comments, variables

<html><body><?php//This is a comment

/*This isa commentblock*/?></body></html>

<?php$txt="Hello World!"; // string$x=16; //intecho $txt;echo $x;// $a1 is good// Az $1a and $123 is not!echo (int) ((0.1 + 0.7) * 10); //7!!!!?>

PHP is a LOOSELY TYPED language! (And not a type-less language! The operators will do the typecasting)

11OE NIK 2013

V 1.0

Strings and variables$hello="Hello";$who = "World";echo "Hello!\n"; //Escape sequences!echo "$hello $who!\n";echo "$hellobello $who!\n";echo "{$hello}bello {$who}!\n";echo "The value of \$hello is \"{$hello}\" ";echo 'Hello $who!\n'; // string "as is"echo 'Hello $who!\'\n'; //Only this one is intepreted

• Do not get used to the automatic variable injection (arrays can get tricky) use quotation marks for string specification and curly braces for variable injetion!

12OE NIK 2013

V 1.0

Indirect variable reference• Since it's an interpreter language, it is possible

$name = ’foo’;$$name = ’bar’;echo $foo; // Echoes ’bar’

$name = ’123’; /* 123 should not be a variable's name */$$name = ’456’; echo ${’123’}; // Echoes ’456’

• AVOID! (except some very useful examples )• Because of the interpreter, we could use eval() too –

ALWAYS AVOID!

13OE NIK 2013

V 1.0

Operator Description Example Result

+(vs .)

Addition $x=2; $y=$x+2;

$x=2; $y=$x.2;

4

22

- Subtraction $x=2;5-$x 3

* Multiplication x=4;$x*5 20

/ Division (float) 15/55/2

32.5

% Remainder 5%210%810%2

120

++ Increase $x=5;$x++; $x=6

-- Decrease $x=5;$x--; $x=4

14OE NIK 2013

V 1.0

POST- and PRE-increment• Look out how the icrement is combined with other

statements (echo, indexing, loop conditions)$a = 1; // integer 1, assign it to $aecho $a++; // Echoes : 1, $a is now 2echo ++$a; // Echoes: 3, $a is now 3echo --$a; // Echoes: 2, $a is now 2echo $a--; // Echoes: 2, $a is now 1

• Suggestion: avoid mixing ++ and -- with other statements!

15OE NIK 2013

V 1.0

Post-increment and typecasting

$a = 1; $b=1;$a=$a+$b;$a++;echo $a; // 3

$a = 1; $b=1;$a=$a.$b;$a++;echo $a; // 12

$a="abc";$a++;echo $a; // abd

$a=(int)"abc";$a++;echo $a; // 1

$a=(int)"12abc";$a++;echo $a; // 13

16OE NIK 2013

V 1.0

Operator Description Example

== Equals 5==8 is false

=== Equals AND HAS THE SAME TYPE

5==”5” is true, 5===”5” is false (5=="5a" is true, 5==="5a" is false)

!=, <> Not equals 5!=8 is true

!== Not equals, with type comparison

5!=”5” is false5!==”5” is true

> Bigger than 5>8 is false

< Smaller than 5<8 is true

>= Bigger or equals 5>=8 is false

<= Smaller or equals 5<=8 is true17OE NIK 2013

V 1.0

Operator Example Meaning

= $x=$y; $x=$y;

+= $x+=$y; $x=$x+$y;

-= $x-=$y; $x=$x-$y;

*= $x*=$y; $x=$x*$y;

/= $x/=$y; $x=$x/$y;

.= $x.=$y; $x=$x.$y;

%= $x%=$y; $x=$x%$y;

18OE NIK 2013

V 1.0

Operator Description Example

&& , and Logical AND (&: bitwise AND)

$x=6; $y=3;(x < 10 && y > 1) is true

|| , or Logical OR (|: bitwise OR)

$x=6; $y=3;($x==5 || $y==5) is false

! Logical NOT $x=6; $y=3; !($x==$y) is true

xor Logical XOR $x=6; $y=3;($x==6) xor ($y==2) is true

&, |, ^, ~ Bitwise AND, OR, XOR, NOT

<< Left Shift (SHL)

>> Right Shift (SHR)

19OE NIK 2013

V 1.0 20

Other operators• Access operators

• Ternary operator

Operator Expression Meaning

-> x->y Member access (class)

( ) f(x) Function call

[ ] a[x] Extract parts of strings (later)Array indexing (later)

Operator

Expression Meaning

? : x ? y : z If X is true, then the expression evaluates to Y, otherwise it evaluates to Z … PHP sadness: left associative!!!!!!

OE NIK 2013

V 1.0

IF

<?php$num=rand(10, 100);if ($num%2 == 0) {

echo "Even";} else {

echo "Odd";}

?>

21OE NIK 2013

if (condition) // code to execute if the condition is true

else // code to execute if the condition is false

V 1.0

ELSEIF• if (condition1)

// code to execute, if condition1 is trueelseif (condition2) // otherwise, code to execute, if condition2 is trueelse // otherwise, the code to execute

22OE NIK 2013

V 1.0

Short-circuit evaluation• An important feature that is used if we connect more

than one logical expressions using the AND/OR (&& / ||) operators

• When using the AND operator (A && B): if the first expression is false, then the second is not evaluated (the result will always be FALSE)

• When using the OR operator (A || B): if the first expression is true, then the second is not evaluated (the result will always be TRUE)

• This is almost always turned on for nearly every programming language (exception: basic, pascal, java)!

OE NIK 2013 23

V 1.0

IF

• „if the condition is true” is not strictly a logical true/false expression or comparison! It can be anything that can be interpreted as boolean (due to the automatic typecasting)• In addition, we do not need comparison at all:

$i = 0;if ($i) echo "Testing for TRUE evaluation…";if (!$i) echo "Testing for FALSE evaluation…";

• Some strange oddities can happen...

24OE NIK 2013

if (condition) // code to execute if the condition is true

else // code to execute if the condition is false

V 1.0

  SHORT int(0) int(1) bool(false) bool(true) string(1) "0" string(1) "1"string(4) "some"

string(0) ""

int(0) FALSE Same   Equals   Equals   Equals Equals

int(1) TRUE   Same   Equals   Equals    

bool(false) FALSE Equals   Same   Equals     Equals

bool(true) TRUE   Equals   Same   Equals Equals  

string(1) "0" FALSE Equals   Equals   Same      

string(1) "1" TRUE   Equals   Equals   Same    

string(4) "some" TRUE Equals     Equals     Same  

string(0) "" FALSE Equals   Equals         Same

25OE NIK 2013

V 1.0

SWITCH

26OE NIK 2013

switch (expression) // expression: usually a variable{case label1: // Code to execute, if $n==label1 break;case label2: // Code to execute, if $n==label2 break;default: // Code to execute for any other values break;}

V 1.0

SWITCH$x=rand(0,10);switch ($x) {case 0:case 1: echo "Number 0 or 1"; break;case 2: echo "Number 2"; break;case 3: echo "Number 3";case 4: echo "Number 3 or 4";break;default: echo "Some other number";}

27OE NIK 2013

• Unlike in C# (much like in c/c++), we can use fall-through case sections: the statements are executed from the entry point till the first break statement

• Intervals and conditions cannot be used as case labels, only strict values!

V 1.0

WHILE

• The condition is always a stay-in condition• Look out for infinite loops! max_time_limit ,

ignore_user_abort

28OE NIK 2013

while (condition){ //code to be executed}

do{ // code to be executed}while (condition);

V 1.0

WHILE• <html>

<body>

<?php$i=1;while($i<=5) { echo "The number is " . $i . "<br />"; $i++; }?>

</body></html>

29OE NIK 2013

V 1.0

FOR

• initialization: Usually set some counter (e.g. $i=0, but it can be any other code)

• condition: Evaluated after every loop. If TRUE, then the loop continues

• increment: Usually a simple $i++ (but it can be any other code)

• WHILE and FOR loops are sometimes inter-changeable

30OE NIK 2013

for (initialization; stay-in condition; increment){ // code to be executed}

V 1.0

FOR<html><body>

<?phpfor ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; }?>

</body></html>

31OE NIK 2013

V 1.0

Break / continue$i = 0;while (true) {

if ($i == 10) {break;

}echo $i .”<br>”;$i++;

}for ($i = 0; $i < 10; $i++) {

for ($j = 0; $j < 3; $j++) {if (($j + $i) % 5 == 0) {

break 2; // Both loops}

}}

32OE NIK 2013

for ($i = 0; $i < 10; $i++) {if ($i > 3 && $i < 6) {

continue;}echo $i . ”<br>”;

}

$i=0;do {

$i+=0.1;echo "NUM: {$i}<br>";if ($i>200) break;

} while ($i!=100);

V 1.0

Empty statement

• Seldomly used– ProcessMessage() {...} //returns boolean– ProcessQueue() { … while (ProcessMessage()) ; … }– Dangerous! Must be used with caution!

• Common mistake:if (condition) ; // or: while (condition) ;{

// do something}

;

33OE NIK 2013

V 1.0 OE NIK 2013 34

PHP+SQL2.

PHP IntroductionControl structures, operatorsFunctionsPractice

V 1.0

Pre-defined functions• php.net/function_name• var_dump($mixed) , print_r($mixed)• isset($mixed) , unset($mixed), is_numeric($mixed), etc...• round($num), ceil($num), floor($num), rand($min,

$max)• strtolower($str) , strlen($str) , strpos($haystack,

$needle), strcmp($str1, $str2), substr($start, $end, $length) [negative numbers as parameter!] substr, strpos and $str[] indexes the BYTES (vs mb_*)

• date($format)• header($string), serialize($mixed), unserialize($str)• include($filename), include_once($filename),

require($filename), require_once($filename)35OE NIK 2013

V 1.0

Custom functions• function myFunc() {

echo ’myFunc!’;}

• function myAdd($first, $second) {return $first+$second;

}• function mySub($first, $second=42) {

return $first-$second;}

• myFunc();echo myAdd(5, 18);echo mySub(42, 0); echo mySub(84);

• $f = ’myFunc’;$f(); // call myFunc(); NEVER EVER

36OE NIK 2013

V 1.0

Variable scopeEvery variable is local!

$a = "Hello World";function hello(){

$a = "Hello Reader";$b = "How are you";

}hello();echo $a; // „Hello World”echo $b; // Warning: undefined variable $b

37OE NIK 2013

V 1.0

Variable scope$a = "Hello"; $b = "World";function hello(){

global $a, $b;echo "{$a} {$b}";

}hello(); // „Hello World”

38OE NIK 2013

$a = "Hello"; function hello(){

global $b;$b = "World";

}echo "{$a} {$b}“; // „Hello World”

V 1.0 OE NIK 2013 39

PHP+SQL2.

PHP IntroductionControl structures, operatorsFunctionsPractice

V 1.0

Exercise #1

Create a PHP script that generates two random integers (A [100 .. 1000], B [1 .. 20])!Echo them out, so that the user can see the numbers!

Then, create and call the functions for the followings:

• Calculate and return B! = 1*2*3*…*B• Calculate and return AB = A*A*A*…*A• Calculate and return Fib(B)

Fib(0)=0, Fib(1)=1, Fib(N)=Fib(N-1)+Fib(N-2) • Return (as a list in a string) every positive divisor of

the number A40OE NIK 2013

V 1.0

Exercise #2

Generate 100 integers from the [150..200] interval.

Display the integers in a 10x10 table.

Emphasize the primes from the generated numbers.

Identify the maximum element, along with the number of occurrences of that element.

41OE NIK 2013

V 1.0 OE NIK 2013 42

PHP+SQL2.

PHP IntroductionControl structures, operatorsFunctionsPractice

V 1.0 OE NIK 2013 43

44OE NIK 2013