1 / 60

Dynamic Web Sites with PHP & MySQL

Dynamic Web Sites with PHP & MySQL. Introduction - Features Syntax with examples Database handling with example Useful hints How to get help. Introduction. PHP is a tool that lets you create dynamic web pages

shaman
Download Presentation

Dynamic Web Sites with PHP & MySQL

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. Dynamic Web Sites with PHP & MySQL Introduction - Features Syntax with examples Database handling with example Useful hints How to get help

  2. Introduction • PHP is a tool that lets you create dynamic web pages • PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally create regular HTML pages • PHP stands for 'Hypertext Pre-Processor' • PHP is script embedded in HTML file, which can generate dynamic HTML contents • It is a server side HTML object-oriented scripting/programming language • Client transparent

  3. What is PHP? • At the most basic level, PHP can do anything any other CGI program can do, such as: • collect form data • generate dynamic page content, or • send and receive cookies • PHP also has support for talking to other services using protocols such as: • IMAP • SNMP • NNTP • POP3 • HTTP • PHP can also: • open network sockets and • interact using other protocols

  4. Functions & Features • Built in support for • Email, FTP, XML, PDF… • Extensive database support • Fully support to all data base products • Over 1000 functions and 50 Modules! • HTTP authentication with PHP • GIF creation with PHP - GD library • File upload support • HTTP cookie support • Error & connection handling • PHP source viewer • Provide easy and powerful hypertext manipulation • High performance : ( 400,000 visitors per day)

  5. History of PHP (Part 1) • PHP is a powerful server side web scripting solution • 1994: Personal project of Rasmus Lerdorf • He combined his Personal Home Page tools scripts with the Form Interpreter, added mSQL support, which resulted the PHP/FI • PHP/FI grew at an amazing pace and people started contributing code to it • By late 1996 PHP/FI was in use on at least 15,000 web sites around the world • By mid-1997 this number had grown to over 50,000 • 1997: New parser (PHP 3.0) from Zeev Suraski & Andi Gutmans • In the PHP 4 the parser is the Zend Engine

  6. History of PHP (Part 2) • It has quickly grown in popularity and according to the February 2001 usage stats PHP is installed on 19.8% of all web sites • in 2000 it was 7%, only • The goal of the language is to allow web developers to write dynamically generated pages quickly • CGI is more powerful in general, while PHP is more convenience to use and write • A lot of possibility of joining to the PHP community...

  7. Grow of PHP Usage I

  8. Grow of PHP Usage II

  9. Why use PHP? • Today Version 4 : powerful language • Cross-platform, extensible, FAST • Very easy to learn / teach • Cheap • Great online community support • It had become the most well-known and most widely used scripting language for • Web, Internet, e-commerce, business-to-business projects • Speed • PHP runs 5 to 20 times faster than Java • It is extremely easy to use and you can develop very complex web/e-commerce applications very rapidly in a very short period of time

  10. Database Support • The strongest and most significant feature in PHP is its support for a wide range of databases • Writing a database-enabled web page is incredibly simple • The following databases are currently supported: Adabas D Ingres Oracle dBase InterBase Ovrimos Informix Empress FrontBase PostgreSQL ODBC FilePro mSQL Direct MS-SQL dbm Solid Hyperwave Sybase IBM DB2 MySQL Velocis Unix dbm

  11. Platforms • The power of PHP is that it is cross-platform and runs everywhere • It runs on many web-servers like: • Apache (built-in) • Microsoft IIS, others (as CGI binary) • It runs on: • Linux • Windows 95/98/NT • Windows 2000 • Solaris • HPUX and • all flavors of Unix • PHP is write once and deploy anywhere and everywhere

  12. What do I need? • The server has to have support for PHP activated and that all files ending in .php3 are handled by PHP • On most servers this is the default extension for PHP files, but ask your server administrator to be sure • If your server supports PHP then you don't need to do anything • Just create your .php3 files and put them in your web directory and the server will magically parse them for you • There is no need to compile anything nor do you need to install any extra tools • Think of these PHP-enabled files as simple HTML files with a whole new family of magical tags that let you do all sorts of things

  13. The Configuration File • The configuration file (called php.ini) is read when PHP starts up • For the server module versions of PHP, this happens only once when the web server is started • For the CGI version, it happens on every invocation • When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files and .htaccess files • You can view the settings of the configuration values in the output of phpinfo()

  14. Syntax • Much of its syntax is borrowed from C, Java and Perl with some unique PHP-specific features thrown in: • Control structures • if, else, for, do while, switch etc… • Types • Integers, strings, arrays, objects • Classes (OOP) and Functions • Syntax of PHP is similar to the basic syntax used by the C language • All the string and memory manipulation issues in C have been eliminated in PHP, but the basic syntax remains • PHP can be compiled and optimized to make it run even faster by using the Zend Optimizer • Zend optimizer is integrated with PHP in PHP version 4.0

  15. Instruction Separation • Instructions are separated the same as in C or perl - terminate each statement with a semicolon • The closing tag (?>) also implies the end of the statement, so the following are equivalent: • <?php • echo "This is a test"; • ?> • <?php echo "This is a test" ?>

  16. Hello World Example I <html> <head> <title>PHP Example I</title> </head> <body> <?php print “Hello World!"; ?> </body> </html>

  17. Another Hello World Example I • Create a file named hello.php3 and in it put the following lines: <html> <head> <title>PHP Example II</title> </head> <body> <?php echo "Hello World<P>"; ?> </body> </html> • The file does not need to be executable or special in any way • Think of it as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things

  18. Another Hello World Example II • This program is extremely simple and you really didn't need to use PHP to create a page like this • All it does is display: Hello World • If it didn't output anything, chances are that the server you are on does not have PHP enabled • Ask your administrator to enable it for you • The point of the example is to show the special PHP tag format • In this example <?php was used to indicate the start of a PHP tag • Then the PHP statement and left PHP mode was put by adding the closing tag, ?> • You may jump in and out of PHP mode in an HTML file like this all you want

  19. Architecture of a PHP-based DBM Application

  20. First Steps in the MySQL Usage • Let the name of the database is : mydata_dbuse mydata_db;create table student (name VARCHAR(30), supervisor VARCHAR(30), birthdateDATE);insert into student (name, supervisor, birthdate) values ("John Little","Andreas Big", "1979-10-20");insert into student (name, supervisor, birthdate) values ("Erica Knight","Andreas Big", "1980-11-22");select * from student where supervisor like "Big";update student set supervisor ="Edward Teller" where name="Erica Knight";commit;quit; • The home page of the mysql documentation:http://www.mysql.com/documentation/mysql/bychapter/index.html

  21. Checking the User Agent • E.g. we are going to check what sort of browser the person viewing the page is using • In order to do that we check the user agent string that the browser sends as part of its request • This information is stored in a variable • Variables always start with a dollar-sign in PHP • The variable we are interested in is $HTTP_USER_AGENT • To display this variable we can simply do: <?php echo $HTTP_USER_AGENT; ?> • For the browser that you are using right now to view this page, this displays: Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)

  22. Function Names • They are case insensitive • Even all of the built in PHP functions are case insensitive • function foo () { • return 'foo'; • } • function FOO () { • return 'FOO'; • } • // error: function foo() already declared

  23. Variables • Variables are case sensitive • $foo = 'foo'; • $FOO = 'FOO'; • echo "$foo:$FOO"; • // prints foo:FOO

  24. Other Variables • There are many other variables that are automatically set by your web server • You can get a complete list of them by creating a file that looks like this: • <?php phpinfo()?> • Then load up this file in your browser and you will see a page full of information about PHP along with a list of all the variables available to you

  25. Usage of the Variables • In PHP, a variable does not require formal declaration • It will automatically be declared when a value is assigned to it • Variables are prefixed by a dollar sign: ($VariableName) • In the following example, four variables are automatically declared by assigning a value to them: • <?php • $number = 5; • $string1 = "this is a string\n"; • $string2 = 'this is another "string"'; • $real = 37.2; • ?>

  26. Variables • Variables that have not been set are defined as NULL • If you use a variable that has not been set then PHP will treat the NULL like it is an empty string • But, don't depend on your variables being empty unless you have explicitly set them to be so • Users can pass arbitrary variable values into your script using the GET and POST HTTP methods

  27. Types • For the most part, types are hidden from the developer in PHP • 99% of the time you don't know or care about the type of a variable since PHP is so good at doing automatic conversions • There are times however when the type of your variables does become important

  28. Types of the PHP4 • array • boolean • double • integer • null • variables that are not set • object • resource • variables that represent resources such as file or database handles • string • unknown type

  29. Converting Types • PHP4 has introduced a concept of identity to the language • Two values are identical if they have the same content and the same type • Equality is based on two values having the same content after they have been converted to the same type • Equality (==) of two variables is not the same as identity (===) • You can explicitly cast and convert between types in PHP when necessary • The main time you need to think about doing this is when you are trying to do comparisons between variables of unknown or different types

  30. Example of Types • A good example of where types can get tricky is with database operations • Any return value from a database will always be represented in PHP as a string • The type in the database is irrelevant, immediately upon its return to PHP the value will be a string • Implicit conversion will treat this string as an integer, but it is still a string • There is one notable exception however • If you get a NULL return value from the database then PHP will create a variable of type NULL • ie.: effectively the variable is not set

  31. References • All variable assignments in PHP are done by copying values • Every time you assign a value to a variable you are creating a copy • Most of the time this doesn't really matter and in fact protects programmers from themselves since they can't destroy their precious data • Sometimes however copying by value can be a burden if your data is large and the copy isn't really necessary • To get around this problem PHP lets you create references to data • E.g., you can make $b reference the same data as $a with this command: • $b =& $a;

  32. Arrays I • PHP arrays are a cross between numbered arrays and associative arrays • This means that you can use the same syntax and functions to deal with either type of array, including arrays that are: • Indexed from 0 • Indexed by strings • Indexed with non-continuous numbers • Indexed by a mix of numbers and strings • In the next example, three literal arrays are declared as follows: 1.A numerically indexed array with indices running from 0 to 4 2.An associative array with string indices 3.A numerically indexed array, with indices running from 5 to 7

  33. Arrays II <?php $array1 = array(2, 3, 5, 7, 11); $array2 = array("one" => 1, "two" => 2, "three" => 3); $array3 = array(5 => "five", "six", "seven"); printf("7: %d, 1: %d, 'six': %s\n", $array1[3], $array2["one"], $array3[6]); ?> • From the above example, the indices in the array1 are implicit, while the indices in array2 are explicit • When specifically setting the index to a number N with the => operator, the next value has the index N+1 by default • Explicit indices do not have to be listed in sequential order • You can also mix numerical and string indexes, but it is not recommended

  34. Conditionals and Looping Constructs I • PHP includes if and elseif conditionals, as well as while and for loops, all with syntax similar to C • The example below introduces these four constructs: • <?php • // Conditionals • if ($a) { • print "a is true<BR>\n"; • } elseif ($b) { • print "b is true<BR>\n"; • } else { • print "neither a or b is true<BR>\n"; • }

  35. Conditionals and Looping Constructs II • // Loops • do { • $c = test_something(); • } while ($c); • while ($d) { • print "ok<BR>\n"; • $d = test_something(); • } • for ($i = 0; $i < 10; $i++) { • print "i=$i<BR>\n"; • } • ?>

  36. Architecture & FOR Loop • Build-in module in Apache web server • Example Apache httpd request PHP module Proxy module GIF module DB module html <html><body> <?php for($t=1;$t<=5;$t++) echo "<p>hello ".$t."times" ?> </body></html> hello 1 times hello 2 times hello 3 times hello 4 times hello 5 times

  37. Usage of Functions I • PHP parses one file at a time • Thus, you can use any function that has already been declared or is declared as part of the current file • So, this is valid: • foo(); • function foo () { • echo 'foo'; • }

  38. Usage of Functions II • If we move the foo() function into an include file the above ordering will no longer work regardless of whether we use include() or require() since PHP will attempt to run that step after the call to the function foo() • So, this will not work: • foo(); • include('./foo.inc');

  39. If Statement • You can put: • multiple PHP statements inside a PHP tag • create little blocks of code (that do more than just a single echo) • E.g., if we wanted to check for Internet Explorer we could do something like this: <?php if(strstr($HTTP_USER_AGENT,"MSIE")) { echo "You are using Internet Explorer<br>"; } ?>

  40. The strstr() Funcion Call I • strstr() is a function built into PHP which searches a string for another string • In this case we are looking for "MSIE" inside $HTTP_USER_AGENT • If the string is found the function returns true and if it isn't, it returns false • If it returns true the following statement is executed

  41. The strstr() Funcion Call II • We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block: <?php if(strstr($HTTP_USER_AGENT,"MSIE")) { ?> <CENTER><B>You are using Internet Explorer</B></CENTER> <? } else { ?> <CENTER><B>You are not using Internet Explorer</B></CENTER> <? } ?>

  42. The strstr() Funcion Call III • Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML • The important and powerful point to note here is that the logical flow of the script remain intact • Only one of the HTML blocks will end up getting sent to the viewer • Running this script right now results in: You are using Internet Explorer

  43. Dealing with Forms • One of the most powerful features of PHP is the way it handles HTML forms • The basic concept that is important to understand is that:any form element in a form will automatically result in a variable with the same name as the element being created on the target page • By default, any form entry creates a global PHP variable of the same name • One of PHP's oldest features is the ability to make HTML form and cookie data available directly to the programmer

  44. Web Application Features • In the followings, a user name is retrieved and assigned to a variable • The name is then printed by the sub-routine "submit.php": • <FORM METHOD="GET" ACTION="submit.php"> • What's your name? • <INPUT NAME="myname" SIZE=3> • </FORM> • submit.php • <?php • print "Hello, $myname!"; • ?> • From the above example, note that variables can also be referenced from within double quoted strings

  45. Simple Example for Forms • Assume you have a page with a form like this on it: <FORM ACTION="action.php3" METHOD="POST"> Your name: <INPUT TYPE=text NAME=name> You age: <INPUT TYPE=text NAME=age> <INPUT TYPE=submit> </FORM> • There is nothing special about this form • It is a straight HTML form with no special tags of any kind • When the user fills in this form and hits the submit button, the action.php3 page is called • In this file you would have something like this: Hi <?php echo $name?>. You are <?php echo $age?> years old • It should be obvious what this does • The $name and $age variables are automatically set for you by PHP

  46. Debugging • The classic debugging technique for PHP (and many other languages) is through echo statements • Just dump out information or the contents of your variables at various points in the script • There are some tricks that you can use to make debugging more effective: • log messages to file rather than printing so you don't affect HTTP headers • your HTML output use print_r or var_dump to examine the contents of any variable • There are some PHP debuggers coming onto the market that allow you to step through PHP code line by line

  47. Comments • PHP supports 'C', 'C++' and Unix shell-style comments • E.g.: • <?php • echo "This is a test"; // This is a one-line c++ style comment • /* This is a multi line comment • yet another line of comment */ • echo "This is yet another test"; • echo "One Final Test"; # This is shell-style style comment • ?>

  48. Usage of Comments • The "one-line" comment styles actually only comment to the end of the line or the current block of PHP code, whichever comes first • <h1>This is an <?# echo "simple";?> example.</h1> • <p>The header above will say 'This is an example'. • You should be careful not to nest 'C' style comments, which can happen when commenting out large blocks • <?php • /* • echo "This is a test"; /* This comment will cause a problem */ • */ • ?>

  49. Built-in Variables • PHP has a number of built-in variables that give you access to your Web server's CGI environment, form/cookie data and PHP internals. Here are some of the most useful variables: • PHP internal variables • The $GLOBALS and $PHP_SELF variables shown in the table below are specific to PHP: • Variable Name Description • $GLOBALS An associative array of all global variables • You can access it anywhere without declaring it • as a global first • $PHP_SELF This is the current script

  50. HTTP Request Variables • HTTP request variables are derived from their corresponding HTTP headers • E.g., $HTTP_USER_AGENT is derived from the User-Agent header, presented in the table below: • $HTTP_HOST • Host name in the browser's "location" field • $HTTP_USER_AGENT • User agent (browser) being used • $HTTP_REFERER • URL of the referring page

More Related