SlideShare a Scribd company logo
PPHHPP//MMyySSQQLL 
DDeevveellooppmmeennttTTuuttoorriiaall 
Introduction to Database
WWhhaatt iiss PPHHPP?? 
 PHP == ‘Hypertext Preprocessor’ 
 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
WWhhaatt iiss PPHHPP ((ccoonntt’’dd)) 
 Interpreted language, scripts are parsed at run-time 
rather than compiled beforehand 
 Executed on the server-side 
 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
What ddooeess PPHHPP ccooddee llooookk lliikkee?? 
 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 
… 
?>
CCoommmmeennttss iinn PPHHPP 
 Standard C, C++, and shell comment symbols 
// C++ and Java-style comment 
# Shell-style comments 
/* C-style comments 
These can span multiple lines */
VVaarriiaabbllee uussaaggee 
<?php 
$foo = 25; // Numerical variable 
$bar = “Hello”; // String variable 
$foo = ($foo * 7); // Multiplies foo by 7 
$bar = ($bar * 7); // Invalid expression 
?>
EEcchhoo 
 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
EEcchhoo eexxaammppllee 
<?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 
?> 
 Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25 
 Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP 
 This is true for both variables and character escape-sequences (such as 
“n” or “”)
AArriitthhmmeettiicc OOppeerraattiioonnss 
<?php 
$a=15; 
$b=30; 
$total=$a+$b; 
Print $total; 
Print “<p><h1>$total</h1>”; 
// total is 45 
?> 
 $a - $b // subtraction 
 $a * $b // multiplication 
 $a / $b // division 
 $a += 5 // $a = $a+5 Also works for *= and /=
CCoonnccaatteennaattiioonn 
 Use a period to join strings into one. 
<?php 
$string1=“Hello”; 
$string2=“PHP”; 
$string3=$string1 . “ ” . 
$string2; 
Print $string3; 
?> 
Hello PHP
EEssccaappiinngg tthhee CChhaarraacctteerr 
 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”
PPHHPP CCoonnttrrooll SSttrruuccttuurreess 
 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; 
}
IIff ...... EEllssee...... 
 If (condition) 
{ 
Statements; 
} 
Else 
{ 
Statement; 
} 
<?php 
If($user==“John”) 
{ 
Print “Hello John.”; 
} 
Else 
{ 
Print “You are not John.”; 
} 
?> 
No THEN in PHP
WWhhiillee LLooooppss 
 While (condition) 
{ 
Statements; 
} 
<?php 
$count=0; 
While($count<3) 
{ 
Print “hello PHP. ”; 
$count += 1; 
// $count = $count + 1; 
// or 
// $count++; 
?> 
hello PHP. hello PHP. hello PHP.
DDaattee DDiissppllaayy 
$datedisplay=date(“yyyy/m/d”); 
Print $datedisplay; 
# If the date is April 1st, 2009 
# It would display as 2009/4/1 
2009/4/1 
$datedisplay=date(“l, F m, Y”); 
Print $datedisplay; 
# If the date is April 1st, 2009 
# Wednesday, April 1, 2009 
Wednesday, April 1, 
2009
MMoonntthh,, DDaayy && DDaattee FFoorrmmaatt 
SSyymmbboollss 
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
FFuunnccttiioonnss 
 Functions MUST be defined before then can be 
called 
 Function headers are of the format 
function functionName($arg_1, $arg_2, …, $arg_n) 
 Note that no return type is specified 
 Unlike variables, function names are not case 
sensitive (foo(…) == Foo(…) == FoO(…))
FFuunnccttiioonnss eexxaammppllee 
<?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 
?>
IInncclluuddee FFiilleess 
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 KSU </i></font><br> 
<i>ALL RIGHTS RESERVED</i></font><br> 
<i>URL: http://www.kent.edu</i></font><br>
PPHHPP -- FFoorrmmss 
•AAcccceessss ttoo tthhee HHTTTTPP PPOOSSTT aanndd GGEETT ddaattaa iiss ssiimmppllee iinn PPHHPP 
•TThhee gglloobbaall vvaarriiaabblleess $$__PPOOSSTT[[]] aanndd $$__GGEETT[[]] ccoonnttaaiinn tthhee 
rreeqquueesstt ddaattaa 
<?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>
WWHHYY PPHHPP –– SSeessssiioonnss ?? 
WWhheenneevveerr yyoouu wwaanntt ttoo ccrreeaattee aa wweebbssiittee tthhaatt aalllloowwss yyoouu ttoo ssttoorree aanndd ddiissppllaayy 
iinnffoorrmmaattiioonn aabboouutt aa uusseerr,, ddeetteerrmmiinnee wwhhiicchh uusseerr ggrroouuppss aa ppeerrssoonn bbeelloonnggss ttoo,, 
uuttiilliizzee ppeerrmmiissssiioonnss oonn yyoouurr wweebbssiittee oorr yyoouu jjuusstt wwaanntt ttoo ddoo ssoommeetthhiinngg ccooooll oonn 
yyoouurr ssiittee,, PPHHPP''ss SSeessssiioonnss aarree vviittaall ttoo eeaacchh ooff tthheessee ffeeaattuurreess.. 
CCooookkiieess aarree aabboouutt 3300%% uunnrreelliiaabbllee rriigghhtt nnooww aanndd iitt''ss ggeettttiinngg wwoorrssee eevveerryy ddaayy.. 
MMoorree aanndd mmoorree wweebb bbrroowwsseerrss aarree ssttaarrttiinngg ttoo ccoommee wwiitthh sseeccuurriittyy aanndd pprriivvaaccyy 
sseettttiinnggss aanndd ppeeooppllee bbrroowwssiinngg tthhee nneett tthheessee ddaayyss aarree ssttaarrttiinngg ttoo ffrroowwnn uuppoonn 
CCooookkiieess bbeeccaauussee tthheeyy ssttoorree iinnffoorrmmaattiioonn oonn tthheeiirr llooccaall ccoommppuutteerr tthhaatt tthheeyy ddoo 
nnoott wwaanntt ssttoorreedd tthheerree.. 
PPHHPP hhaass aa ggrreeaatt sseett ooff ffuunnccttiioonnss tthhaatt ccaann aacchhiieevvee tthhee ssaammee rreessuullttss ooff 
CCooookkiieess aanndd mmoorree wwiitthhoouutt ssttoorriinngg iinnffoorrmmaattiioonn oonn tthhee uusseerr''ss ccoommppuutteerr.. PPHHPP 
SSeessssiioonnss ssttoorree tthhee iinnffoorrmmaattiioonn oonn tthhee wweebb sseerrvveerr iinn aa llooccaattiioonn tthhaatt yyoouu cchhoossee 
iinn ssppeecciiaall ffiilleess.. TThheessee ffiilleess aarree ccoonnnneecctteedd ttoo tthhee uusseerr''ss wweebb bbrroowwsseerr vviiaa tthhee 
sseerrvveerr aanndd aa ssppeecciiaall IIDD ccaalllleedd aa ""SSeessssiioonn IIDD"".. TThhiiss iiss nneeaarrllyy 9999%% ffllaawwlleessss iinn 
ooppeerraattiioonn aanndd iitt iiss vviirrttuuaallllyy iinnvviissiibbllee ttoo tthhee uusseerr..
PPHHPP -- SSeessssiioonnss •SSeessssiioonnss ssttoorree tthheeiirr iiddeennttiiffiieerr iinn aa ccooookkiiee iinn tthhee cclliieenntt’’ss bbrroowwsseerr 
•EEvveerryy ppaaggee tthhaatt uusseess sseessssiioonn ddaattaa mmuusstt bbee pprroocceeeeddeedd bbyy tthhee 
sseessssiioonn__ssttaarrtt(()) ffuunnccttiioonn 
•SSeessssiioonn vvaarriiaabblleess aarree tthheenn sseett aanndd rreettrriieevveedd bbyy aacccceessssiinngg tthhee gglloobbaall 
$$__SSEESSSSIIOONN[[]] 
•SSaavvee iitt aass sseessssiioonn..pphhpp 
<<??pphhpp 
sseessssiioonn__ssttaarrtt(());; 
iiff ((!!$$__SSEESSSSIIOONN[[""ccoouunntt""]])) 
$$__SSEESSSSIIOONN[[""ccoouunntt""]] == 00;; 
iiff (($$__GGEETT[[""ccoouunntt""]] ==== ""yyeess"")) 
$$__SSEESSSSIIOONN[[""ccoouunntt""]] == $$__SSEESSSSIIOONN[[""ccoouunntt""]] ++ 11;; 
eecchhoo ""<<hh11>>""..$$__SSEESSSSIIOONN[[""ccoouunntt""]]..""<<//hh11>>"";; 
??>> 
<<aa hhrreeff==""sseessssiioonn..pphhpp??ccoouunntt==yyeess"">>CClliicckk hheerree ttoo ccoouunntt<<//aa>>
AAvvooiidd EErrrroorr PPHHPP -- SSeessssiioonnss 
PHP Example: <?php 
echo "Look at this nasty error below:<br />"; 
session_start(); 
?> 
Error! 
Warning: Cannot send session cookie - headers already sent 
by (output started at 
session_header_error/session_error.php:2) in 
session_header_error/session_error.php on line 3 
Warning: Cannot send session cache limiter - headers 
already sent (output started at 
session_header_error/session_error.php:2) in 
session_header_error/session_error.php on line 3 
PHP Example: <?php 
session_start(); 
echo "Look at this nasty error below:"; 
?> 
Correct
DDeessttrrooyy PPHHPP -- SSeessssiioonnss 
Destroying a Session 
why it is necessary to destroy a session when the session will get 
destroyed when the user closes their browser. Well, imagine that you 
had a session registered called "access_granted" and you were using 
that to determine if the user was logged into your site based upon a 
username and password. Anytime you have a login feature, to make 
the users feel better, you should have a logout feature as well. That's 
where this cool function called session_destroy() comes in handy. 
session_destroy() will completely demolish your session (no, the 
computer won't blow up or self destruct) but it just deletes the session 
files and clears any trace of that session. 
NOTE: If you are using the $_SESSION superglobal array, you must 
clear the array values first, then run session_destroy. 
Here's how we use session_destroy():
DDeessttrrooyy PPHHPP -- SSeessssiioonnss 
<?php 
// start the session 
session_start(); 
header("Cache-control: private"); //IE 6 Fix 
$_SESSION = array(); 
session_destroy(); 
echo "<strong>Step 5 - Destroy This Session </strong><br />"; 
if($_SESSION['name']){ 
echo "The session is still active"; 
} else { 
echo "Ok, the session is no longer active! <br />"; 
echo "<a href="page1.php"><< Go Back Step 1</a>"; 
} 
?>
PPHHPP OOvveerrvviieeww 
 Easy learning 
 Syntax Perl- and C-like syntax. Relatively 
easy to learn. 
 Large function library 
 Embedded directly into HTML 
 Interpreted, no need to compile 
 Open Source server-side scripting language 
designed specifically for the web.
PPHHPP OOvveerrvviieeww ((ccoonntt..)) 
 Conceived in 1994, now used on +10 million 
web sites. 
 Outputs not only HTML but can output XML, 
images (JPG & PNG), PDF files and even 
Flash movies all generated on the fly. Can write 
these files to the file system. 
 Supports a wide-range of databases 
(20+ODBC). 
 PHP also has support for talking to other 
services using protocols such as LDAP, IMAP, 
SNMP, NNTP, POP3, HTTP.
FFiirrsstt PPHHPP ssccrriipptt 
 Save as sample.php: 
<!– sample.php --> 
<html><body> 
<strong>Hello World!</strong><br /> 
<?php 
echo “<h2>Hello, World</h2>”; ?> 
<?php 
$myvar = "Hello World"; 
echo $myvar; 
?> 
</body></html>
Example –– sshhooww ddaattaa iinn tthhee ttaabblleess 
 Function: list all tables in your database. 
Users can select one of tables, and show all 
contents in this table. 
 second.php 
 showtable.php
sseeccoonndd..pphhpp 
<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.kent.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");
sseeccoonndd..pphhpp ((ccoonntt..)) 
$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>
sshhoowwttaabbllee..pphhpp 
<html><head> 
<title>MySQL Table Viewer</title> 
</head> 
<body> 
<?php 
$dbhost = 'hercules.cs.kent.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());
sshhoowwttaabbllee..pphhpp ((ccoonntt..)) 
$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>
FFuunnccttiioonnss CCoovveerreedd 
 mysql_connect() mysql_select_db() 
 include() 
 mysql_query() mysql_num_rows() 
 mysql_fetch_array()mysql_close()

More Related Content

PPT
Php mysql
PPT
Synapseindia reviews sharing intro on php
PDF
07 Introduction to PHP #burningkeyboards
PDF
Code Generation in PHP - PHPConf 2015
PDF
OSDC.TW - Gutscript for PHP haters
PPT
slidesharenew1
PPT
My cool new Slideshow!
PDF
Functional Structures in PHP
Php mysql
Synapseindia reviews sharing intro on php
07 Introduction to PHP #burningkeyboards
Code Generation in PHP - PHPConf 2015
OSDC.TW - Gutscript for PHP haters
slidesharenew1
My cool new Slideshow!
Functional Structures in PHP

What's hot (20)

PPT
Mocking Dependencies in PHPUnit
PPT
Open Source Package PHP & MySQL
PPTX
Php string function
PDF
8時間耐久CakePHP2 勉強会
PDF
Learning Perl 6 (NPW 2007)
PDF
ODP
PHP Tips for certification - OdW13
PDF
Learning Perl 6
PPT
Php Lecture Notes
PPT
Php Crash Course
PDF
[PL] Jak nie zostać "programistą" PHP?
PPT
Php Calling Operators
PDF
Php unit the-mostunknownparts
PDF
Zend Certification Preparation Tutorial
PPSX
Php and MySQL
PDF
The most exciting features of PHP 7.1
PPT
Class 2 - Introduction to PHP
PPT
PHP variables
PDF
What's New in Perl? v5.10 - v5.16
ODP
PHP Web Programming
Mocking Dependencies in PHPUnit
Open Source Package PHP & MySQL
Php string function
8時間耐久CakePHP2 勉強会
Learning Perl 6 (NPW 2007)
PHP Tips for certification - OdW13
Learning Perl 6
Php Lecture Notes
Php Crash Course
[PL] Jak nie zostać "programistą" PHP?
Php Calling Operators
Php unit the-mostunknownparts
Zend Certification Preparation Tutorial
Php and MySQL
The most exciting features of PHP 7.1
Class 2 - Introduction to PHP
PHP variables
What's New in Perl? v5.10 - v5.16
PHP Web Programming
Ad

Viewers also liked (12)

PDF
Adepus news no. 1
DOC
akshat resume nov2015
PPT
Synapseindia mobile application architectures
ODP
Synapse India Reviews
ODP
Synaseindia Apps vs. the web
PPT
Synapseindia android app sharing app inventor for android
PPTX
Tarea seminario 2 historia
PPT
Synapse india reviews sharing chapter 23 – asp.net-part2
PPTX
Puppies for adoption in florida
PPTX
Tarea seminario 2 Historia odontologia
PPTX
Internal messenger
PDF
Footing design
Adepus news no. 1
akshat resume nov2015
Synapseindia mobile application architectures
Synapse India Reviews
Synaseindia Apps vs. the web
Synapseindia android app sharing app inventor for android
Tarea seminario 2 historia
Synapse india reviews sharing chapter 23 – asp.net-part2
Puppies for adoption in florida
Tarea seminario 2 Historia odontologia
Internal messenger
Footing design
Ad

Similar to Synapseindia php development tutorial (20)

PPT
Prersentation
PPT
Php Tutorial
PDF
PHP Programming and its Applications workshop
PPT
Php mysql
PPT
Php with my sql
PPT
PHP - Introduction to PHP Fundamentals
PPT
Introducation to php for beginners
PPT
Learning of Php and My SQL Tutorial | For Beginners
PPT
Php Tutorial | Introduction Demo | Basics
PPTX
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
PPT
Synapseindia reviews sharing intro on php
PPT
Synapseindia reviews on array php
PPT
PPT
Synapse india reviews on php website development
PPTX
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
PPT
Php mysql
Prersentation
Php Tutorial
PHP Programming and its Applications workshop
Php mysql
Php with my sql
PHP - Introduction to PHP Fundamentals
Introducation to php for beginners
Learning of Php and My SQL Tutorial | For Beginners
Php Tutorial | Introduction Demo | Basics
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
Synapseindia reviews sharing intro on php
Synapseindia reviews on array php
Synapse india reviews on php website development
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql

More from Synapseindiappsdevelopment (20)

PPTX
Synapse india elance top in demand in it skills
PPT
SynapseIndia dotnet web development architecture module
PPT
SynapseIndia dotnet module development part 1
PPT
SynapseIndia dotnet framework library
PPT
SynapseIndia dotnet development platform overview
PPT
SynapseIndia dotnet development framework
PPT
SynapseIndia dotnet web applications development
PPT
SynapseIndia dotnet website security development
PPT
SynapseIndia mobile build apps management
PPT
SynapseIndia mobile apps deployment framework internal architecture
PPT
SynapseIndia java and .net development
PPT
SynapseIndia dotnet development panel control
PPT
SynapseIndia dotnet development ajax client library
PPT
SynapseIndia php web development
PPT
SynapseIndia mobile apps architecture
PPT
SynapseIndia mobile apps deployment framework architecture
PPT
SynapseIndia mobile apps
PPT
SynapseIndia dotnet development
PPT
SynapseIndia dotnet client library Development
PPT
SynapseIndia creating asp controls programatically development
Synapse india elance top in demand in it skills
SynapseIndia dotnet web development architecture module
SynapseIndia dotnet module development part 1
SynapseIndia dotnet framework library
SynapseIndia dotnet development platform overview
SynapseIndia dotnet development framework
SynapseIndia dotnet web applications development
SynapseIndia dotnet website security development
SynapseIndia mobile build apps management
SynapseIndia mobile apps deployment framework internal architecture
SynapseIndia java and .net development
SynapseIndia dotnet development panel control
SynapseIndia dotnet development ajax client library
SynapseIndia php web development
SynapseIndia mobile apps architecture
SynapseIndia mobile apps deployment framework architecture
SynapseIndia mobile apps
SynapseIndia dotnet development
SynapseIndia dotnet client library Development
SynapseIndia creating asp controls programatically development

Synapseindia php development tutorial

  • 2. WWhhaatt iiss PPHHPP??  PHP == ‘Hypertext Preprocessor’  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
  • 3. WWhhaatt iiss PPHHPP ((ccoonntt’’dd))  Interpreted language, scripts are parsed at run-time rather than compiled beforehand  Executed on the server-side  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
  • 4. What ddooeess PPHHPP ccooddee llooookk lliikkee??  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 … ?>
  • 5. CCoommmmeennttss iinn PPHHPP  Standard C, C++, and shell comment symbols // C++ and Java-style comment # Shell-style comments /* C-style comments These can span multiple lines */
  • 6. VVaarriiaabbllee uussaaggee <?php $foo = 25; // Numerical variable $bar = “Hello”; // String variable $foo = ($foo * 7); // Multiplies foo by 7 $bar = ($bar * 7); // Invalid expression ?>
  • 7. EEcchhoo  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
  • 8. EEcchhoo eexxaammppllee <?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 ?>  Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25  Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP  This is true for both variables and character escape-sequences (such as “n” or “”)
  • 9. AArriitthhmmeettiicc OOppeerraattiioonnss <?php $a=15; $b=30; $total=$a+$b; Print $total; Print “<p><h1>$total</h1>”; // total is 45 ?>  $a - $b // subtraction  $a * $b // multiplication  $a / $b // division  $a += 5 // $a = $a+5 Also works for *= and /=
  • 10. CCoonnccaatteennaattiioonn  Use a period to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1 . “ ” . $string2; Print $string3; ?> Hello PHP
  • 11. EEssccaappiinngg tthhee CChhaarraacctteerr  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”
  • 12. PPHHPP CCoonnttrrooll SSttrruuccttuurreess  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; }
  • 13. IIff ...... EEllssee......  If (condition) { Statements; } Else { Statement; } <?php If($user==“John”) { Print “Hello John.”; } Else { Print “You are not John.”; } ?> No THEN in PHP
  • 14. WWhhiillee LLooooppss  While (condition) { Statements; } <?php $count=0; While($count<3) { Print “hello PHP. ”; $count += 1; // $count = $count + 1; // or // $count++; ?> hello PHP. hello PHP. hello PHP.
  • 15. DDaattee DDiissppllaayy $datedisplay=date(“yyyy/m/d”); Print $datedisplay; # If the date is April 1st, 2009 # It would display as 2009/4/1 2009/4/1 $datedisplay=date(“l, F m, Y”); Print $datedisplay; # If the date is April 1st, 2009 # Wednesday, April 1, 2009 Wednesday, April 1, 2009
  • 16. MMoonntthh,, DDaayy && DDaattee FFoorrmmaatt SSyymmbboollss 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
  • 17. FFuunnccttiioonnss  Functions MUST be defined before then can be called  Function headers are of the format function functionName($arg_1, $arg_2, …, $arg_n)  Note that no return type is specified  Unlike variables, function names are not case sensitive (foo(…) == Foo(…) == FoO(…))
  • 18. FFuunnccttiioonnss eexxaammppllee <?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 ?>
  • 19. IInncclluuddee FFiilleess 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 KSU </i></font><br> <i>ALL RIGHTS RESERVED</i></font><br> <i>URL: http://www.kent.edu</i></font><br>
  • 20. PPHHPP -- FFoorrmmss •AAcccceessss ttoo tthhee HHTTTTPP PPOOSSTT aanndd GGEETT ddaattaa iiss ssiimmppllee iinn PPHHPP •TThhee gglloobbaall vvaarriiaabblleess $$__PPOOSSTT[[]] aanndd $$__GGEETT[[]] ccoonnttaaiinn tthhee rreeqquueesstt ddaattaa <?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>
  • 21. WWHHYY PPHHPP –– SSeessssiioonnss ?? WWhheenneevveerr yyoouu wwaanntt ttoo ccrreeaattee aa wweebbssiittee tthhaatt aalllloowwss yyoouu ttoo ssttoorree aanndd ddiissppllaayy iinnffoorrmmaattiioonn aabboouutt aa uusseerr,, ddeetteerrmmiinnee wwhhiicchh uusseerr ggrroouuppss aa ppeerrssoonn bbeelloonnggss ttoo,, uuttiilliizzee ppeerrmmiissssiioonnss oonn yyoouurr wweebbssiittee oorr yyoouu jjuusstt wwaanntt ttoo ddoo ssoommeetthhiinngg ccooooll oonn yyoouurr ssiittee,, PPHHPP''ss SSeessssiioonnss aarree vviittaall ttoo eeaacchh ooff tthheessee ffeeaattuurreess.. CCooookkiieess aarree aabboouutt 3300%% uunnrreelliiaabbllee rriigghhtt nnooww aanndd iitt''ss ggeettttiinngg wwoorrssee eevveerryy ddaayy.. MMoorree aanndd mmoorree wweebb bbrroowwsseerrss aarree ssttaarrttiinngg ttoo ccoommee wwiitthh sseeccuurriittyy aanndd pprriivvaaccyy sseettttiinnggss aanndd ppeeooppllee bbrroowwssiinngg tthhee nneett tthheessee ddaayyss aarree ssttaarrttiinngg ttoo ffrroowwnn uuppoonn CCooookkiieess bbeeccaauussee tthheeyy ssttoorree iinnffoorrmmaattiioonn oonn tthheeiirr llooccaall ccoommppuutteerr tthhaatt tthheeyy ddoo nnoott wwaanntt ssttoorreedd tthheerree.. PPHHPP hhaass aa ggrreeaatt sseett ooff ffuunnccttiioonnss tthhaatt ccaann aacchhiieevvee tthhee ssaammee rreessuullttss ooff CCooookkiieess aanndd mmoorree wwiitthhoouutt ssttoorriinngg iinnffoorrmmaattiioonn oonn tthhee uusseerr''ss ccoommppuutteerr.. PPHHPP SSeessssiioonnss ssttoorree tthhee iinnffoorrmmaattiioonn oonn tthhee wweebb sseerrvveerr iinn aa llooccaattiioonn tthhaatt yyoouu cchhoossee iinn ssppeecciiaall ffiilleess.. TThheessee ffiilleess aarree ccoonnnneecctteedd ttoo tthhee uusseerr''ss wweebb bbrroowwsseerr vviiaa tthhee sseerrvveerr aanndd aa ssppeecciiaall IIDD ccaalllleedd aa ""SSeessssiioonn IIDD"".. TThhiiss iiss nneeaarrllyy 9999%% ffllaawwlleessss iinn ooppeerraattiioonn aanndd iitt iiss vviirrttuuaallllyy iinnvviissiibbllee ttoo tthhee uusseerr..
  • 22. PPHHPP -- SSeessssiioonnss •SSeessssiioonnss ssttoorree tthheeiirr iiddeennttiiffiieerr iinn aa ccooookkiiee iinn tthhee cclliieenntt’’ss bbrroowwsseerr •EEvveerryy ppaaggee tthhaatt uusseess sseessssiioonn ddaattaa mmuusstt bbee pprroocceeeeddeedd bbyy tthhee sseessssiioonn__ssttaarrtt(()) ffuunnccttiioonn •SSeessssiioonn vvaarriiaabblleess aarree tthheenn sseett aanndd rreettrriieevveedd bbyy aacccceessssiinngg tthhee gglloobbaall $$__SSEESSSSIIOONN[[]] •SSaavvee iitt aass sseessssiioonn..pphhpp <<??pphhpp sseessssiioonn__ssttaarrtt(());; iiff ((!!$$__SSEESSSSIIOONN[[""ccoouunntt""]])) $$__SSEESSSSIIOONN[[""ccoouunntt""]] == 00;; iiff (($$__GGEETT[[""ccoouunntt""]] ==== ""yyeess"")) $$__SSEESSSSIIOONN[[""ccoouunntt""]] == $$__SSEESSSSIIOONN[[""ccoouunntt""]] ++ 11;; eecchhoo ""<<hh11>>""..$$__SSEESSSSIIOONN[[""ccoouunntt""]]..""<<//hh11>>"";; ??>> <<aa hhrreeff==""sseessssiioonn..pphhpp??ccoouunntt==yyeess"">>CClliicckk hheerree ttoo ccoouunntt<<//aa>>
  • 23. AAvvooiidd EErrrroorr PPHHPP -- SSeessssiioonnss PHP Example: <?php echo "Look at this nasty error below:<br />"; session_start(); ?> Error! Warning: Cannot send session cookie - headers already sent by (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3 Warning: Cannot send session cache limiter - headers already sent (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3 PHP Example: <?php session_start(); echo "Look at this nasty error below:"; ?> Correct
  • 24. DDeessttrrooyy PPHHPP -- SSeessssiioonnss Destroying a Session why it is necessary to destroy a session when the session will get destroyed when the user closes their browser. Well, imagine that you had a session registered called "access_granted" and you were using that to determine if the user was logged into your site based upon a username and password. Anytime you have a login feature, to make the users feel better, you should have a logout feature as well. That's where this cool function called session_destroy() comes in handy. session_destroy() will completely demolish your session (no, the computer won't blow up or self destruct) but it just deletes the session files and clears any trace of that session. NOTE: If you are using the $_SESSION superglobal array, you must clear the array values first, then run session_destroy. Here's how we use session_destroy():
  • 25. DDeessttrrooyy PPHHPP -- SSeessssiioonnss <?php // start the session session_start(); header("Cache-control: private"); //IE 6 Fix $_SESSION = array(); session_destroy(); echo "<strong>Step 5 - Destroy This Session </strong><br />"; if($_SESSION['name']){ echo "The session is still active"; } else { echo "Ok, the session is no longer active! <br />"; echo "<a href="page1.php"><< Go Back Step 1</a>"; } ?>
  • 26. PPHHPP OOvveerrvviieeww  Easy learning  Syntax Perl- and C-like syntax. Relatively easy to learn.  Large function library  Embedded directly into HTML  Interpreted, no need to compile  Open Source server-side scripting language designed specifically for the web.
  • 27. PPHHPP OOvveerrvviieeww ((ccoonntt..))  Conceived in 1994, now used on +10 million web sites.  Outputs not only HTML but can output XML, images (JPG & PNG), PDF files and even Flash movies all generated on the fly. Can write these files to the file system.  Supports a wide-range of databases (20+ODBC).  PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP.
  • 28. FFiirrsstt PPHHPP ssccrriipptt  Save as sample.php: <!– sample.php --> <html><body> <strong>Hello World!</strong><br /> <?php echo “<h2>Hello, World</h2>”; ?> <?php $myvar = "Hello World"; echo $myvar; ?> </body></html>
  • 29. Example –– sshhooww ddaattaa iinn tthhee ttaabblleess  Function: list all tables in your database. Users can select one of tables, and show all contents in this table.  second.php  showtable.php
  • 30. sseeccoonndd..pphhpp <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.kent.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");
  • 31. sseeccoonndd..pphhpp ((ccoonntt..)) $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>
  • 32. sshhoowwttaabbllee..pphhpp <html><head> <title>MySQL Table Viewer</title> </head> <body> <?php $dbhost = 'hercules.cs.kent.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());
  • 33. sshhoowwttaabbllee..pphhpp ((ccoonntt..)) $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>
  • 34. FFuunnccttiioonnss CCoovveerreedd  mysql_connect() mysql_select_db()  include()  mysql_query() mysql_num_rows()  mysql_fetch_array()mysql_close()