SlideShare a Scribd company logo
1 of 40
PHP/ MySQL
By : AJIT VIJAYEE YADAV
Contents
• What is PHP?
• History of PHP
• Operators
• Concatenation
• Escaping the character
• PHP control Structures
• Array
• Date display
• Function
• File Handling
• PHP Sessions
Connect to Mysql Databse
What is PHP?
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
History of PHP
PHP began in 1995 when Rasmus Lerdorf developed a

Perl/CGI script toolset he called the Personal Home Page
or PHP
PHP 2 released 1997 (PHP now stands for Hypertex
Processor). Lerdorf developed it further, using C instead
PHP3 released in 1998 (50,000 users)
PHP4 released in 2000 (3.6 million domains). Considered
debut of functional language and including Perl parsing,
with other major features
PHP5.0.0 released July 13, 2004 (113 libraries>1,000
functions with extensive object-oriented programming)
PHP5.0.5 released Sept. 6, 2005 for maintenance and bug
fixes
What is PHP (cont’d)
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 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
…
?>
PHP Overview
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.
PHP Overview (cont.)
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.
First PHP script
 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>
Comments 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 */
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)
Etc.
Variable usage
<?php
$foo = 25;
$bar = “Hello”;
$foo = ($foo * 7);
$bar = ($bar * 7);
?>

// Numerical variable
// String variable
// Multiplies foo by 7
// Invalid expression
Echo

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
Echo example
<?php
$foo = 25;
$bar = “Hello”;
echo
echo
echo
echo
echo
?>

$bar;
$foo,$bar;
“5x5=”,$foo;
“5x5=$foo”;
‘5x5=$foo’;

// Numerical variable
// String variable
//
//
//
//
//

Outputs
Outputs
Outputs
Outputs
Outputs

Hello
25Hello
5x5=25
5x5=25
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 “”)
Operators
Concatenation
Use a period to join strings into one.
<?php
$string1=“Hello”;
$string2=“PHP”;
$string3=$string1 . “ ” . $string2;
Print $string3;
?>

Hello PHP
Escaping 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”
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;
}
If ... Else...
If (condition)

{
Statements;
}
Else
{
Statement;

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

}

No THEN in PHP
While Loops
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.
Array
 An array is a special variable, which can hold more than one value

at a time.
 Create an Array in PHP
In PHP, the array() function is used to create an array:
E.g. – array();
<?php
$country=array(“IND",“AUS",“SA");
echo "I have travel in " . $country[0] . ", " . $country [1] . " and "
. $country [2] . ".";
?>
Array Types
In PHP, there are three types of arrays:
Numeric arrays - Arrays with numeric index
<?php
$name=array(0=>“Smith",“Lee”,"Joe”);
echo “My Friends are " . $name[0] .”,”. $name[1] ;
?>
Associative arrays - Arrays with named keys
<?php
$age=array(“Smith"=>"35",“Lee"=>"37","Joe"=>"43");
echo “Smith is " . $age[‘Smith'] . " years old.";
?>
Multidimensional arrays - Arrays containing one or more
arrays
Date Display
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
Month, Day & Date Format
Symbols
M
F
m
n
Day of Month
Day of Month
Day of Week
Day of Week

Jan
January
01
1
d
J
l
D

01
1
Monday
Mon
Functions
Functions MUST be defined before then can be called
Function headers are of the format
Note that no return type is specified
function functionName($arg_1, $arg_2, …, $arg_n)

Unlike variables, function names are not case sensitive (foo(…)

== Foo(…) == FoO(…))
Functions 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);
echo $result_1;
echo foo(12, 3);
?>

// Store the function
// Outputs 36
// Outputs 36
Include Files
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 WIDTH=“100%”>
<i>Copyright © by niit</i><br>
<i>ALL RIGHTS RESERVED</i><br>
<i>URL: http://www.niit.com</i><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>
File Handling
 The fopen() function is used to open files in PHP.
 The first parameter of this function contains the name of the file

to be opened and the second parameter specifies in which mode
the file should be opened:
 <html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
The file opened in one of the following modes:
<?php
$file = fopen("welcome.txt", "r") or exit("file can not be open!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br>";
  }
fclose($file);
?>
The feof() function checks if the "end-of-file" (EOF) has been

reached.
The fgets() function is used to read a single line from a file.
File Uploading
<form action="upload.php" method="post” enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
 Notice the following about the HTML form above:
 The enctype attribute of the <form> tag specifies which content-type to use

when submitting the form. "multipart/form-data" is used when a form
requires binary data, like the contents of a file, to be uploaded
 The type="file" attribute of the <input> tag specifies that the input should be
processed as a file. For example, when viewed in a browser, there will be a
browse-button next to the input field
To upload the file in server use this predefine function

move_uploaded_file($filename, $destination)
$filename – name of the temporary file name
$destination – in which directory you want to save file
WHYcreate a website Sessionsstore and display
PHP – that allows you to ?
Whenever you want to

information about a user, determine which user groups a person belongs to,
utilize permissions on your website or you just want to do something cool on
your site, PHP's Sessions are vital to each of these features.
Cookies are about 30% unreliable right now and it's getting worse every day.
More and more web browsers are starting to come with security and privacy
settings and people browsing the net these days are starting to frown upon
Cookies because they store information on their local computer that they do
not want stored there.
PHP has a great set of functions that can achieve the same results of
Cookies and more without storing information on the user's computer. PHP
Sessions store the information on the web server in a location that you chose
in special files. These files are connected to the user's web browser via the
server and a special ID called a "Session ID". This is nearly 99% flawless in
operation and it is virtually invisible to the user.
PHP - Sessions
•Sessions store their identifier in a cookie in the client’s 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>
Avoid Error PHP - Sessions
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
Destroy PHP - Sessions
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():
PHP
 To Connect with Mysql

$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username,
$password) ;

 To select Database

//select a database to work with
$selected = mysql_select_db("examples",$dbhandle) 
  or die("Could not select examples");
 Execute the SQL query and i-nsert  record
mysql_query(“insert into tbl_name values(‘val_1’,’val_2’)“);
 Close Mysql connection

mysql_close();

More Related Content

What's hot

What's hot (20)

Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
PHP slides
PHP slidesPHP slides
PHP slides
 
PHP
PHPPHP
PHP
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
Web technology html5 php_mysql
Web technology html5 php_mysqlWeb technology html5 php_mysql
Web technology html5 php_mysql
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting language
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomer
 
Php introduction
Php introductionPhp introduction
Php introduction
 
PHP
PHPPHP
PHP
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
 
Php1
Php1Php1
Php1
 
Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 
What Is Php
What Is PhpWhat Is Php
What Is Php
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
PHP Comprehensive Overview
PHP Comprehensive OverviewPHP Comprehensive Overview
PHP Comprehensive Overview
 

Similar to Php mysql

Similar to Php mysql (20)

Php advance
Php advancePhp advance
Php advance
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
slidesharenew1
slidesharenew1slidesharenew1
slidesharenew1
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
Materi Dasar PHP
Materi Dasar PHPMateri Dasar PHP
Materi Dasar PHP
 
Prersentation
PrersentationPrersentation
Prersentation
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
Basic php 5
Basic php 5Basic php 5
Basic php 5
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
 
Php notes
Php notesPhp notes
Php notes
 
Php
PhpPhp
Php
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php mysql training-in-mumbai
Php mysql training-in-mumbaiPhp mysql training-in-mumbai
Php mysql training-in-mumbai
 
Training on php by cyber security infotech (csi)
Training on  php by cyber security infotech (csi)Training on  php by cyber security infotech (csi)
Training on php by cyber security infotech (csi)
 
Php basics
Php basicsPhp basics
Php basics
 

More from Ajit Yadav

More from Ajit Yadav (6)

Cloud Computing Documentation Report
Cloud Computing Documentation ReportCloud Computing Documentation Report
Cloud Computing Documentation Report
 
Remote Admittance
Remote AdmittanceRemote Admittance
Remote Admittance
 
Frame Relay
Frame RelayFrame Relay
Frame Relay
 
Phishing
PhishingPhishing
Phishing
 
INTRODUCTION TO JAVA APPLICATION
INTRODUCTION TO JAVA APPLICATIONINTRODUCTION TO JAVA APPLICATION
INTRODUCTION TO JAVA APPLICATION
 
Cloud computing
Cloud computingCloud computing
Cloud computing
 

Recently uploaded

會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
中 央社
 

Recently uploaded (20)

Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
Climbers and Creepers used in landscaping
Climbers and Creepers used in landscapingClimbers and Creepers used in landscaping
Climbers and Creepers used in landscaping
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 

Php mysql

  • 1. PHP/ MySQL By : AJIT VIJAYEE YADAV
  • 2. Contents • What is PHP? • History of PHP • Operators • Concatenation • Escaping the character • PHP control Structures • Array • Date display • Function • File Handling • PHP Sessions Connect to Mysql Databse
  • 3. What is PHP? 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
  • 4. History of PHP PHP began in 1995 when Rasmus Lerdorf developed a Perl/CGI script toolset he called the Personal Home Page or PHP PHP 2 released 1997 (PHP now stands for Hypertex Processor). Lerdorf developed it further, using C instead PHP3 released in 1998 (50,000 users) PHP4 released in 2000 (3.6 million domains). Considered debut of functional language and including Perl parsing, with other major features PHP5.0.0 released July 13, 2004 (113 libraries>1,000 functions with extensive object-oriented programming) PHP5.0.5 released Sept. 6, 2005 for maintenance and bug fixes
  • 5. What is PHP (cont’d) 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
  • 6. 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 … ?>
  • 7. PHP Overview 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.
  • 8. PHP Overview (cont.) 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.
  • 9. First PHP script  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>
  • 10. Comments 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 */
  • 11. 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) Etc.
  • 12. Variable usage <?php $foo = 25; $bar = “Hello”; $foo = ($foo * 7); $bar = ($bar * 7); ?> // Numerical variable // String variable // Multiplies foo by 7 // Invalid expression
  • 13. Echo 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
  • 14. Echo example <?php $foo = 25; $bar = “Hello”; echo echo echo echo echo ?> $bar; $foo,$bar; “5x5=”,$foo; “5x5=$foo”; ‘5x5=$foo’; // Numerical variable // String variable // // // // // Outputs Outputs Outputs Outputs Outputs Hello 25Hello 5x5=25 5x5=25 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 “”)
  • 16.
  • 17.
  • 18. Concatenation Use a period to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1 . “ ” . $string2; Print $string3; ?> Hello PHP
  • 19. Escaping 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”
  • 20. 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; }
  • 21. If ... Else... If (condition) { Statements; } Else { Statement; <?php If($user==“John”) { Print “Hello John.”; } Else { Print “You are not John.”; } ?> } No THEN in PHP
  • 22. While Loops 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.
  • 23. Array  An array is a special variable, which can hold more than one value at a time.  Create an Array in PHP In PHP, the array() function is used to create an array: E.g. – array(); <?php $country=array(“IND",“AUS",“SA"); echo "I have travel in " . $country[0] . ", " . $country [1] . " and " . $country [2] . "."; ?>
  • 24. Array Types In PHP, there are three types of arrays: Numeric arrays - Arrays with numeric index <?php $name=array(0=>“Smith",“Lee”,"Joe”); echo “My Friends are " . $name[0] .”,”. $name[1] ; ?> Associative arrays - Arrays with named keys <?php $age=array(“Smith"=>"35",“Lee"=>"37","Joe"=>"43"); echo “Smith is " . $age[‘Smith'] . " years old."; ?> Multidimensional arrays - Arrays containing one or more arrays
  • 25. Date Display 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
  • 26. Month, Day & Date Format Symbols M F m n Day of Month Day of Month Day of Week Day of Week Jan January 01 1 d J l D 01 1 Monday Mon
  • 27. Functions Functions MUST be defined before then can be called Function headers are of the format Note that no return type is specified function functionName($arg_1, $arg_2, …, $arg_n) Unlike variables, function names are not case sensitive (foo(…) == Foo(…) == FoO(…))
  • 28. Functions 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); echo $result_1; echo foo(12, 3); ?> // Store the function // Outputs 36 // Outputs 36
  • 29. Include Files 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 WIDTH=“100%”> <i>Copyright © by niit</i><br> <i>ALL RIGHTS RESERVED</i><br> <i>URL: http://www.niit.com</i><br>
  • 30. 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>
  • 31. File Handling  The fopen() function is used to open files in PHP.  The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:  <html> <body> <?php $file=fopen("welcome.txt","r"); ?> </body> </html>
  • 32. The file opened in one of the following modes:
  • 33. <?php $file = fopen("welcome.txt", "r") or exit("file can not be open!"); //Output a line of the file until the end is reached while(!feof($file))   {   echo fgets($file). "<br>";   } fclose($file); ?> The feof() function checks if the "end-of-file" (EOF) has been reached. The fgets() function is used to read a single line from a file.
  • 34. File Uploading <form action="upload.php" method="post” enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file"><br> <input type="submit" name="submit" value="Submit"> </form>  Notice the following about the HTML form above:  The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded  The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field
  • 35. To upload the file in server use this predefine function move_uploaded_file($filename, $destination) $filename – name of the temporary file name $destination – in which directory you want to save file
  • 36. WHYcreate a website Sessionsstore and display PHP – that allows you to ? Whenever you want to information about a user, determine which user groups a person belongs to, utilize permissions on your website or you just want to do something cool on your site, PHP's Sessions are vital to each of these features. Cookies are about 30% unreliable right now and it's getting worse every day. More and more web browsers are starting to come with security and privacy settings and people browsing the net these days are starting to frown upon Cookies because they store information on their local computer that they do not want stored there. PHP has a great set of functions that can achieve the same results of Cookies and more without storing information on the user's computer. PHP Sessions store the information on the web server in a location that you chose in special files. These files are connected to the user's web browser via the server and a special ID called a "Session ID". This is nearly 99% flawless in operation and it is virtually invisible to the user.
  • 37. PHP - Sessions •Sessions store their identifier in a cookie in the client’s 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>
  • 38. Avoid Error PHP - Sessions 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
  • 39. Destroy PHP - Sessions 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():
  • 40. PHP  To Connect with Mysql $username = "your_name"; $password = "your_password"; $hostname = "localhost"; //connection to the database $dbhandle = mysql_connect($hostname, $username, $password) ;  To select Database //select a database to work with $selected = mysql_select_db("examples",$dbhandle)    or die("Could not select examples");  Execute the SQL query and i-nsert  record mysql_query(“insert into tbl_name values(‘val_1’,’val_2’)“);  Close Mysql connection mysql_close();