SlideShare a Scribd company logo
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
Php mysql
Php mysql
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 (20)

PDF
Introduction to php
Anjan Banda
 
PPTX
PHP slides
Farzad Wadia
 
PPT
PHP
sometech
 
PPT
Control Structures In Php 2
Digital Insights - Digital Marketing Agency
 
PPS
Web technology html5 php_mysql
durai arasan
 
PDF
Php a dynamic web scripting language
Elmer Concepcion Jr.
 
PPT
Php Tutorial
SHARANBAJWA
 
PPTX
Php by shivitomer
Shivi Tomer
 
PDF
Php introduction
krishnapriya Tadepalli
 
PPTX
PHP
Steve Fort
 
PPT
Php Lecture Notes
Santhiya Grace
 
PDF
Web Development Course: PHP lecture 1
Gheyath M. Othman
 
PPTX
Php1
Shamik Tiwari
 
PDF
Web Development Course: PHP lecture 3
Gheyath M. Othman
 
PPTX
Php.ppt
Nidhi mishra
 
PPTX
Basic of PHP
Nisa Soomro
 
PPT
Basic PHP
Todd Barber
 
PPT
What Is Php
AVC
 
PPT
Php i basic chapter 3
Muhamad Al Imran
 
PPSX
PHP Comprehensive Overview
Mohamed Loey
 
Introduction to php
Anjan Banda
 
PHP slides
Farzad Wadia
 
Control Structures In Php 2
Digital Insights - Digital Marketing Agency
 
Web technology html5 php_mysql
durai arasan
 
Php a dynamic web scripting language
Elmer Concepcion Jr.
 
Php Tutorial
SHARANBAJWA
 
Php by shivitomer
Shivi Tomer
 
Php introduction
krishnapriya Tadepalli
 
Php Lecture Notes
Santhiya Grace
 
Web Development Course: PHP lecture 1
Gheyath M. Othman
 
Web Development Course: PHP lecture 3
Gheyath M. Othman
 
Php.ppt
Nidhi mishra
 
Basic of PHP
Nisa Soomro
 
Basic PHP
Todd Barber
 
What Is Php
AVC
 
Php i basic chapter 3
Muhamad Al Imran
 
PHP Comprehensive Overview
Mohamed Loey
 

Similar to Php mysql (20)

PPT
Php mysql
Alebachew Zewdu
 
PPT
slidesharenew1
truptitasol
 
PPT
My cool new Slideshow!
omprakash_bagrao_prdxn
 
PPT
PHP - Introduction to PHP Fundamentals
Vibrant Technologies & Computers
 
PPT
Training on php by cyber security infotech (csi)
Cyber Security Infotech Pvt. Ltd.
 
PPTX
Day1
IRWAA LLC
 
PPTX
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
PPT
Php introduction with history of php
pooja bhandari
 
PPT
php fundamental
zalatarunk
 
PPT
php
Ramki Kv
 
PPT
Prersentation
Ashwin Deora
 
PPT
05php
Shahid Usman
 
PPT
Php classes in mumbai
Vibrant Technologies & Computers
 
PPT
Learning of Php and My SQL Tutorial | For Beginners
Ratnesh Pandey
 
PPT
Php Tutorial | Introduction Demo | Basics
Shubham Kumar Singh
 
PPT
05php
sahilshamrma08
 
PPT
Php mysql
Abu Bakar
 
Php mysql
Alebachew Zewdu
 
slidesharenew1
truptitasol
 
My cool new Slideshow!
omprakash_bagrao_prdxn
 
PHP - Introduction to PHP Fundamentals
Vibrant Technologies & Computers
 
Training on php by cyber security infotech (csi)
Cyber Security Infotech Pvt. Ltd.
 
Day1
IRWAA LLC
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
Php introduction with history of php
pooja bhandari
 
php fundamental
zalatarunk
 
Prersentation
Ashwin Deora
 
Php classes in mumbai
Vibrant Technologies & Computers
 
Learning of Php and My SQL Tutorial | For Beginners
Ratnesh Pandey
 
Php Tutorial | Introduction Demo | Basics
Shubham Kumar Singh
 
Php mysql
Abu Bakar
 
Ad

More from Ajit Yadav (6)

DOC
Cloud Computing Documentation Report
Ajit Yadav
 
PPT
Remote Admittance
Ajit Yadav
 
PPT
Frame Relay
Ajit Yadav
 
PPTX
Phishing
Ajit Yadav
 
PPT
INTRODUCTION TO JAVA APPLICATION
Ajit Yadav
 
PPTX
Cloud computing
Ajit Yadav
 
Cloud Computing Documentation Report
Ajit Yadav
 
Remote Admittance
Ajit Yadav
 
Frame Relay
Ajit Yadav
 
Phishing
Ajit Yadav
 
INTRODUCTION TO JAVA APPLICATION
Ajit Yadav
 
Cloud computing
Ajit Yadav
 
Ad

Recently uploaded (20)

PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PDF
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
infertility, types,causes, impact, and management
Ritu480198
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Difference between write and update in odoo 18
Celine George
 
Introduction presentation of the patentbutler tool
MIPLM
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 

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 “”)
  • 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();