1 / 61

PHP Scripting language

PHP Scripting language. Something about PHP. PHP = PHP Hypertext Preprocessor Open-source Easy to use ( C-like and Perl-like syntax) Multiplatform Many databases support Many common built-in libraries Pre-installed in Linux distributions. Client Browser. 4. 1. PHP module. 3. Apache.

ena
Download Presentation

PHP Scripting language

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PHP Scripting language

  2. Something about PHP • PHP = PHP Hypertext Preprocessor • Open-source • Easy to use ( C-like and Perl-like syntax) Multiplatform • Many databases support • Many common built-in libraries • Pre-installed in Linux distributions

  3. Client Browser 4 1 PHP module 3 Apache 2 How PHP generates HTML/JS Web pages 1: Client from browser send HTTP request (with POST/GET variables) 2: Apache recognizes that a PHP script is requested and sends the request to PHP module 3: PHP interpreter executes PHP script, collects script output and sends it back 4: Apache replies to client using the PHP script output as HTML output

  4. HTML Embedding • SGML style: <? code ?> • XML style: <?php code ?> • ASP style: <% code %> • Javascript style: <script language=“php”> code</script>

  5. Integrated with HTML code • Possible within a block of statements:

  6. <html> <head> <title>My personal Hello World! PHP script</title> </head> <body> <? echo “Hello World!”; ?> </html> Hello World! (web oriented) PHP tag, allow to insert PHP code. Interpretation by PHP module will substitute the code with code output

  7. Data types • PHP Manual about data types http://tw2.php.net/manual/en/language.variables.php • Basic data types • numbers (integers and real) Decimal 1234, Octal 0777, Hex 0xff • strings Double-quoted "abc", single-quoted 'abc' • booleans true,false • Dynamic data typing • Don't have to declare types • Automatic conversion done

  8. To use or assign variable $ must be present before the name of the variable The assign operator is '=' There is no need to declare the type of the variable the current stored value produces an implicit type-casting of the variable. A variable can be used before to be assigned $A = 1; $B = “2”; $C = ($A + $B); // Integer sum $D = $A . $B; // String concatenation echo $C; // prints 3 echo $D;// prints 12 Variables (I)

  9. Function isset tests if a variable is assigned or not $A = 1; if (isset($A)) print “A isset” if (!isset($B)) print “B is NOT set”; Using $$ $help = “hiddenVar”; $$help = “hidden Value”; echo $$help; // prints hidden Value $$help = 10; $help = $$help * $$help; echo $help; // print 100 Variables (II)

  10. A string is a sequence of chars $stringTest = “this is a sequence of chars”; echo $stringTest[0]; output: t echo $stringTest; output: this is a sequence of chars A single quoted strings is displayed “as-is” $age = 37; $stringTest = 'I am $age years old'; // output: I am $age years old $stringTest = “I am $age years old”; // output: I am 37 years old Concatenation $conc = ”is “.”a “.”composed “.”string”; echo $conc; // output: is a composed string $newConc = 'Also $conc '.$conc; echo $newConc; // output: Also $conc is a composed string Strings (I)

  11. Explode function $sequence = “A,B,C,D,E,F,G”; $elements = explode (“,”,$sequence); // Now elements is an array with all substrings between “,” char echo $elemets[0]; // output: A; echo $elemets[1]; // output: B; echo $elemets[2]; // output: C; echo $elemets[3]; // output: D; echo $elemets[4]; // output: E; echo $elemets[5]; // output: F; echo $elemets[6]; // output: G; Strings (II)

  12. Groups a set of variables, every element stored into an array as an associated key (index to retrieve the element) $books = array( 0=>”php manual”,1=>”perl manual”,2=>”C manual”); $books = array( 0=>”php manual”,”perl manual”,”C manual”); $books = array (“php manual”,”perl manual”,”C manual”); echo $books[2]; output: C manual Arrays with PHP are associative $books = array( “php manual”=>1,”perl manual”=>1,”C manual”=>1); // HASH echo $books[“perl manual”]; output: 1 $books[“lisp manual”] = 1; // Add a new element Arrays (I)

  13. Working on an arrays $books = array( ”php manual”,”perl manual”,”C manual”); Common loop for ($i=0; $i < count($books); $i++) print ($i+1).”-st book of my library: $books[$i]”; each $books = array( “php manual”=>1,”perl manual”=>2,”C manual”=>3); while ($item = each( $books )) // Retrieve items one by one print $item[“value”].”-st book of my library: ”.$item[“key”]; // each retrieve an array of two elements with key and value of current element each and list while ( list($value,$key) = each( $books )) print “$value-st book of my library: $key”; // list collect the two element retrieved by each and store them in two different // variables Arrays (II)

  14. Multidimensional arrays $books = array( array(“title”=>“php manual”,”editor”=>”X”,”author”=>”A”), array(“title”=>“perl manual”,”editor”=>”Y”,”author”=>”B”), array(“title=>“C manual”,”editor”=>”Z”,author=>”C”)); Common loop for ($i=0; $i < count($books); $i++ ) print “$i-st book, title: ”.$books[$i][“title”].” author: “.$books[$i][“author”]. “ editor: “.$books[$i][“editor”]; // Add .”\n” for text new page or “.<BR>” for HTML new page; Use list and each for ($i=0; $i < count($books); $i++) { print “$i-st book is: “; while ( list($key,$value) = each( $books[$i] )) print “$key: $value ”; print “<BR>”; // or “\n” } Arrays (III)

  15. Arithmetic Operators

  16. Logical Operators

  17. Comparison Operators

  18. C-like syntax • For loops • While • switchcasebreak • ++ / -- • elseif

  19. <!--#! /usr/local/bin/php --> <html> <body> <h2>Radio buttons example</h2> <form><tableborder=0><tr><th>Button</th><th>Text</th></tr><?php for ($j=1; $j<6; $j++) { $rbname = "rbn"; $rbvalue = "rbv_".$j; $rbtext = "Text_".$j; $radio = "input type=\"radio\" name=\"$rbname\" value=\"$rbvalue\" " ; if ($j == 3) $radio .= " checked=\"checked\" "; echo "<tr><td align =\"center\"><$radio></td> <td>$rbtext</td></tr>"; };?></table> </form></body></html> LOOPING EXAMPLE

  20. Arrays Construct arrays using the array() function: $numbers = array(5,4,3,2,1) $words = array(“Web”,”Database”,”Interactive”,”Apps”) Numbered arrays: accessed by numeric indexDefault: Index of 1st element is 0. Echo $words[0]; // Web Echo $words[3]; // Apps $words() = “GUI”; // adds a 5th element to the above $words(5) = “Usability”; // adds 6th element

  21. Associative Arrays Also called string-indexed arrays Uses key to access values stored in the array: $catch_it[‘cat’] = “mouse”; $catch_it[‘dog’] = “cat”; echo catch_it[‘dog’]; // prints “cat”

  22. … <h2>Radio buttons array example</h2> <form><tableborder=0><tr><th>Button</th><th>Text</th></tr><?php $pizza_type = array("Ham","Sausage","Pepperoni","Anchovies","Cheese");for ($j=1; $j<6; $j++) { $rbname = "rbn"; $rbvalue = "rbv_".$j; $rbtext = $pizza_type[$j -1]; $radio = "input type=\"radio\" name=\"$rbname\" value=\"$rbvalue\" " ; if ($j == 3) $radio .= " checked=\"checked\" "; echo "<tr><td align =\"center\"><$radio></td> <td>$rbtext</td></tr>"; };?></table></form></body></html> Array Example

  23. Form Handling (1) • Three methods • Short: $varfoo (the variable name defined in the <FORM>) • Medium: $_POST[‘varfoo’], (recommended for versions of PHP +4.1) • Long: $HTTP_POST_VARS[‘varfoo’] • Need register_globals ON for short method to work. If register_globals = on, the EGPCS (Environment, GET, POST, Cookie, Server) variables are regarded as global variables. • Tip: For checkbox variables your variable name should end with [ ] • Checkbox results are automatically put into an array • Example: <input type=checkbox name=foo[] value=Y>

  24. Form Handling (2) “action.php” • Traditional: • Since PHP 4.2: • Better: less danger for incorrect programs “form.php”

  25. PHP Variables from a Form <html><body><?phpif ( $name ) { print( "Hello, $name !");} else { // form entry print( "<form action=\"$PHP_SELF\" method=post>\n"); print( "Your name: <input type=text size=10 name=name ><br>\n"); print("<input type=submit value=Submit>\n" ); print("</form>\n");}?></body></html>

  26. Passing variables via URL You can test by setting variables through a URL: http://localhost/php/urlvariables.php?var1=This+is+a+String&var2=3.1415159265 (urlvariables.php) <!--#! /usr/local/bin/php --><html><body><?php echo "$var1 <br>"; ?><?php echo "$var2 <br>";?></body></html>

  27. Dates Date and Time is carried in Unix timestamp:Number of seconds since 1 Jan 1970 GMT To create a timestamp, use mktime(): int mktime(int hour, int minute, int second, int month, int day, int year [, int is_dst] Ex: $aDate = mktime(9, 30,0,6,18,1998) 9:30 A.M. on June 18, 1998 String to timestamp: $var = strtotime(“25 December 2002”)

  28. Formatting a Date Date() function: string date(string format, [int timestamp]) $var = mktime(8, 15, 25, 8, 24, 1964); echo date(‘d/m/Y’,$var); // “24/08/1964” echo date(‘m/d/y’,$var); // “08/24/64” echo date(‘m/d/y); // “03/12/03” (today) Many powerful formatting arguments: see the PHP on-line manual.

  29. Other Functions Absolute Value: echo abs(-1); // prints 1 Ceiling and Floor: integer above or below float echo ceil(27.3); // prints 28 echo floor(27.3); // prints 27 Rounding: Up or down value to given precision echo round(10.4); // prints 10 echo round(10.5); // prints 11 echo round(2.40964,3); // prints 2.410

  30. Random Number Generation Random number generation: needs seeding // generate a seed$seed = (float) srand(microtime() * 100000000; // seed the random number generatorsrand($seed); // generate random numbersecho rand(); // between 0 and getmaxrand() echo rand(1,6); // random numbers between // 1 and 6, inclusive

  31. User-Defined Functions <?php function doublevalue($var) {$returnVal = $var * 2;return($returnVal);}$var = 5;$temp = doublevalue($var);echo "$temp";?>

  32. function function_name([parameters-list]opt) {……implementation code……} parameters-list is a sequence of variables separated by “,” it’s not allowed to overload the name of an existing function; Function names aren’t case-sensitive; To each parameter can be assigned a default value; arguments can be passed by value or by reference It’s possible using a variable number of parameters Syntax to define a function

  33. Passing Arguments • Passing By Value: (outputs 5) function square($p) { return $p*$p; } $a=5; echo square($a); • Passing By Reference: (outputs 25) function square($p) { return $p*$p; } $a=5; echo square(&$a);

  34. Variable Scope • Local and Global are the only options • Variables defined within functions have scope local to that function. • To access a global variable from within a function use the GLOBAL keyword: function test() { global $a; echo $a; } $a = “the quick brown fox”; test(); • Alternatively use $GLOBALS array: function test() { echo $GLOBALS[“a”]; } $a = “the quick brown fox”; test();

  35. Include Files You can put several functions into a file and save it: <?php function doublevalue($var) {$returnVal = $var * 2;return($returnVal);}function bold($string){echo "<b>" . $string . "</b>\n";}?>Save this file as stdfunctions.inc

  36. Using Include Files <html><body><?include "stdfunctions.inc";echo "this is not bold <br>\n" ;bold("this is bold");echo "<br>again, this is not bold <br> \n";bold(doublevalue(3.14));?></body></html>

  37. #cat /usr/local/myDatabaseDirectory/library.txt php manual X A 330 perl manual Y B 540 C manual Z C 480 (fields separated by tabs: 'php manual<tab>X<tab>A', new line at the end of each entry) <? // script to show all book in my library $books = file(“/usr/local/myDatabaseDirectory/library.txt”); // retrieve library “database” for ($i=0; $i<count($books), $i++ ) $books_array[$i] = explode( “\t”, $books[$i]); // Extract elements from line ... for ($i=0; $i<count($books_array), $i++ ) print “$i-st book, title: ”.$books_array[$i][“title”].” author: “.$books_array[$i][“author”]. “ editor: “.$books_array[$i][“editor”].”<BR>”; File Access

  38. Sessions • A session is the time a client spends on a site. • A session id is stored (as a cookie) on the client OR passed along via the URLs (using php only). The id is a key to session information stored on the server for each client. • Php sessions will work even if cookies have been disabled by the person using the browser • Session information is stored on the server.

  39. PHP Sessions • session_start(); called at each script using the session variables • $total = …. • $cart["pencils"] = $qty; • $cart[$productname] = $productqty; • session_register("total"); • session_register("cart"); • any other script, can use $cart and $total. • $result = session_is_registered("total"); • session_unregister("total"); • session_destroy();

  40. Object Oriented PHP • Encapsulation • Polymorphism • Inheritance • Multiple Inheritance: actually unsupported

  41. $val4 = (($month+1)*3)/5; $val5 = $year/4; $val6 = $year/100; $val7 = $year/400; $val8 = $day+($month*2)+$val4+$val3+$val5-$val6+$val7+2; $val9 = $val8/7; $val0 = $val8-($val9*7); return $val0; } } // Main $instance = new dayOfWeek($_GET[“day”],$_GET[“week”],$_GET[“ month”]); print “You born on “.$instance->calculate().”\n”; ?> Encapsulation <? class dayOfWeek { var $day,$month,$year; function dayOfWeek($day,$month,$year) { $this->day = $day; $this->month = $month; $this->year = $year; } function calculate(){ if ($this->month==1){ $monthTmp=13; $yearTmp = $this->year - 1; } if ($this->month == 2){ $monthTmp = 14; $yearTmp = $this->year - 1; }

  42. Allow the creation of a hierarchy of classes Inheritance Class reuseMe { function reuseMe(){...} function doTask1(){...} function doTask2(){...} function doTask3(){...} } Class extends reuseMe { function example(){ ... // local initializations // call super constructor reuseMe::reuseMe(); } function doTask4(){...} function doTask5(){...} function doTask6(){...} }

  43. Polymorphism A member function can override superclass implementation. Allow each subclass to reimplement a common interfaces. class reuseMe { function reuseMe(){...} function doTask1(){...} function doTask2(){...} function doTask3(){...} } Class extends reuseMe { function example(){ ... // local initializations // call super constructor reuseMe::reuseMe(); } function doTask4(){...} function doTask5(){...} function doTask6(){...} function doTask3(){...} }

  44. Class example class Cart { var $items; // Items in our shopping cart // Add $num articles of $artnr to the cart function add_item ($artnr, $num) { $this->items[$artnr] += $num; } // Take $num articles of $artnr out of the cart function remove_item ($artnr, $num) { if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; } else { return false; } } }

  45. Inheritance example Class ParentObject {    var $value;   function ParentObject() {        $this->value = 42;   } } class MemberObject extends ParentObject {    var $string;    function MemberObject() {       $this->string = "This is a test string."; $this->ParentObject();   } } class ObjTest {    var $ObjPointer;   function ObjTest() {        $tmp = new MemberObject; $this->ObjPointer = $tmp;   } } $object = new ObjTest; echo "String Contents: " . $object->ObjPointer->string . "\n"; echo "Value  Contents: " . $object->ObjPointer->value . "\n";

  46. class extends reuseMe1,reuseMe2 {...} Multiple Inheritance not actually supported by PHP class reuseMe1 { function reuseMe1(){...} function doTask1(){...} function doTask2(){...} function doTask3(){...} } class reuseMe2 { function reuseMe2(){...} function doTask3(){...} function doTask4(){...} function doTask5(){...} }

  47. Overview of MySQL • Relational database management system (RDBMS) • Free • Website @ http://www.mysql.com/

  48. MySQL Basics • Common SQL Statements • INSERT • SELECT • UPDATE • DELETE • Simple Join • Entity-Relationship (ER) Modeling • An Easy Way to Manage Your MySQL DBs

  49. MySQL Basics (cont.) • A relational database manager (MySQL) manages databases which holds tables which has records (rows) with attributes (columns) • Each record must have a unique ID, also known as a Primary Key. When used as an identifier in another table it’s called a Foreign Key. Used for joins. • Each attribute has to have a data type. (e.g. int, text, varchar) • A database language (SQL) is used to create and delete databases and manage data

More Related