1 / 70

PHP Programming Web Development

PHP Programming Web Development. Required Output. At the end of the course, student should be able to develop one of the following web applications… Instructor’s Web Portal student’s registration School’s Online Registration Simulation of an Online Shopping. Pre-Requisites.

oleg-garcia
Télécharger la présentation

PHP Programming Web Development

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

  2. Required Output • At the end of the course, student should be able to develop one of the following web applications… • Instructor’s Web Portal • student’s registration • School’s Online Registration • Simulation of an Online Shopping

  3. Pre-Requisites • Basic knowledge on the following: • Hypertext Mark-Up Language (HTML) • JavaScript • Cascading Style Sheets (CSS) • C/C++ Language

  4. What is PHP? • PHP is a simple yet powerful language designed for creating HTML content. • A server-side scripting language designed to create dynamic web content. To generate HTML, you need the PHP parser and a web server to send the documents. • PHP runs on all major operating systems, from Unix variants including Linux, FreeBSD, and Solaris to such diverse platforms as Windows and Mac OS X. It can be used with all leading web servers, including Apache, Microsoft IIS, and the Netscape/iPlanet servers. • One of PHP's most significant features is its wide-ranging support for databases. PHP supports all major databases (including MySQL, PostgreSQL, Oracle, Sybase, and ODBC-compliant databases), and even many obscure ones. With PHP, creating web pages with dynamic content from a database is remarkably simple.

  5. Embedding PHP in Web Pages Although it is possible to write and run standalone PHP programs, most PHP code is embedded in HTML or XML files. This is, after all, why it was created in the first place. Processing such documents involves replacing each chunk of PHP source code with the output it produces when executed. Because a single file contains PHP and non-PHP source code, we need a way to identify the regions of PHP code to be executed. When writing PHP, you need to inform the PHP engine that you want it to execute your commands. If you don't do this, the code you write will be mistaken for HTML and will be output to the browser. You can do this with special tags that mark the beginning and end of PHP code blocks. PHP provides four different ways to do this.

  6. Beginning & Ending Block of a PHP Code

  7. Display Function

  8. Testing PHP Installation The simplest way to test your PHP installation is to create a small test script utilizing the phpinfo() function. This function will produce a long list of configuration information. Open a text editor and type any of the following lines: <? phpinfo(); ?> <?php phpinfo(); ?> <% phpinfo(); %> <script language="php"> phpinfo (); </script> Save this file as phpinfo.php and place it in the document root of your Web server—the htdocs subdirectory of your Apache installation.

  9. PHP Lexical Structure • The lexical structure of a programming language is the set of basic rules that governs how you write programs in that language. • It is the lowest-level syntax of the language and specifies such things as what variable names look like, what characters are used for comments, and how program statements are separated from each other.

  10. Case Sensitivity The names of user-defined classes and functions, as well as built-in constructs and keywords such as echo, while, class, etc., are not case-insensitive. Thus, these three lines are equivalent: echo 'hello, world'; ECHO 'hello, world'; EcHo 'hello, world'; Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and $NaME are three different variables.

  11. Statements & Semicolon A statement is a collection of PHP code that does something. It can be as simple as a variable assignment or as complicated as a loop with multiple exit points. Here is a small sample of PHP statements, including function calls, assignment, and an if test: echo 'Hello, world'; myfunc(42, 'Test'); $a = 1; $name = 'Alphabet'; $b = $a / 25.0; if ($a == $b) { echo 'Rhyme? And Reason?'; }

  12. Statements & Semicolon PHP uses semicolons to separate simple statements. A compound statement that uses curly braces to mark a block of code, such as a conditional test or loop, does not need a semicolon after a closing brace. Unlike in other languages, in PHP the semicolon before the closing brace is not optional: if ($needed) { echo 'We must have it!'; } The semicolon is optional before a closing PHP tag: <?php if ($a == $b) { echo 'Rhyme? And Reason?'; } echo 'Hello, world' ?>

  13. Whitespace and Line Breaks In general, whitespace doesn't matter in a PHP program. You can spread a statement across any number of lines, or lump a bunch of statements together on a single line. For example, this statement: raise_prices($inventory, $inflation, $cola, $greed); could just as well be written with more whitespace: raise_prices ( $inventory , $inflation , $cola, $greed ); or with less whitespace: raise_prices($inventory,$inflation,$cola,$greed);

  14. Comments • Comments give information to people who read your code, but they are ignored by PHP. Even if you think you're the only person who will ever read your code, it's a good idea to include comments in your code—in retrospect, code you wrote months ago can easily look as though a stranger wrote it. • Shell Type Comment • When PHP encounters a hash mark (#) within the code, everything from the hash mark to the end of the line or the end of the section of PHP code (whichever comes first) is considered a comment. This method of commenting is found in Unix shell scripting languages and is useful for annotating single lines of code or making short notes. • $value = $p * exp($r * $t); # calculate compounded interest

  15. Comments • C++ Comment • When PHP encounters two slash characters (//) within the code, everything from the slashes to the end of the line or the end of the section of code, whichever comes first, is considered a comment. This method of commenting is derived from C++. The result is the same as the shell comment style. • $value = $p * exp($r * $t); // calculate compounded interest

  16. Comments • C Comment • While shell- and C++-style comments are useful for annotating code or making short notes, longer comments require a different style. As such, PHP supports block comments, whose syntax comes from the C programming language. When PHP encounters a slash followed by an asterisk (/*), everything after that until it encounters an asterisk followed by a slash (*/) is considered a comment. • /* In this section, we take a bunch of variables and assign numbers to them. There is no real reason. • */ • $a = 1; $b = 2; $c = 3; $d = 4;

  17. Practice Exercise Create a php script the will display your personal information. Format the page so that it would be nicer.

  18. Data Types • PHP provides eight types of values, or data types. Four are scalar (single-value) types: integers, floating-point numbers, strings, and booleans. Two are compound (collection) types: arrays and objects. The remaining two are special types: resource and NULL.

  19. Data Type: Integer • Integers are whole numbers, like 1, 12, and 256. The range of acceptable values varies according to the details of your platform but typically extends from -2,147,483,648 to +2,147,483,647. • Integer literals can be written in decimal, octal, or hexadecimal. Decimal values are represented by a sequence of digits, without leading zeros. The sequence may begin with a plus (+) or minus (-) sign. If there is no sign, positive is assumed. Examples of decimal integers include the following: 1998 -641 +33

  20. Data Type: Integer • Octal numbers consist of a leading 0 and a sequence of digits from 0 to 7. Like decimal numbers, octal numbers can be prefixed with a plus or minus. Here are some example octal values and their equivalent decimal values: 0755 // decimal 493 +010 // decimal 8 • Hexadecimal values begin with 0x, followed by a sequence of digits (0-9) or letters (A-F). The letters can be upper- or lowercase but are usually written in capitals. Like decimal and octal values, you can include a sign in hexadecimal numbers: 0xFF // decimal 255 0x10 // decimal 16 -0xDAD1 // decimal -56017 • Use the is_int() function to test whether a value is an integer

  21. Data Type: Floating-point • Floating-point numbers (often referred to as real numbers) represent numeric values with decimal digits. Like integers, their limits depend on your machine's details. PHP floating-point numbers are equivalent to the range of the double data type of your C compiler. Usually, this allows numbers between 1.7E-308 and 1.7E+308 with 15 digits of accuracy. • PHP recognizes floating-point numbers written in two different formats. There's the one we all use every day: 3.14 0.017 -7.1 • PHP also recognizes numbers in scientific notation: 0.314E1 // 0.314*101, or 3.14 17.0E-3 // 17.0*10-3, or 0.017 • Use the is_float() function to test whether a value is a floating point

  22. Data Type: String • Because strings are so common in web applications, PHP includes core-level support for creating and manipulating strings. A string is a sequence of characters of arbitrary length. String literals are delimited by either single or double quotes: 'big dog' "fat hog" • Variables are expanded within double quotes, while within single quotes they are not: $name = "Jose"; echo "Hi, $name\n"; echo 'Hi, $name'; Hi, Jose Hi, $name

  23. Data Type: String • Double quotes also support a variety of string escapes

  24. Data Type: String • A single-quoted string only recognizes \\ to get a literal backslash and \' to get a literal single quote. • Use the is_string() function to test whether a value is a string

  25. Data Type: Boolean • A boolean value represents a "truth value"—it says whether something is true or not. Like most programming languages, PHP defines some values as true and others as false. • In PHP, the following values are false: • The keyword false • The integer 0 • The floating-point value 0.0 • The empty string ("") and the string "0" • An array with zero elements • An object with no values or functions • The NULL value

  26. Data Type: Boolean • PHP provides true and false keywords for clarity: • $x = 5; // $x has a true value • $x = true; // clearer way to write it • $y = ""; // $y has a false value • $y = false; // clearer way to write it • Use the is_bool()function to test whether a value is a boolean

  27. Data Type: Array • An array holds a group of values, which you can identify by position (a number, with zero being the first position) or some identifying name (a string): $person[0] = "Edison"; $person[1] = "Wankel"; $person[2] = "Crapper"; $creator['Light bulb'] = "Edison"; $creator['Rotary Engine'] = "Wankel"; $creator['Toilet'] = "Crapper";

  28. The array() construct creates an array: $person = array( 'Edison', 'Wankel', 'Crapper' ); $creator = array( 'Light bulb' => 'Edison', 'Rotary Engine' => 'Wankel', 'Toilet' => 'Crapper' );

  29. There are several ways to loop across arrays, but the most common is a foreach loop: foreach ($person as $name) { echo "Hello, $name<br>"; } foreach ($creator as $invention => $inventor) { echo "$inventor created the $invention<br>"; } Hello, Edison Hello, Wankel Hello, Crapper Edison created the Light bulb Wankel created the Rotary Engine Crapper created the Toilet

  30. You can sort the elements of an array with the various sort functions: • sort($person); • // $person is now array('Crapper', 'Edison', 'Wankel') • asort($creator); • /* $creator is now • array( 'Toilet' => 'Crapper', • 'Light bulb' => 'Edison', • 'Rotary Engine' => 'Wankel‘ • ); • /* • Use the is_array() function to test whether a value is an array

  31. Data Type: Object • PHP supports object-oriented programming (OOP). OOP promotes clean modular design, simplifies debugging and maintenance, and assists with code reuse. • Classes are the unit of object-oriented design. A class is a definition of a structure that contains properties (variables) and methods (functions). Classes are defined with the class keyword: • class Person { • var $name = ''; • function name ($newname = NULL) { • if (! is_null($newname)) { • $this->name = $newname; • } • return $this->name; • } • }

  32. Once a class is defined, any number of objects can be made from it with the new keyword, and the properties and methods can be accessed with the -> construct: • $ed = new Person; • $ed->name('Edison'); • echo 'Hello, '.$ed->name.'<br>'; • $tc = new Person; • $tc->name('Crapper'); • echo 'Look out below ,'.$tc->name; • Hello, Edison • Look out below Crapper • Use the is_object( ) function to test whether a value is an object:

  33. You can use PHP's built-in function gettype() to acquire the type of any variable. If you place a variable between the parentheses of the function call, gettype() returns a string representing the relevant type. <?php $testing; // declare without assigning echo gettype($testing)."<br/>"; // NULL $testing = 5; echo gettype($testing)."<br/>"; // integer $testing = "five"; echo gettype($testing)."<br/>"; // string $testing = 5.0; echo gettype($testing)."<br/>"; // double $testing = true; echo gettype($testing)."<br/>"; // boolean ?>

  34. PHP provides the function settype() to change the type of a variable. To use settype(), you must place the variable to change (and the type to change it to) between the parentheses and separate them by commas. <?php $undecided = 3.14; echo gettype($undecided); // double echo " -- $undecided<br/>"; // 3.14 settype($undecided, string); echo gettype($undecided); // string echo " -- $undecided<br />"; // 3.14 settype($undecided, int); echo gettype($undecided); // integer echo " -- $undecided<br />"; // 3 settype($undecided, double); echo gettype($undecided); // double echo " -- $undecided<br />"; // 3.0 settype($undecided, bool); echo gettype($undecided); // boolean echo " -- $undecided<br />"; // 1 ?>

  35. Variables • Variables in PHP are identifiers prefixed with a dollar sign ($). For example: $name $Age $_debugging $MAXIMUM_IMPACT

  36. A variable may hold a value of any type. There is no compile- or runtime type checking on variables. • You can replace a variable's value with another of a different type: • $what = "Fred"; • $what = 35; • $what = array('Fred', '35', 'Wilma');

  37. Variable Scope • The scope of a variable, which is controlled by the location of the variable's declaration, determines those parts of the program that can access it. • There are four types of variable scope in PHP: local, global, static, and function parameters.

  38. Local Scope A variable declared in a function is local to that function. That is, it is visible only to code in that function, it is not accessible outside the function. In addition, by default, variables defined outside a function (called global variables) are not accessible inside the function. For example, here's a function that updates a local variable instead of a global variable: function update_counter ( ) { $counter++; } $counter = 10; update_counter( ); echo $counter; The $counter inside the function is local to that function, because we haven't said otherwise. The function increments its private $counter, whose value is thrown away when the subroutine ends. The global $counter remains set at 10.

  39. Global Scope Variables declared outside a function are global. That is, they can be accessed from any part of the program. However, by default, they are not available inside functions. To allow a function to access a global variable, you can use the global keyword inside the function to declare the variable within the function. Here's how we can rewrite the update_counter( ) function to allow it to access the global $counter variable: function update_counter ( ) { global $counter; $counter++; } $counter = 10; update_counter( ); echo $counter;

  40. Global Scope A more cumbersome way to update the global variable is to use PHP's $GLOBALS array instead of accessing the variable directly: function update_counter ( ) { $GLOBALS[counter]++; } $counter = 10; update_counter( ); echo $counter;

  41. Static Scope A static variable retains its value between calls to a function but is visible only within that function. You declare a variable static with the static keyword. For example: function update_counter ( ) { static $counter = 0; $counter++; echo "Static counter is now $counter"; echo "<br>"; } $counter = 10; update_counter( ); update_counter( ); echo "Global counter is $counter<br>"; Static counter is now 1 Static counter is now 2 Global counter is 10

  42. Function Parameters A function definition can have named parameters for example: function greet ($name) { echo "Hello, $name<br>"; } greet("Janet"); Function parameters are local, meaning that they are available only inside their functions. In this case, $name is inaccessible from outside greet( ).

  43. About variables… To see if a variable has been set to something, even the empty string, use isset(): $s1 = isset($name); // $s1 is false $name = "Fred"; $s2 = isset($name); // $s2 is true Use unset() to remove a variable's value: $name = "Fred"; unset($name); // $name is NULL

  44. Operators Arithmetic Operators Assignment w/ Operators

  45. Operators Comparison Operators Logical Operators

  46. Q & A Q1:Why can it be useful to know the type of data a variable holds? A1: Often the data type of a variable constrains what you can do with it. You might want to ensure that a variable contains an integer or a double before using it in a mathematical calculation, for example. Q2:Should I obey any conventions when naming variables? A2: Your goal should always be to make your code easy to both read and understand. A variable such as $ab 123245 tells you nothing about its role in your script and invites typos. Keep your variable names short and descriptive. A variable named $f is unlikely to mean much to you when you return to your code after a month or so. A variable named $filename, on the other hand, should make more sense.

  47. Workshop 1: Which of the following variable names is not valid? $a_value_submitted_by_a_user $666666xyz $xyz666666 $_____counter_____ $the first $file-name 2: What will the following code fragment output? $num = 33; (boolean) $num; echo $num; 3: What will the following statement output? echo gettype("4"); 4: What will be the output from the following code fragment? $test_val = 5.4566; settype( $test_val, integer ); echo $test_val;

  48. Exercises • Create a script that contains at least five different variables. Populate them with values of different data types and use the gettype() function to print each type to the browser. • Assign values to two variables. Use comparison operators to test whether the first value is • The same as the second • Less than the second • Greater than the second • Less than or equal to the second Print the result of each test to the browser. Change the values assigned to your test variables and run the script again.

  49. Flow Control Statements • PHP supports a number of traditional programming constructs for controlling the flow of execution of a program. • Conditional statements, such as if/else and switch, allow a program to execute different pieces of code, or none at all, depending on some condition. Loops, such as while and for, support the repeated execution of particular code.

  50. If Statement • The if statement checks the truthfulness of an expression and, if the expression is true, evaluates a statement. An if statement looks like: if (expression) statement • To specify an alternative statement to execute when the expression is false, use the else keyword: if (expression) statement else statement

More Related