Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "V 1.0 OE NIK 2013 1 PHP+SQL 2. PHP Introduction Control structures, operators Functions Practice"— Presentation transcript:

1 V 1.0 OE NIK 2013 1 PHP+SQL 2. PHP Introduction Control structures, operators Functions Practice www.w3schools.com, http://www.tizag.com/phpT/index.php

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

3 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) 3 OE NIK 2013

4 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_Project 4 OE NIK 2013

5 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!) 5 OE NIK 2013

6 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 UNPARSED CONTENT, YAY THIS IS HTML TOO Errrr, what about fatal parser errors? Notice/warning/error, display_errors vs error_reporting 6 OE NIK 2013

7 V 1.0 PHP vs Javascript document.write("Hello World!") 7 OE NIK 2013

8 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! 8 OE NIK 2013

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

10 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 10 OE NIK 2013

11 V 1.0 Comments, variables <?php $txt="Hello World!"; // string $x=16; //int echo $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) 11 OE NIK 2013

12 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! 12 OE NIK 2013

13 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! 13 OE NIK 2013

14 V 1.0 OperatorDescriptionExampleResult + (vs.) Addition$x=2; $y=$x+2; $x=2; $y=$x.2; 4 22 -Subtraction$x=2; 5-$x3 *Multiplicationx=4; $x*520 /Division (float)15/5 5/2 3 2.5 %Remainder5%2 10%8 10%2 120120 ++Increase$x=5; $x++;$x=6 --Decrease$x=5; $x--;$x=4 14 OE NIK 2013

15 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 $a echo $a++; // Echoes : 1, $a is now 2 echo ++$a; // Echoes: 3, $a is now 3 echo --$a; // Echoes: 2, $a is now 2 echo $a--; // Echoes: 2, $a is now 1 Suggestion: avoid mixing ++ and -- with other statements! 15 OE NIK 2013

16 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 16 OE NIK 2013

17 V 1.0 OperatorDescriptionExample ==Equals5==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 equals5!=8 is true !==Not equals, with type comparison 5!=”5” is false 5!==”5” is true >Bigger than5>8 is false <Smaller than5<8 is true >=Bigger or equals5>=8 is false <=Smaller or equals5<=8 is true 17 OE NIK 2013

18 V 1.0 OperatorExampleMeaning =$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; 18 OE NIK 2013

19 V 1.0 OperatorDescriptionExample &&, andLogical AND (&: bitwise AND) $x=6; $y=3; (x 1) is true ||, orLogical OR (|: bitwise OR) $x=6; $y=3; ($x==5 || $y==5) is false !Logical NOT$x=6; $y=3; !($x==$y) is true xorLogical XOR$x=6; $y=3; ($x==6) xor ($y==2) is true &, |, ^, ~Bitwise AND, OR, XOR, NOT <<Left Shift (SHL) >>Right Shift (SHR) 19 OE NIK 2013

20 V 1.020 Other operators Access operators Ternary operator Operator ExpressionMeaning -> x->yMember access (class) ( ) f(x)Function call [ ] a[x]Extract parts of strings (later) Array indexing (later) Operator ExpressionMeaning ? : 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

21 V 1.0 IF <?php $num=rand(10, 100); if ($num%2 == 0) { echo "Even"; } else { echo "Odd"; } ?> 21 OE NIK 2013 if (condition) // code to execute if the condition is true else // code to execute if the condition is false

22 V 1.0 ELSEIF if (condition1) // code to execute, if condition1 is true elseif (condition2) // otherwise, code to execute, if condition2 is true else // otherwise, the code to execute 22 OE NIK 2013

23 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

24 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... 24 OE NIK 2013 if (condition) // code to execute if the condition is true else // code to execute if the condition is false

25 V 1.0 SHORTint(0)int(1)bool(false)bool(true)string(1) "0"string(1) "1" string(4) "some" string(0) "" int(0)FALSESame Equals int(1)TRUE Same Equals bool(false)FALSEEquals Same Equals bool(true)TRUE Equals Same Equals string(1) "0"FALSEEquals Same string(1) "1"TRUE Equals Same string(4) "some"TRUEEquals Same string(0) ""FALSEEquals Same 25 OE NIK 2013

26 V 1.0 SWITCH 26 OE 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; }

27 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"; } 27 OE 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!

28 V 1.0 WHILE The condition is always a stay-in condition Look out for infinite loops!  max_time_limit, ignore_user_abort 28 OE NIK 2013 while (condition) { //code to be executed } do { // code to be executed } while (condition);

29 V 1.0 WHILE "; $i++; } ?> 29 OE NIK 2013

30 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 30 OE NIK 2013 for (initialization; stay-in condition; increment) { // code to be executed }

31 V 1.0 FOR "; } ?> 31 OE NIK 2013

32 V 1.0 Break / continue $i = 0; while (true) { if ($i == 10) { break; } echo $i.” ”; $i++; } for ($i = 0; $i < 10; $i++) { for ($j = 0; $j < 3; $j++) { if (($j + $i) % 5 == 0) { break 2; // Both loops } } } 32 OE NIK 2013 for ($i = 0; $i 3 && $i ”; } $i=0; do { $i+=0.1; echo "NUM: {$i} "; if ($i>200) break; } while ($i!=100);

33 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 } ; 33 OE NIK 2013

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

35 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) 35 OE NIK 2013

36 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 36 OE NIK 2013

37 V 1.0 Variable scope Every 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 37 OE NIK 2013

38 V 1.0 Variable scope $a = "Hello"; $b = "World"; function hello() { global $a, $b; echo "{$a} {$b}"; } hello(); // „Hello World” 38 OE NIK 2013 $a = "Hello"; function hello() { global $b; $b = "World"; } echo "{$a} {$b}“; // „Hello World”

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

40 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 A B = 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 A 40 OE NIK 2013

41 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. 41 OE NIK 2013

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

43 V 1.0 OE NIK 2013 43

44 44 OE NIK 2013


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

Similar presentations


Ads by Google