You are on page 1of 32

Unit IV


What is PHP ?
 Stands for Hypertext Preprocessor
General-purpose, server-side(executed on the server-side)
scripting language used to design dynamic, interactive
Web sites.
– dynamic: a page whose contents can change automatically
each time the page is viewed
– interactive: a site that responds to input from its visitors
 Free, open source
 PHP can interact with MySQL databases
 Purpose: to process information and produce
hypertext (HTML) as a result.

What is PHP?
-- PHP scripts can be embedded within HTML pages
-- an interpreted language — PHP script is processed by
the PHP engine each time it’s run
-- process of running a PHP script on a Web server
1. A visitor requests a Web page by clicking a link, or typing
the page’s URL. The visitor can also send data to the Web
server either using a form or via AJAX (Asynchronous
JavaScript And XML).
2. Web server recognizes that the requested URL is a PHP
script, and instructs the PHP engine to process and run
the script.
3. The script runs, and when it’s finished it usually sends an
HTML page to the Web browser

and PHP code  PHP files have extension ". What is PHP (cont’d)  Interpreted language. scripts are parsed at run-time rather than compiled beforehand  Source-code not visible by client  ‘View Source’ in browsers does not display the PHP code  Various built-in functions allow for fast development  Compatible with many popular databases  PHP files can contain text. CSS. JavaScript.php" . HTML.

What Can PHP Do? -. and even Flash movies. read. open. delete.add.send and receive cookies -.used to control user-access -.generate dynamic page content -. write.encrypt data PHP not only output HTML but also images. and close files on the server -. delete.create. . modify data in your database -. PDF files.collect form data -.


just to use the mysql-functions. IIS) -.php.Fast Load Time – PHP results in faster site loading speeds. that means it is easy to start using databases. no additional drivers needs to be and easy to setup and create a website using PHP -. PHP codes runs much faster. -. -.Integrated database support: It has built-in support for the most popular databases like MySQL.Server compatibility: compatible with almost all servers used today (Apache.Platform flexibility : runs on various platforms -.Easy to use: PHP doesn't need to be compiled. . Why PHP? -. so it's just to write the script and then upload it to the server and then update the (www.

such as WordPress. so you need not pay for them. most tools associated with the program are open source software. It is available through a hosting provider at no additional cost. Why PHP? -. There is no problem to find hosting with PHP pre- installed. -.Cheap hosting: Since PHP has existed for long time and works good on both Linux and Windows.Less Expensive Software – In working with PHP. and many webservers have support for it. .

PHP code syntax  Structurally similar to C/C++  A PHP script can be placed anywhere in the document  Supports procedural and OO pattern  All PHP statements end with a semi-colon  Each PHP script must be enclosed in the reserved PHP tag Example <?php <?php … echo "Hello World!". ?> ?> .

// Numerical variable $bar = “Hello”. // Outputs Hello echo $n.. Echo (print)  ‘echo’ is used to output the parameters passed to it Syntax: echo (string arg1 [. // Outputs 25Hello echo “5x5=”.$bar.])  arguments are not passed in () since echo is a language construct rather than an actual function <?php $n = 25.. // Outputs 5x5=25 echo ‘5x5=$n’.$n. // Outputs 5x5=$n ?>  Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP . // Outputs 5x5=25 echo “5x5=$n”. string arg n. // String variable echo $bar.

. // This is a single-line comment # Shell comment which is also a single-line comment /* This is a multiple-lines comment */ Note: PHP keywords and user defined functions are not case sensitive. Comments in PHP A comment in PHP code is a line that is not read/executed as part of the program.

$_GET) Server variables ($_SERVER) e. $txt = "Hello world!". $x = 5. Variables in PHP  PHP variables must begin with a “$” sign  Case-sensitive ($Foo != $foo != $fOo)  Certain variable names reserved by PHP Form variables ($_POST.g.  Loosely typed language: no need to specify datatype PHP Variables Scope .

. Data types in PHP A variable’s data type determines what operations can be carried out on the data. as well as the amount of memory needed to hold the data.

$b // subtraction  $a * $b // multiplication  $a / $b // division  $a += 5 // $a = $a+5 . Print $total.Arithmetic Operations <?php $a=15. $total=$a+$b. Print “<p><h1>$total</h1>”. ?>  $a . $b=30.

Print $string3. ?> Hello PHP .“ ”.$string2. $string3=$string1. <?php $string1=“Hello”. $string2=“PHP”.Concatenation  Use a period to join strings into one.

?> “Computer Science” . Print $heading. use the \ [backslash] before the quotation marks to ignore and display them. <?php $heading=“\”Computer Science\””.Escaping the Character  If the string has a set of double quotation marks that must remain visible.

} else if (($n > 0) && ($n <= 5)) { echo ‘The variable n is between 1 and 5’. PHP Control Structures  allow us to control the flow of execution of program  Grouped into conditional/branching structures (if/else) and repetition structures (while loops).$n. } else { echo ‘The variable n is equal to ‘. Example: if ($n == 0) { echo ‘The variable n is equal to 0’. } .

. } Statements.. } . If . Else } { Print “You are not John. Else } ?> { Statement. <?php  If (condition) If($user==“John”) { { Print “Hello John.. Else..”.”.

While($count<3) { { Statements. hello PHP. hello PHP. } } ?> hello PHP.While Loops <?php  While (condition) $count=0. . $count += 1. Print “hello PHP. ”.

$arg_2. $arg_n)  Unlike variables. …. Functions  Functions MUST be defined before they can be called  Function headers are of the format function functionName($arg_1. function names are not case sensitive .

$arg_2) { $arg_2 = $arg_1 * $arg_2. 3). Functions example <?php function foo($arg_1. // Outputs 36 ?> . // Store the function echo $result. 3). } $result = foo(12. // Outputs 36 echo foo(12. return $arg_2.

Termination PHP Instruction Termination -. exit.g. -. Exit statuses should be in the range 0 to 254.Each statement. . void exit ([ string $status ] ) or void exit ( int $status ) -. exit("unable to open file”). If status is an integer.Parameters: status If status is a string. PHP script termination -. -. this function prints the status just before exiting. or instruction.exit — Output a message and terminate the current script -.Each statement made in PHP needs to indicate end of the statement so that each instruction can be carried out without mix-up. -. e. The status 0 is used to terminate the program successfully. that value will be used as the exit status and not printed. is terminated with a semicolon. the exit status 255 is reserved by PHP and shall not be used.exit is a language construct and it can be called without parentheses if no status is passed.Terminates execution of the script.

The code in files will be inserted into current code. as well as for other repeated functions.kent. Include “closedb.Include Files Include “opendb. This will provide useful and protective means once you connect to a database.php might look like: <hr size=11 width=“100%”> <i>Copyright © 2008-2010 KSU </i><br> <i>ALL RIGHTS RESERVED</i><br> <i>URL: http://www.php”). Include (“footer. The file footer.php”. This inserts</i><br> .php”.

else if ($_POST["cancel"]) echo "<h2>You clicked Cancel!</h2>". ?> <form action="form.Forms •Access to the HTTP POST and GET data is simple in PHP •The global variables $_POST[] and $_GET[] contain the request data <?php if ($_POST["submit"]) echo "<h2>You clicked Submit!</h2>". PHP .php" method="post"> <input type="submit" name="submit" value="Submit"> <input type="submit" name="cancel" value="Cancel"> </form> .

First PHP script  Save as sample.php --> <html><body> <strong>Hello World!</strong><br> <?php echo “<h2>Hello. ?> </body></html> . echo $myvar.php: <!– sample. ?> <?php $myvar = "Hello World". World</h2>”.

php  showtable.Example – show data in the tables  Function: list all tables in your database.php . and show all contents in this table.  second. Users can select one of tables.

$table = 'account'. if (!$conn) { die('Could not connect: ' .cs.php <html><head><title>MySQL Table Viewer</title></head><body> <?php // change the value of $dbuser and $dbpass to your username and password $dbhost = 'hercules. $dbpass = ‘*****************’.second. mysql_error()). $dbpass).kent. $dbname = $dbuser. $conn = mysql_connect($dbhost. $dbuser. $dbuser = 'nruan'. } if (!mysql_select_db($dbname)) die("Can't select database"). .edu:3306'.

php (cont. echo "<div><input type=\"submit\" value=\"submit\"></div>".) $result = mysql_query("SHOW TABLES"). for($i=0. echo "<select name=\"table\" size=\"1\" Font size=\"+2\">". echo "<h1>Choose one table:<h1>". ?> </body></html> . echo "</form>". mysql_close($conn).second. $i++) { $tablename=mysql_fetch_row($result). if (!$result) { die("Query to show fields from table failed"). mysql_free_result($result). echo "<form action=\"showtable. } echo "</select>". $i<$num_row. } $num_row = mysql_num_rows($result). echo "<option value=\"{$tablename[0]}\" >{$tablename[0]}</option>".php\" method=\"POST\">".

kent. $dbname = 'nruan'. $dbuser = 'nruan'. $dbuser.showtable.cs. $dbpass = ‘**********’. $dbpass). if (!$result) die("Query to show fields from table failed!" . $table = $_POST[“table”]. . if (!$conn) die('Could not connect: ' .edu:3306'. mysql_error()). mysql_error()).php <html><head> <title>MySQL Table Viewer</title> </head> <body> <?php $dbhost = 'hercules. if (!mysql_select_db($dbname)) die("Can't select database"). $conn = mysql_connect($dbhost. $result = mysql_query("SELECT * FROM {$table}").

echo "</tr>\n". ) puts every element // of $row to $cell variable foreach($row as $cell) echo "<td>$cell</td>".. echo "<h1>Table: {$table}</h1>"..showtable. $i<$fields_num. } echo "</tr>\n". echo "<td><b>{$field->name}</b></td>". echo "<table border='1'><tr>". mysql_close($conn). while($row = mysql_fetch_row($result)) { echo "<tr>". } mysql_free_result($result). ?> </body></html> .) $fields_num = mysql_num_fields($result). $i++) { $field = mysql_fetch_field($result). // $row is array.php (cont. foreach( . // printing table headers for($i=0..

Functions Covered  mysql_connect() mysql_select_db()  include()  mysql_query() mysql_num_rows()  mysql_fetch_array() mysql_close() .

php home page http://www.phpmyadmin.asp  etc.php installation manual    php forums .net <  <-. text book http://geocities.php download page http://www.academic.php <-.PHP resources like sample  <-.htm   http://www.php. PHP References  http://www.