PHP: Hypertext
Preprocessor
What is PHP?
Open-source, server-side scripting language
Used to generate dynamic web-pages
PHP scripts reside between reserved PHP
tags
This allows the programmer to embed PHP
scripts within HTML pages
Interpreted language, scripts are parsed at
run-time rather than compiled beforehand
Why PHP?
PHP runs on different platforms
(Windows, Linux, Unix, etc.)
PHP is compatible with almost all servers
used today (Apache, IIS, etc.)
PHP is FREE.
PHP is easy to learn and runs efficiently
on the server side.
Working of PHP.
URL is typed in the browser.
The browser sends a request to the web server.
The web server then calls the PHP script on that page.
The PHP module executes the script, which then sends
out the result in the form of HTML back to the browser,
which can be seen on the screen.
What does PHP code look like?
Structurally similar to C/C++
Supports procedural and object-oriented
paradigm (to some degree)
All PHP statements end with a semi-colon
Each PHP script must be enclosed in the
reserved PHP tag.
PHP code structure
<html>
<body>
<?php
echo hi friends..";
?>
</body>
</html>
Variables in PHP
PHP variables must begin with a $ sign
Case-sensitive ($Foo != $foo != $fOo)
Global and locally-scoped variables
Global variables can be used anywhere
Local variables restricted to a function or
class
Certain variable names reserved by PHP
Form variables ($_POST, $_GET)
Server variables ($_SERVER)
PHP Control Structures
Control Structures: Are the structures within a language
that allow us to control the flow of execution through a
program or script.
Grouped into conditional (branching) structures (e.g.
if/else) and repetition structures (e.g. while loops).
Example if/else if/else statement:
if ($foo == 0) {
echo The variable foo is equal to 0;
}
else if (($foo > 0) && ($foo <= 5)) {
echo The variable foo is between 1 and 5;
}
else {
echo The variable foo is equal to .$foo;
}
PHP Function
Functions MUST be defined before then can be called
Function headers are of the format
Note that no return type is specified
Unlike variables, function names are not case sensitive
(foo() == Foo() == FoO())
<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
return $arg_2;
}
$result_1 = foo(12, 3);
echo $result_1;
echo foo(12, 3);
?>
// Store the function
// Outputs 36
// Outputs 36
PHP strings
Concatenation
Use a period/dot to join strings into one.
<?php
$string1=Hello;
$string2=PHP;
$string3=$string1 . . $string2;
Print $string3;
?>
Hello PHP
Date and Time
2009/4/1
Wednesday, April 1, 2009
$datedisplay=date(yyyy/m/d);
Print $datedisplay;
# If the date is April 1st, 2009
# It would display as 2009/4/1
$datedisplay=date(l, F m, Y);
Print $datedisplay;
# If the date is April 1st, 2009
# Wednesday, April 1, 2009
PHP Include
Include opendb.php;
Include closedb.php;
This inserts files; the code in files will be inserted into current
code. This will provide useful and protective means once you
connect to a database, as well as for other repeated
functions.
Include (footer.php);
The file footer.php might look like:
<hr SIZE=11 NOSHADE WIDTH=100%>
<i>Copyright 2008-2010 KIIT </i></font><br>
<i>ALL RIGHTS RESERVED</i></font><br>
<i>URL: http://www.kiit.edu</i></font><br>
PHP-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>";
else if ($_POST["cancel"])
echo "<h2>You clicked Cancel!</h2>";
?>
<form action="form.php" method="post">
<input type="submit" name="submit" value="Submit">
<input type="submit" name="cancel" value="Cancel">
</form>
PHP with MYSQL
Function: list all tables in your
database. Users can select one of
tables, and show all contents in this
table.
second.php
showtable.php
second.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.cs.edu:3306';
$dbuser = 'nruan';
$dbpass = *****************;
$dbname = $dbuser;
$table = 'account';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db($dbname))
die("Can't select database");
$result = mysql_query("SHOW TABLES");
if (!$result) {
die("Query to show fields from table failed");
}
$num_row = mysql_num_rows($result);
echo "<h1>Choose one table:<h1>";
echo "<form action=\"showtable.php\" method=\"POST\">";
echo "<select name=\"table\" size=\"1\" Font size=\"+2\">";
for($i=0; $i<$num_row; $i++) {
$tablename=mysql_fetch_row($result);
echo "<option value=\"{$tablename[0]}\" >{$tablename[0]}</option>";
}
echo "</select>";
echo "<div><input type=\"submit\" value=\"submit\"></div>";
echo "</form>";
mysql_free_result($result);
mysql_close($conn);
?>
</body></html>
showtable.php
<html><head>
<title>MySQL Table Viewer</title>
</head>
<body>
<?php
$dbhost = 'hercules.cs.edu:3306';
$dbuser = 'nruan';
$dbpass = **********;
$dbname = 'nruan';
$table = $_POST[table];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
if (!mysql_select_db($dbname))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) die("Query to show fields from table failed!" . mysql_error());
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++) {
$field = mysql_fetch_field($result);
echo "<td><b>{$field->name}</b></td>";
}
echo "</tr>\n";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
mysql_close($conn);
?>
</body></html>
Functions Covered
mysql_connect()
mysql_select_db()
include()
mysql_query()
mysql_num_rows()
mysql_fetch_array()
mysql_close()
PHP-Sessions
Sessions store their identifier in a cookie in the clients browser
Every page that uses session data must be proceeded by the
session_start() function
Session variables are then set and retrieved by accessing the
global $_SESSION[]
Save it as session.php
<?php
session_start();
if (!$_SESSION["count"])
$_SESSION["count"] = 0;
if ($_GET["count"] == "yes")
$_SESSION["count"] = $_SESSION["count"] + 1;
echo "<h1>".$_SESSION["count"]."</h1>";
?>
<a href="session.php?count=yes">Click here to count</a>
What is Ajax?
"Asynchronous JavaScript and XML"
New name for an old technique:
JavaScript + DHTML + XMLHttpRequest
In use since at least 1997
Already enabled in your Web server and browser
Use JavaScript asynchronously behind the scenes
to load additional data (typically XML) without
discarding and reloading the entire Web page.
21
Why use Ajax?
Client/Server Apps:
Dynamic data
Static forms, controls, code, etc.
Efficient, but not flexible
Traditional Web Apps:
Dynamic data
Dynamic forms, controls, code, etc.
Flexible, but inefficient, and noticeably slow
Ajax Apps:
Dynamic data
Static or dynamic forms, controls, code, etc.
Best of both worlds
22
How to use Ajax?
Simple!
Use the
XMLHttpRequest
Object
23
XMLHttpRequest Methods
open (method, URL, [async, username,
password])
Assigns destination URL, method, etc.
send (params)
Sends request including postable string or DOM object data
abort ()
Terminates current request
getAllResponseHeaders ()
Returns headers (name/value pairs) as a string
getResponseHeader (header)
Returns value of a given header
setRequestHeader (label,value)
Sets Request Headers before sending
1/25/2006
Intro to Ajax Fred Stluka
24
XMLHttpRequest Properties
onreadystatechange
Event handler (your code) that fires at each state change
readyState
0 = uninitialized
1 = loading
2 = loaded
3 = interactive (some data has been returned)
(broken in IE 6.0)
4 = complete
status
HTTP Status returned from server: 200-299 = OK
responseText
String version of data returned from server
responseXML
XML DOM document of data returned
statusText
Status text returned from server
25
Simple Example
var req = new XMLHttpRequest();
req.onreadystatechange = myHandler;
req.open("GET", "servlet", true);
req.send("p1=abc");
...
function myHandler() {
if (req.readyState == 4) {
doSomethingWith(req.responseXML);
}
else if (req.readyState == 3) {
showProgressIndicator();
}
}
26
AJAX-Implementation
BACK THEN
Click
Search
You got this :
These days you get this :