1 / 42

Introduction to PHP

Introduction to PHP. Server-Side Scripting MySQL PHP Apache Variables Control Structure Looping. Server-Side Scripting. A “script” is a collection of program or sequence of instructions that is interpreted or carried out by another program rather than by the computer processor.

alda
Download Presentation

Introduction to PHP

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. Introduction to PHP Server-Side Scripting MySQL PHP Apache Variables Control Structure Looping

  2. Server-Side Scripting • A “script” is a collection of program or sequence of instructions that is interpreted or carried out by another program rather than by the computer processor. • Client-side • Server-side • In server-side scripting, (such as PHP, ASP) the script is processed by the server Like: Apache, ColdFusion, ISAPI and Microsoft's IIS on Windows. • Client-side scripting such as JavaScript runs on the web browser.

  3. Server-Side Scripting – Continued • Advantages of Server-Side Scripting • Dynamic content. • Computational capability. • Database and file system access. • Network access (from the server only). • Built-in libraries and functions. • Known platform for execution (as opposed to client-side, where the platform is uncontrolled.) • Security improvements

  4. Introduction to PHP • PHP stands for PHP: Hypertext Preprocessor • Developed by Rasmus Lerdorf in 1994 • It is a powerful server-side scripting language for creating dynamic and interactive websites. • It is an open source software, which is widely used and free to download and use (PHP is FREE to download from the official PHP resource: www.php.net). • It is an efficient alternative to competitors such as Microsoft's ASP.

  5. Introduction to PHP • PHP is perfectly suited for Web development and can be embedded directly into the HTML code. • The PHP syntax is very similar to JavaScript, Perl and C. • PHP is often used together with Apache (web server) on various operating systems. It also supports ISAPI and can be used with Microsoft's IIS on Windows. • PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)

  6. Introduction to PHP • What is a PHP File? • PHP files have a file extension of ".php", ".php3", or ".phtml" • PHP files can contain text, HTML tags and scripts • PHP files are returned to the browser as plain HTML 

  7. Introduction to PHP What you need to develop PHP Application: • Install Apache (or IIS) on your own server, install PHP, and MySQL • OR • Install Wampserver2 (a bundle of PHP, Apache, and MySql server) on your own server/machine

  8. PHP Installation Downloads Free Download • PHP: http://www.php.net/downloads.php • MySQL Database: http://www.mysql.com/downloads/index.html • Apache Server: http://httpd.apache.org/download.cgi • How to install and configure apache • Here is a link to a good tutorial from PHP.net on how to install PHP5: http://www.php.net/manual/en/install.php

  9. How PHP is Processed • When a PHP document is requested of a server, the server will send the document first to a PHP processor • Two modes of operation • Copy mode in which plain HTML is copied to the output • Interpret mode in which PHP code is interpreted and the output from that code sent to output • The client never sees PHP code, only the output produced by the code

  10. Basic PHP Syntax • PHP statements are terminated with semicolons ; • Curly braces, { } are used to create compound statements • Variables cannot be defined in a compound statement unless it is the body of a function • PHP has typical scripting language characteristics • Dynamic typing, un-typed variables • Associative arrays • Pattern matching • Extensive libraries • Primitives, Operations, Expressions • Four scalar types: boolean, integer, double, string • Two compound types: array, object • Two special types: resource and NULL

  11. Basic PHP Syntax • A PHP scripting block always starts with <?php and ends with ?> <?php ……………. ?> • Other options are: • <? ……………… ?> • <script> ... </script> • There are three basic statements to output text with PHP: echo,print, and printf. Example: echo 'This is a <b>test</b>!'; • Comments: • # • // • /* . . . */

  12. Basic PHP Syntax • Inserting external files: • PHP provides four functions that enable you to insert code from external files: include() or require()include_once() orrequire_once() functions. • E.g. • include("table2.php"); • Included files start in copy mode

  13. Basic PHP Syntax Example 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Simple PHP Example</title> <body> <?php echo "Hello Class of 2011. This is my first PHP Script"; echo "<br />"; print "<b><i>What have you learnt and how many friends have you made?</i></b>"; echo "<br /><a href='PHP I-BSIC.ppt'>PHP BASIC</a>"; ?> </body> </html>

  14. Example: <html> <head> <title>My first PHP page</title> </head> <body> <?php $var1 = 'PHP'; // Assigns a value of 'PHP' to $var1 $var2 = 5; // Assigns a value of 5 to $var2 $var3 = $var2 + 1; // Assigns a value of 6 to $var3 $var2 = $var1; // Assigns a value of 'PHP' to $var2 echo $var1; // Outputs 'PHP‘ echo "<br />"; echo $var2; // Outputs 'PHP' echo "<br />"; echo $var3; // Outputs '6' echo "<br />"; echo $var1 . ' rules!'; // Outputs 'PHP rules!' echo "$var1 rules!"; // Outputs 'PHP rules!' echo '$var1 rules!'; // Outputs '$var1 rules!‘ ?> </body> </html> PHP Variables • Variables are used for storing values, such as numbers, strings or function results, so that they can be used many times in a script. • All variables in PHP start with a $ sign symbol. • Variables are assigned using the assignment operator "=" • Variable names are case sensitive in PHP: $name is not the same as $NAME or $Name. • In PHP a variable does not need to be declared before being set. • PHP is a Loosely Typed Language.

  15. Variable Naming Rules • A variable name must start with a letter or an underscore "_" • A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) • If variable name is more than one word, it should be separated with an underscore e.g. ($my_string), or with capitalization ($myString)

  16. Variable Scope and Lifetime • Example: • <?php • function mul() • { • global $start; • print "<tr>"; • for ($num=1; $num <= 10; $num++ ) • { • $cell = $num * $start; • print "<td> " . $cell . " </td>"; • } • print "</tr>"; • } • $start = 0; • print "<table border=1 cellpadding=3>"; • while ( $start <=10 ) • { • mul(); • $start++; • } • print "</table>"; • ?> • The scope of a variable defined within a function is  local to that function. • A variable defined in the main body of code has a global scope.  • If a function needs to use a variable that is defined in the main body of the program, it must reference it using the "global" keyword, like this:

  17. Strings in PHP • a string is a sequence of letters, symbols, characters and arithmetic values or combination of all tied together in single or double quotes. • String literals are enclosed in single or double quotes • Example: <?php $sum = 20; echo 'the sum is: $sum'; echo "<br />"; echo "the sum is: $sum"; echo "<br />"; echo '<input type="text" name="first_name" id="first_name">'; ?> • Double quoted strings have escape sequences (such as /n or /r) interpreted and variables interpolated (substituted) • Single quoted strings have neither escape sequence interpretation nor variable interpolation • A literal $ sign in a double quoted string must be escaped with a backslash, \ • Double-quoted strings can cover multiple lines

  18. Escaping quotes with in quotes Example 1: <?php $str = "\"This is a PHP string examples quotes\""; echo $str; ?> Example 2 <?php $str = 'It\'s a nice day today.'; echo $str; ?>

  19. The Concatenation Operator • The concatenation operator (.)  is used to put two string values together. • Example: <?php $txt1="Hello Everyone,"; $txt2="1234 is Dan’s home address"; echo $txt1.$txt2; ?>

  20. PHP Operators • Operators are used to operate on values. • List of PHP Operators:

  21. PHP Function • In php a function is a predefined set of commands that are carried out when the function is called. • The real power of PHP comes from its functions. • PHP has more than 700 built-in or predefine functions for you to use. • Complete php string reference • You can write your own functions

  22. Using Built-in Fuctions • Useful PHP String Functions <?php echo strlen("Hello world!"); echo "<br />"; echo strpos("Hello world!","world"); ?> </body> </html> • Useful PHP String Functions Example - strlen() Function <?php $str = "Hello world!"; echo strlen($str); ?> Example - strlen() Function <?php $str = “Hello world!”; echo strpos(“$str”,"world"); ?> </body> </html>

  23. Using Built-in Function <html> <head> <title>My first PHP page</title> </head> <body> <?php $a = abs(-.43); $b = sqrt(16); $c = round(12.3); print "The absolute value of -.43 is " . $a . "<br />"; print "The square root of 16 is " . $b . "<br />"; print "12.3 rounded is " . $c . " and 12.5 rounded is " . round(12.5); ?> </body> </html>

  24. Using Built-in Function • Examples: Inserting external files: • PHP provides four functions that enable you to insert code from external files: include() or require()include_once() or require_once() functions. • A sample include file called add.php <html> <body> <?php function add( $x, $y ) { return $x + $y; } ?> <h1>Welcome to my home page</h1> <p>Some text</p> </body> </html> Using the include function <?php include('add.php'); echo add(2, 2); ?>

  25. Using Built-in Function • Inserting external files - continued: • The functions are identical in every way, except how they handle errors. • The include() and include_once() functions generates a warning (but the script will continue execution) • The require() and require_once() functions generates a fatal error (and the script execution will stop after the error). • These functions are used to create functions, headers, footers, or elements that can be reused on multiple pages. • This can save the developer a considerable amount of time for updating/editing.

  26. Date Function Formatting • TIMEa - am or pmA - AM or PMB - Swatch Internet time (000 - 999)g - 12 hour (1-12)G - 24 hour c (0-23)h - 2 digit 12 hour (01-12)H - 2 digit 24 hour (00-23)i - 2 digit minutes (00-59)s 0 2 digit seconds (00-59) • OTHER e - timezone (Ex: GMT, CST)I - daylight savings (1=yes, 0=no)O - offset GMT (Ex: 0200)Z - offset in seconds (-43200 - 43200)r - full RFC 2822 formatted date • Date Function Formatting • DAYS d - day of the month 2 digits (01-31) j - day of the month (1-31) D - 3 letter day (Mon - Sun) l - full name of day (Monday - Sunday) N - 1=Monday, 2=Tuesday, etc (1-7) S - suffix for date (st, nd, rd) w - 0=Sunday, 1=Monday (0-6) z - day of the year (1=365) • WEEKW - week of the year (1-52) • MONTHF - Full name of month (January - December)m - 2 digit month number (01-12) n - month number (1-12) M - 3 letter month (Jan - Dec) t - Days in the month (28-31) • YEARL - leap year (0 no, 1 yes)o - ISO-8601 year number (Ex. 1979, 2006)Y - four digit year (Ex. 1979, 2006)y - two digit year (Ex. 79, 06)

  27. Using Built-in Function PHP Date() function formatting characters: Example 1: <?php $theDate = date("m/d/y"); echo "Today's date is: $theDate"; ?> Example 2 <?php $b = time (); print date("m/d/y",$b) . "<br />"; print date("D, F jS",$b) . "<br />"; print date("l, F jSY",$b) . "<br />"; print date("g:i A",$b) . "<br />"; print date("r",$b) . "<br />"; print date("g:i:s A D, F jSY",$b) . "<br />"; ?>

  28. Defining and Referencing a Function Syntax functionfunctionname(){ your code } Example: <html> <body> <?php Function Name() { echo "Ben John"; } Name(); ?> </body> </html>

  29. PHP Functions - Adding parameters Functions can also be used to return values. Example: <html> <body> <?php function add($x,$y) { $total = $x + $y; return $total; } echo "1 + 16 = " . add(1,16); ?> </body> </html> • A parameter is just like a variable. • The parameters are specified inside the parentheses. Syntax: <?php   function function_name(param_1, ... , param_n)    {       statement_1;       statement_2;       ...statement_m;       return return_value;    } ?>

  30. Control Structure • Control structures are the building blocks of any programming language. PHP provides all the control structures that you may have encountered anywhere. The syntax is the same as C or Perl. • Making computers think has always been the goal of the computer architect and the programmer. Using control structures computers can make simple decisions and when programmed cleverly they can do some complex things.

  31. Conditional Statements • If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces: • <?php • $d=date("D"); • if ($d=="Fri") • { echo "Hello!<br />"; • echo "Have a nice weekend!"; • echo "See you on Monday!"; } ?> • The If...Else Statement Syntax if (condition) code to be executed if condition is true; else code to be executed if condition is false; <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?>

  32. Conditional Statements <html><head> <title>good ......</title> </head> <body> <?php $hour = date("H"); if ($hour <= 11) { echo "good morning my friend"; } elseif ($hour > 11 &&$hour < 18) { echo "good afternoon my friend"; } else { echo "good evening my friend"; } ?> </body></html> 2. The ElseIf Statement • If you want to execute some code if one of several conditions is true use the elseif statement Syntax if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false;

  33. PHP Switch Statement switch ($textcolor) { case "black": echo "I'm black"; break; case "blue": echo "I'm blue"; break; case "red": echo "I'm red"; break; default: // It must be something else echo "too bad!!, I'm something else"; } • If you want to select one of many blocks of code to be executed, use the Switch statement. • The switch statement is used to avoid long blocks of if..elseif..else code. Syntax switch (expression) { case label1:code to be executed if expression = label1; break; case label2:code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; }

  34. PHP Looping • Looping statements in PHP are used to execute the same block of code a specified number of times. • In PHP we have the following looping statements: • while - loops through a block of code if and as long as a specified condition is true • do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true • for - loops through a block of code a specified number of times • foreach- loops through a block of code for each element in an array

  35. The while Statement Example <html> <head> <title>Let us count !!!</title></head> <body> <?php $limit = 10; echo "<h2> Let us count from 1 to $limit </h2><br />"; $count = 1; while ($count <= $limit) { echo "counting $count of $limit <br>"; $count++; } ?> </body> <html> Syntax while (condition) { // statements }

  36. The do...while Statement Example <html> <body> <?php $i=0; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<5); ?> </body> </html> • 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);

  37. The for Statement Example <html> <body> <?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> </body> </html> • It is used when you know how many times you want to execute a statement or a list of statements. Syntax • for (init; cond; incr) { code to be executed; } Parameters: • init: Is mostly used to set a counter, but can be any code to be executed once at the beginning of the loop statement. • cond: Is evaluated at beginning of each loop iteration. If the condition evaluates to TRUE, the loop continues and the code executes. If it evaluates to FALSE, the execution of the loop ends. • incr: Is mostly used to increment a counter, but can be any code to be executed at the end of each loop.

  38. The foreach Statement Example <html> <body> <?php $arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; } ?> </body> </html> • The foreach statement is used to loop through arrays. • For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop, you'll be looking at the next element. Syntax • foreach (array as value) { code to be executed; }

  39. PHP Arrays • An array can store one or more values in a single variable name. • There are three different kind of arrays: • Numeric array - An array with a numeric ID key • Associative array - An array where each ID key is associated with a value • Multidimensional array - An array containing one or more arrays

  40. Numeric Array Example 3: <?php $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe"; echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors"; ?> • A numeric array stores each element with a numeric ID key. • There are different ways to create a numeric array: Example 1 • In this example the ID key is automatically assigned: • $names = array("Peter","Quagmire","Joe"); Example 2 • In this example we assign the ID key manually: $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe";

  41. Associative Arrays Example 3: <?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?> • Each ID key is associated with a value. • When storing data about specific named values, a numerical array is not always the best way to do it. • There are two ways of creating Associative Array: Example 1 • $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); Example 2 • $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";

  42. Multidimensional Arrays • Example 2: • The array above would look like this if written to the output: • Array • ( • [Griffin] => Array • ( • [0] => Peter • [1] => Lois • [2] => Megan • ) • [Quagmire] => Array • ( • [0] => Glenn • ) • [Brown] => Array • ( • [0] => Cleveland • [1] => Loretta • [2] => Junior ) • ) • displaying a single value from the array above: • echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?"; • In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. • Example 1 • with automatically assigned ID keys: $families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );

More Related