2. IntroductionIntroduction
PHP is stands for ’Hypertext Preprocessor ’ used for making
dynamic web pages and interactive web pages.
PHP is server side scripting language intented to help web
developers build dynamic web pages.
PHP scripts are executed on the server.
PHP supports many databases (MySql ,Oracle,PostgreSQL,Generic
ODBC etc).
PHP was created by Rasmus Lerdrof in 1995.
PHP originally stood for ”PERSONAL HOME PAGE”
PHP is an Open Source software.
PHP is free to download and use.
3. PHP FilesPHP Files
PHP files can contain text, HTML Tags and scripts.
PHP files are returned to the browser as plain HTML
PHP files have a file extension of ”.php”.
EXECUTION OF PHP PAGE
4. “PHP is an HTML-embedded scripting language. Much of its syntax is
borrowed from C,Java & Perl with a couple of unique PHP-specific
features thrown in .The goal of the language is to allow web developers
to write dynamically generated pages quickly. ”
5. Brief History of PHPBrief History of PHP
PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf
in 1994. It was initially developed for HTTP usage logging and server-
side form generation in Unix
PHP 2 (1995) transformed the language into a Server-side embedded
scripting language. Added database support, file uploads, variables,
arrays, recursive functions, conditionals, iteration, regular
expressions, etc.
PHP 3 (1998) added support for ODBC data sources, multiple
platform support, email protocols (SNMP,IMAP), and new parser
written by Zeev Suraski and Andi Gutmans .
PHP 4 (2000) became an independent component of the web server
for added efficiency. The parser was renamed the Zend Engine. Many
security features were added.
6.
PHP 5 (2004) adds Zend Engine II with object oriented programming,
robust XML support using the libxml2 library, SOAP extension for
interoperability with Web Services, SQLite has been bundled with
PHP
7. PHP FeaturesPHP Features
Open source / Free software.
Cross Platform to develop, to deploy, and to use.
Power,Robust, Scalable.
Web development specific.
Can be Object Oriented.
It is faster to code and faster to execute.
Large, active developer community.
20 million websites
Support for PHP is free.
Great documentation in many language www.php.net/docs.php
8. Why use PHP ?Why use PHP ?
1. Easy to use
Code is embedded into HTML. The PHP code is enclosed in special
start and end tags that allow you to jump into and out.
<html>
<head>
<title>Example</title>
</head>
10. 2.Cross Platform
Run on almost any web server on several Operating Systems.
One of the strongest features is the wide range of supported databases.
• Web Server : Apache, Microsoft IIS , Netscape Enterprise Server.
• Operating Systems : Unix (Solaris,Linux),Mac OS, Window
NT/98/2000/XP/2003.
• Supported Databases : dBase,Empress,FilePro (read only),
Hyperware, IBM DB2,InformixIngress,Frontbase,MySql,ODBC,Oracle
etc.
11. 3. Cost Benefits
PHP is free. Open Source code means that the entire PHP community
will contribute towards bug fixes. There are several add-on technologies
(libraries) for PHP that are also free.
12. DatatypesDatatypes
PHP stores whole numbers in a platform-dependent range.
This range is typically that of 32-bit signed integers. Unsigned
integers are converted to signed values in certain situations.
Arrays can contain elements of any type that handle in PHP .
Including resources, objects, and even other arrays.
PHP also supports strings, which can be used with single quotes,
double quotes, or heredoc syntax.
13. What does PHP code look like?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
…
?>
14. Comments in PHPComments in PHP
Standard C, C++, and shell comment symbols
// C++ and Java-style comment
# Shell-style comments
/* C-style comments
These can span multiple lines
*/
15. Variables in PHPVariables 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)
-- Etc.
17. EchoEcho
The PHP command ‘echo’ is used to output the parameters passed
to it
--The typical usage for this is to send data to the client’s web-browser
Syntax
-- void echo (string arg1 [, string argn...])
-- In practice, arguments are not passed in parentheses since echo
is a language construct rather than an actual function
18. Echo exampleEcho example
PHP scripts are stored as human-readable source code and are compiled
on-the-fly to an internal format that can be executed by the PHP engine.
Code optimizers aim to reduce the runtime of the compiled code by reducing
its size and making other changes that can reduce the execution time with the
goal of improving performance.
<?php
$foo = 25; // Numerical
variable
$bar = “Hello”; // String variable
echo $bar; // Outputs Hello
echo $foo,$bar; // Outputs 25Hello
echo “5x5=”,$foo; // Outputs
5x5=25
echo “5x5=$foo”; // Outputs 5x5=25
echo ‘5x5=$foo’; // Outputs 5x5=$foo
?>
19. Arithmetic OperationsArithmetic Operations
$a - $b // subtraction
$a * $b // multiplication
$a / $b // division
$a += 5 // $a = $a+5 Also works for *= and /=
<?php
$a=15;
$b=30;
$total=$a+$b;
Print $total;
Print “<p><h1>$total</h1>”;
// total is 45
?>
21. Escaping the CharacterEscaping the Character
If the string has a set of double quotation marks that must remain
visible, use the [backslash] before the quotation marks to ignore and
display them.
<?php
$heading=“”Computer Science””;
Print $heading;
?>
“Computer Science”
22. PHP Control StructuresPHP 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;
}
23. If ... Else...If ... Else...
If (condition)
{
Statements;
}
Else
{
Statement;
}
<?php
If($user==“John”)
{
Print “Hello John.”;
}
Else
{
Print “You are not John.”;
}
?>
No THEN in PHP
25. Date DisplayDate Display
$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
2009/4/1
Wednesday, April 1, 2009
26. Month, Day & Date Format SymbolsMonth, Day & Date Format Symbols
M Jan
F January
m 01
n 1
Day of Month d 01
Day of Month J 1
Day of Week l Monday
Day of Week D Mon
27. FunctionsFunctions
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(…))
function functionName($arg_1, $arg_2, …, $arg_n)
28. Functions exampleFunctions example
<?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); //
Store the function
echo $result_1; // Outputs 36
echo foo(12, 3); // Outputs 36
?>
30. PHP FormsPHP Forms
Access to the HTTP POST and GET data is simple in PHPAccess to the HTTP POST and GET data is simple in PHP
The global variables $_POST[] and $_GET[] contain the request dataThe 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>
31. What is a cookie ?What is a cookie ?
A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests for a page
with a browser, it will send the cookie too. With PHP, you can
both create and retrieve cookie values.
32. How To Create a Cookie?How To Create a Cookie?
The setcookie() function is used to create cookies.
Note: The setcookie() function must appear BEFORE the
<html> tag.
setcookie(name, [value], [expire], [path], [domain], [secure]);
This sets a cookie named "uname" - that expires after ten hours.
<?php setcookie("uname", $name, time()+36000); ?>
<html> <body> …
33. How To Retrieve a Cookie Value?How To Retrieve a Cookie Value?
To access a cookie you just refer to the cookie name as a
variable or use $_COOKIE array
Tip: Use the isset() function to find out if a cookie has been
set.
<html> <body>
<?php
if (isset($uname))
echo "Welcome " . $uname . "!<br />";
else
echo "You are not logged in!<br />"; ?>
</body> </html>
34. How To Delete a Cookie ?How To Delete a Cookie ?
Cookies must be deleted with the same parameters as they
were set with. If the value argument is an empty string (""),
and all other arguments match a previous call to setcookie,
then the cookie with the specified name will be deleted from
the remote client.
35. What is a Session?
The session support allows you to register arbitrary numbers
of variables to be preserved across requests.
A visitor accessing your web site is assigned an unique id,
the so-called session id. This is either stored in a cookie on
the user side or is propagated in the URL.
Tip: Use the isset() function to find out if a cookie has been
set.
36. How to Create a Session ?
The session_start() function is used to create cookies.
<?php
session_start();
?>
37. How to Retrieve a Session Value ?
Register Session variable
-- session_register('var1','var2',...); // will also create a session
-- PS:Session variable will be created on using even if you will not
register it!
Use it
<?php
session_start();
if (!isset($_SESSION['count']))
$_SESSION['count'] = 0;
else
$_SESSION['count']++;
?>
38. Storing Session Data
The $_SESSION superglobal array can be
used to store any session data.
e.g.
$_SESSION[‘name’] = $name;
$_SESSION[‘age’] = $age;
39. Reading Session Data
Data is simply read back from the $_SESSION
superglobal array.
e.g.
$_SESSION[‘name’] = $name;
$_SESSION[‘age’] = $age;
40. How to Delete a Session Value ?
session_unregister(´varname´);
How to destroy a session:
session_destroy()
41. PHP DATABASE INTERACTION IN FIVE STEPS
1) Create the Connection
2) Select the Database
3) Perform Database Query
4) Use Returned Data (if any)
5) Close Connection
42. 1. Connect with MySQL RDBMS
mysql_connect($hostName, $userName, $password) or
die("Unable to connect to host $hostName");
43. 2. Connect with database
mysql_select_db($dbName) or die("Unable to select
database $dbName");
44. 3. Perform Database Query
Queries: Nearly all table interaction and management is done through
queries:
Basic information searches
$query = "SELECT FirstName, LastName, DOB, Gender FROM
Patients WHERE Gender = '$Gender‘ ORDER BY FirstName
DESC";
$Patients = mysql_query($SQL);
Editing, adding, and deleting records and tables
$query = "INSERT INTO Patients (FirstName, LastName)
VALUES('$firstName', '$lastName')";
$Patients = mysql_query($SQL);
45. 4. Process Results (if any)
• Many functions exist to work with database results
mysql_num_rows()
– Number of rows in the result set
– Useful for iterating over result set
mysql_fetch_array()
– Returns a result row as an array
– Can be associative or numeric or both (default)
– $row = mysql_fetch_array($query);
– $row[‘column name’] :: value comes from database row with specified
column name
46. Process Results Loop
• Easy loop for processing results:
$result = mysql_query($query;
$num_rows = mysql_num_rows($query);
for ($i=0; $i<$num_rows; $i++) {
$row = mysql_fetch_array($result);
// take action on database results here
}
47. 5. Closing Database Connection
• mysql_close()
– Closes database connection
– Only works for connections opened with mysql_connect()
– Connections opened with mysql_pconnect() ignore this call
– Often not necessary to call this, as connections created by
mysql_connect are closed at the end of the script anyway