SlideShare une entreprise Scribd logo
1  sur  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();

Contenu connexe

Tendances

Tendances (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
 

Similaire à Php mysql

Similaire à 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
 

Plus de Ajit Yadav

Plus de 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
 

Dernier

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Dernier (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 

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();