SlideShare ist ein Scribd-Unternehmen logo
1 von 67
INTRODUCTION
•PHP is an Interpreted High-level Programming
Language
•PHP stands for Personal Home Page (1995 by Rasmus
lerdorf)
•After PHP version 3 : Hypertext Preprocessor.
•PHP is a server side scripting language that is
embedded in HTML. It is used to manage dynamic
content, databases, session tracking, even build entire
ecommerce sites.
• It is integrated with a number of popular
databases, including MySQL, PostgreSQL, Oracle,
Sybase, Informix, and Microsoft SQL Server.
• PHP supports a large number of major protocols
such as POP3, IMAP, and LDAP. PHP4 added
support for Java and distributed object
architectures (COM and CORBA), making n-tier
development a possibility for the first time.
• PHP Syntax is C-Like.
Common uses of PHP
• PHP can handle forms, i.e. gather data from files,
save data to a file, thru email you can send data,
return data to the user.
• You add, delete, modify elements within your
database thru PHP.
• Access cookies variables and set cookies.
• Using PHP, you can restrict users to access some
pages of your website.
• It can encrypt data.
Characteristics of PHP
• Performance
• Portability
• Simplicity
• Open Source
• Community Support
• Third-Party Application Support
• Security
• Flexibility
• Familiarity
"Hello World" Script in PHP
<html>
<head>
<title>Hello World</title>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
All PHP code must be included inside one of the three
special markup tags
<?php PHP code goes here ?>
<? PHP code goes here ?>
<script language="php"> PHP code goes here </script>
SYNTAX OVERVIEW
• Escaping to PHP
The PHP parsing engine needs a way to differentiate
PHP code from other elements in the page.
The mechanism for doing so is known as 'escaping to
PHP.'
There are four ways to do this:
Canonical PHP tags: <?php...?>
Short-open (SGML-style) tags: <?...?>
ASP-style tags :<%...%>
HTML script tags : <script language="PHP">...</script>
• Commenting PHP Code
Single-line comment
<?
# This is a comment, and
# This is the second line of the comment
// This is a comment too. Each style comments only print "An
example with single line comments";
?>
Multi-lines comments
<?
/* This is a comment with multiline
Author : Parameswar
Purpose: Multiline Comments Demo
Subject: PHP
*/
print "An example with multi line comments";
?>
PHP is whitespace insensitive
$four = 2 + 2; // single spaces
$four <tab>=<tab>2<tab>+<tab>2 ; // spaces and tabs
$four =
2+
2; // multiple lines
PHP is case sensitive
<html>
<body>
<? $capital = 67;
print("Variable capital is $capital<br>");
print("Variable CaPiTaL is $CaPiTaL<br>");
?>
</body>
</html>
Statements or expressions terminated by semicolons
VARIABLE TYPES
To store the information we use a variable.
Here are the most important things to know about
variables in PHP.
1. All variables are denoted with a dollar sign ($).
2. The value of a variable is the value of its most
recent assignment.
3. Variables are assigned with “= “operator
4. Variables in PHP do not have intrinsic types
5. Variables used before they are assigned have
default values.
6. PHP automatically converting types from one to
another when necessary.
PHP has eight data type
Integers
Doubles
Booleans simple Types
NULL
Strings
Arrays
Objects compound Types
Resources : are special variables that hold references
to resources external to PHP
Here Document
To assign multiple lines to a single string variable using here document
<?php
$channel =<<<_XML_
<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>
</channel>
_XML_;
echo <<<END
This uses the "here document" syntax to output
multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
<br />
END;
print $channel;
?>
Variable Naming
Rules for naming a variable
1.Variable names must begin with a letter or
underscore character.
2.A variable name can consist of numbers, letters,
underscores but you cannot use characters like + , -
, % , ( , ) . & , etc
3.There is no size limit for variables.
Variables Scope
Local variables
a variable declared in a function is considered local
<?
$x = 4;
function assignx () {
$x = 0;
print "$x inside function is $x. ";
}
assignx();
print "$x outside of function is $x. ";
?>
Function Parameters
Function parameters are declared after the function
name and inside parentheses.
They are declared much like a typical variable
<?
// multiply a value by 10 and return it to the caller
function multiply ($value)
{
$value = $value * 10;
return $value;
}
$retval = multiply (10);
Print "Return value is $retvaln";
?>
Global Variables
a global variable can be accessed in any part of the
program
placing the keyword GLOBAL in front of the variable that
should be recognized as global
<?
$somevar = 15;
function addit()
{
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>
Static Variables
a static variable will not lose its value when the function exits
and will still hold that value should the function be called
again
<?
function keep_track()
{
STATIC $count = 0;
$count++;
print $count;
print " ";
}
keep_track();
keep_track();
keep_track();
?>
CONSTANTS
A constant is a name or an identifier for a simple
value.
A constant value cannot change during the execution
of the script.
By default a constant is case-sensitive
To define a constant you have to use define() function
you do not need to have a constant with a $
constant() function:
this function will return the value of the constant
constant() example
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the
previous line
?>
Differences between constants and variables
There is no need to write a dollar sign ($) before a
constant, where as in Variable one has to write a
dollar sign.
Constants cannot be defined by simple assignment,
they may only be defined using the define()
function.
Constants may be defined and accessed anywhere
without regard to variable scoping rules.
Once the Constants have been set, may not be
redefined or undefined.
Few "magical" PHP constants
__LINE__ : The current line number of the file.
__FILE__ :The full path and filename of the file. If used inside
an include, the name of the included file is returned. Since
PHP 4.0.2, __FILE__ always contains an absolute path
whereas in older versions it contained relative path under
some circumstances.
__FUNCTION__ :
The function name. (Added in PHP 4.3.0) As of PHP 5 this
constant returns the function name as it was declared (case-
sensitive). In PHP 4 its value is always lowercased.
__CLASS__ :The class name. (Added in PHP 4.3.0) As of PHP 5
this constant returns the class name as it was declared (case-
sensitive). In PHP 4 its value is always lowercased.
__METHOD_ _ :
The class method name. (Added in PHP 5.0.0) The method name
is returned as it was declared (case-sensitive).
OPERATOR TYPES
What is Operator?
types of operators
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Arithmetic Operators
+ , - , *, /, %, ++, --
<html>
<head><title>Arithmetical Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
$c = $a + $b;
echo "Addition Operation Result: $c <br/>";
$c = $a - $b;
echo "Subtraction Operation Result: $c <br/>";
$c = $a * $b;
echo "Multiplication Operation Result: $c <br/>";
$c = $a / $b;
echo "Division Operation Result: $c <br/>";
$c = $a % $b;
echo "Modulus Operation Result: $c <br/>";
$c = $a++;
echo "Increment Operation Result: $c <br/>";
$c = $a--;
echo "Decrement Operation Result: $c <br/>";
?>
</body>
</html
Comparison Operators
==, !=, >, <, >=, <=
<html>
<head><title>Comparison Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
if( $a == $b ){
echo "TEST1 : a is equal to b<br/>";
}else{
echo "TEST1 : a is not equal to b<br/>";
}
if( $a > $b ){
echo "TEST2 : a is greater than b<br/>";
}else{
echo "TEST2 : a is not greater than b<br/>";
}
if( $a < $b ){
echo "TEST3 : a is less than b<br/>";
}else{
echo "TEST3 : a is not less than b<br/>";
}
if( $a != $b ){
echo "TEST4 : a is not equal to b<br/>";
}else{
echo "TEST4 : a is equal to b<br/>";
}
if( $a >= $b ){
echo "TEST5 : a is either greater than or equal to b<br/>";
}else{
echo "TEST5 : a is neither greater than nor equal to b<br/>";
}
if( $a <= $b ){
echo "TEST6 : a is either less than or equal to b<br/>";
}else{
echo "TEST6 : a is neither less than nor equal to b<br/>";
}
?>
</body>
</html>
Logical Operators
And: (A and B) is true.
Or: (A or B) is true.
&&: (A &&B) is true.
||: (A || B) is true.
!: !(A && B) is true.
Assignment Operators
=, +=,-=,*=,/=,%=
<head><title>Assignment Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
$c = $a + $b; /* Assignment operator */
echo "Addition Operation Result: $c <br/>";
$c += $a; /* c value was 42 + 20 = 62 */
echo "Add AND Assignment Operation Result: $c <br/>";
$c -= $a; /* c value was 42 + 20 + 42 = 104 */
echo "Subtract AND Assignment Operation Result: $c <br/>";
$c *= $a; /* c value was 104 - 42 = 62 */
echo "Multiply AND Assignment Operation Result: $c <br/>";
$c /= $a; /* c value was 62 * 42 = 2604 */
echo "Division AND Assignment Operation Result: $c <br/>";
$c %= $a; /* c value was 2604/42 = 62*/
echo "Modulus AND Assignment Operation Result: $c <br/>";
?>
</body>
</html>
Conditional Operator
<html>
<head><title>Arithmetical Operators</title><head>
<body>
<?php
$a = 10;
$b = 20;
/* If condition is true then assign a to result otherwise b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otherwise b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result<br/>";
?>
</body>
</html>
DECISION MAKING
use conditional statements in your code to make your
decisions
if...else statement - use this statement if you want to
execute a set of code when a condition is true and
another if the condition is not true
elseif statement - is used with the if...else statement
to execute a set of code if one of several condition
are true
switch statement - is used if you want to select one of
many blocks of code to be executed, use the Switch
statement. The switch statement is used to avoid
long blocks of if..elseif..else code.
Switch Statement
<html>
<body>
<?php
$d=date("D");
switch ($d)
{
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
</body>
</html>
LOOP TYPES
Loops in PHP are used to execute the same block of
code a specified number of times
for - loops through a block of code a specified number
of times.
while - loops through a block of code if and as long as
a specified condition is true.
do...while - loops through a block of code once, and
then repeats the loop as long as a special condition
is true.
foreach - loops through a block of code for each
element in an array.
For Loop
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?>
</body>
</html>
While Loop
<html>
<body>
<?php
$i = 0;
$num = 50;
while( $i < 10)
{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body> </html
do...while loop
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
foreach loop
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
break statement
<html>
<body>
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
continue statement
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>
</body>
</html>
ARRAYS
Array variables are “special,” because they can hold
more than one value at a time.
There are three different kind of arrays
Numeric array : An array with a numeric index
Associative array : An array with strings as index
Multidimensional array :An array containing one or
more arrays and values are accessed using multiple
indices
Numeric array
Example
<?php // define array
$fruits = array('apple', 'banana', 'pineapple', 'grape');
?>
To access this
$fruits[index]
here index is numeric, which starts from 0
Associative array
Example
<?php // define array
$fruits = array(
'a' => 'apple',
'b' => 'banana',
'p' => 'pineapple',
'g' => 'grape' );
?>
To access this
$fruits[index]
Here index numbers are replaced with user-defined
strings, or “keys.”
Assigning Array Values
Two ways u can assign values to arrays(both numeric and
associate )
Method 1: same as previous
Method 2:
numeric
<?php
// define array
$cars[0] = 'Ferrari';
$cars[1] = 'Porsche';
$cars[2] = 'Jaguar';
$cars[3] = 'Lamborghini';
$cars[4] = 'Mercedes';
?>
Associate
<?php
// define array
$data['username'] = 'john';
$data['password'] = 'secret';
$data['host'] = '192.168.0.1';
?>
To access a value from an array in a script
echo 'The password is: ' . $data['password'];
Modifying Array Values
example
<?php // define array
$meats = array(
'fish',
'chicken',
'ham',
'lamb'
);
// change 'ham' to 'turkey'
$meats[2] = 'turkey';
?>
To remove an element from an array
use the unset() function on the corresponding key or
index:
Multidimensional Arrays(Nesting Arrays)
Example
<?php // define nested array
$phonebook = array(
array(
'name' => 'Raymond Rabbit',
'tel' => '1234567',
'email' => 'ray@bunnyplanet.in',
),
array(
'name' => 'David Duck',
'tel' => '8562904',
'email' => 'dduck@duckpond.corp',
),
array(
'name' => 'Harold Horse',
'tel' => '5942033',
'email' => 'kingharold@farmersmarket.horsestuff.com',
)
);
?>
To access a value from nested array, use the correct
hierarchical sequence of indices/keys to get to the
value.
// access nested value
echo "David Duck's number is: "
.$phonebook[0]['tel'];
echo " Raymond Rabbit mail id: "
.$phonebook[1][‘email'];
echo " name: "
.$phonebook[2][‘name'];
Strings
• PHP provides many functions with which you can format and
manipulate strings.
Formatting Strings with PHP
Specifier Description
d Display argument as a decimal number
b Display an integer as a binary number
c Display an integer as ASCII equivalent
f Display an integer as a floating-point number (double)
o Display an integer as an octal number
S Display argument as a string
x Display an integer as a lowercase hexadecimal number
X Display an integer as an uppercase hexadecimal
number
Example:str1.php(htdocs)
<?php
$number = 543;
printf('Decimal: %d<br/>', $number);
printf('Binary: %b<br/>', $number);
printf('Double: %f<br/>', $number);
printf('Octal: %o<br/>', $number);
printf('String: %s<br/>', $number);
printf('Hex (lower): %x<br/>', $number);
printf('Hex (upper): %X<br/>', $number);
?>
STRING Handling Functions
String Concatenation Operator
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
strlen() – function returns length of the string.
<?php
$string=“welcome”;
Echo “the length of string is :”.strlen($string);
?>
the strpos() function
The strpos() function is used to search for a string or
character within a string.
example
<?php
echo strpos("Hello world!","world");
?>
• Splitting the string into an array –
explode(seperator, string);
• Joining the array elements into a single string -
implode(seperator,array);
Repeating the same string many times:
str_repeat() – is used to repeat a string for a
specific number of times.
Reversing a string – strrev()
<?php
$string=“kogent- ”;
echo “the repeated string is :”.str_repeat($string,5);
?>
<?php
$string=“kogent”;
Echo “the reversed string is :”.strrev($string);
?>
Finding current date and time
• The date() function is used to format the local
time and date.
date(format, timestamp);
format- format in which the date string to be
displayed.
timestamp – optional, it displays current
system date and time by default.
Some of the characters that can be used with the format
parameter are as follows:
 d – specifies the day of the month(from 01 to 31)
 D – textual representation of the day in three letters
 F – full textual representation of a month(january)
 t – specifies number of days in the given month
 g – specifies 12 – hour format of an hour (1 to 12)
 l – specifies full textual representation of a day
 h - specifies 12 – hour format of an hour (01 to 12)
 i – specifies minutes with leading zeros (00 to 59)
 s – specifies seconds with leading zeros (00 to 59)
 Y – four digit representation of a year
 a – specifies a lowercase am or pm
 S – specifies the english ordinal suffix for the day of month(st,nd,rd,
or th)
<?php
date_default_timezone_set('UTC');
echo date('l'). '<br>';
echo date('l dS of F Y h: i: s a');
?>
Functions
Advantages
It reduces duplication within a program
A function is created once but used many times
Debugging and testing a program becomes easier
when the program is subdivided into functions.
Creating and Invoking Functions
<?php
// function definition // print today's weekday name
function whatIsToday()
{
echo "Today is " . date('l', mktime());
}
// function invocation
whatIsToday();
?>
Function Using Arguments
<?php
// calculate perimeter of rectangle
// p = 2 * (l+w)
function getPerimeter($length, $width)
{
$perimeter = 2 * ($length + $width);
echo "The perimeter of a rectangle of length $length
units and width $width units is: $perimeter units";
}
// function invocation with arguments
getPerimeter(4,2);
?>
Function with return value
<?php
// function definition
// calculate perimeter of rectangle
// p = 2 * (l+w)
function getPerimeter($length, $width)
{ $perimeter = 2 * ($length + $width);
return $perimeter;
}
// function invocation with arguments
echo 'The perimeter of a rectangle of length 4 units and
width 2 units is: ' . getPerimeter(4,2) . ' units';
?>
Setting Default Argument Values
<?php
// generate e-mail address from supplied values
function buildAddress($username, $domain = ‘gmail.com')
{
return $username . '@' . $domain;
}
// function invocation
// without optional argument
echo 'My e-mail address is ' . buildAddress('john');
// function invocation
// with optional argument
echo 'My e-mail address is ' . buildAddress('jane',
'cooldomain.net');
?>
Using Dynamic Argument Lists
<?php
// function definition
// calculate average of supplied values
function calcAverage()
{
$args = func_get_args(); //returns the actual argument values, as an
array
$count = func_num_args(); // returns the number of arguments
passed to a function
$sum = array_sum($args);
$avg = $sum / $count;
return $avg; }
// function invocation with 3 arguments
echo calcAverage(3,6,9);
// function invocation with 8 arguments
echo calcAverage(100,200,100,300,50,150,250,50);
?>
Form Handling
Simple form
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
get
welcome.php
<html>
< body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"];
?>
< /body>
< /html>
---------------------------------------------------------------------
The same result could also be achieved using the
HTTP GET
_get
GET vs. POST vs REQUEST
Both GET and POST create an array. This array holds
key/value pairs, where keys are the names of the form
controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST.
These are superglobals
$_GET is an array of variables passed to the current
script via the URL parameters.
$_POST is an array of variables passed to the current
script via the HTTP POST method.
We may also use the $_REQUEST superglobal, if you
do not care about the source of your request data.
Connecting to database(MySql)
• Php is providing php_mysql.dll library with
number of functionalities to connect with mysql
databse.
• Mysql is open source RDBMS. It supports number
of objects like tables,views, etc.
• The default username for mysql db is “root” and
it does not contain any password.
• We can connect to mysql db through a command
prompt by executing mysql.exe file
c:/xampp/mysql/bin>mysql.exe
mysql>create database dbname;
mysql>use dbname;
phpmyadmin
• It is a GUI used to connect with mysql db.
• It is available with xampp download.
• The url address to open phpmyadmin is
http://localhost/phpmyadmin.
insert – we can insert records in a table
browse – we can browse the table records
structure – to change the structure of a table
sql – we can execute our sql statements
export – we can export database tables into text
files,pdf,excell,etc.
import – we can import the exported file
empty – we can delete the table records
drop – we can delete the table structure
My sql interaction with php
• php_mysql.dll provides more functions to connect with mysql database.
 mysql_connect:
By using this we can create a connection between php and mysql database.it
contains 3 arguments:
 servername
 Username
 password
 mysql_select_db:
to select database from mysql server, arguments are sql statement
and connection id.
 mysql_query:
To execute sql query in mysql database. arguments are sql statement
and connection id.
 mysql_error:
To get the error messages while executing mysql statements.
 mysql_errno:
To get the error number while executing mysql statements.
To create connection between mysql
and php
<?php
if($con=mysql_connect(“localhost”, “root”, “ ”))
{
echo “connected”. “<br>”;
echo $con; // resource type
}
else
echo mysql_error();
?>
Creating database
<?php
$con=mysql_connect("localhost","root");
if(mysql_query("create database student",$con))
echo "database created";
else
echo mysql_error();
?>
Creating table
<?php
$con=mysql_connect("localhost","root");
mysql_select_db(“student”,$con);
if(mysql_query("create table cse(sno int)",$con))
echo “table created";
else
echo mysql_error();
?>

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
 
Introduction to web and php mysql
Introduction to web and php mysqlIntroduction to web and php mysql
Introduction to web and php mysql
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
PHP - Introduction to PHP
PHP -  Introduction to PHPPHP -  Introduction to PHP
PHP - Introduction to PHP
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
Open Source Package PHP & MySQL
Open Source Package PHP & MySQLOpen Source Package PHP & MySQL
Open Source Package PHP & MySQL
 
Web technology html5 php_mysql
Web technology html5 php_mysqlWeb technology html5 php_mysql
Web technology html5 php_mysql
 
Practice exam php
Practice exam phpPractice exam php
Practice exam php
 
PHP - Introduction to PHP Functions
PHP -  Introduction to PHP FunctionsPHP -  Introduction to PHP Functions
PHP - Introduction to PHP Functions
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Data Types In PHP
Data Types In PHPData Types In PHP
Data Types In PHP
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
slidesharenew1
slidesharenew1slidesharenew1
slidesharenew1
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
Programming in perl style
Programming in perl styleProgramming in perl style
Programming in perl style
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 

Ähnlich wie Php

PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
webhostingguy
 

Ähnlich wie Php (20)

php 1
php 1php 1
php 1
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics
 
php.pdf
php.pdfphp.pdf
php.pdf
 
Php essentials
Php essentialsPhp essentials
Php essentials
 
PHP Introduction and Training Material
PHP Introduction and Training MaterialPHP Introduction and Training Material
PHP Introduction and Training Material
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
PHP
PHPPHP
PHP
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
 
lab4_php
lab4_phplab4_php
lab4_php
 
lab4_php
lab4_phplab4_php
lab4_php
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
Php Learning show
Php Learning showPhp Learning show
Php Learning show
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
LAB PHP Consolidated.ppt
LAB PHP Consolidated.pptLAB PHP Consolidated.ppt
LAB PHP Consolidated.ppt
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
In-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTMLIn-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTML
 

Mehr von Rajkiran Mummadi (17)

Servlets
ServletsServlets
Servlets
 
Javabeans .pdf
Javabeans .pdfJavabeans .pdf
Javabeans .pdf
 
Java beans
Java beansJava beans
Java beans
 
Java script
Java scriptJava script
Java script
 
Ajax.pdf
Ajax.pdfAjax.pdf
Ajax.pdf
 
Google glasses
Google glassesGoogle glasses
Google glasses
 
Environmental hazards
Environmental hazardsEnvironmental hazards
Environmental hazards
 
Wcharging
WchargingWcharging
Wcharging
 
Wireless charging
Wireless chargingWireless charging
Wireless charging
 
Standard bop
Standard bopStandard bop
Standard bop
 
Russian technology in indian banking system 1
Russian technology in indian banking system 1Russian technology in indian banking system 1
Russian technology in indian banking system 1
 
Ai presentation
Ai presentationAi presentation
Ai presentation
 
Loon
LoonLoon
Loon
 
Triggers
TriggersTriggers
Triggers
 
autonomous cars
autonomous carsautonomous cars
autonomous cars
 
ET3
ET3ET3
ET3
 
demonetisation
demonetisationdemonetisation
demonetisation
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Php

  • 1. INTRODUCTION •PHP is an Interpreted High-level Programming Language •PHP stands for Personal Home Page (1995 by Rasmus lerdorf) •After PHP version 3 : Hypertext Preprocessor. •PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire ecommerce sites.
  • 2. • It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server. • PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time. • PHP Syntax is C-Like.
  • 3. Common uses of PHP • PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send data, return data to the user. • You add, delete, modify elements within your database thru PHP. • Access cookies variables and set cookies. • Using PHP, you can restrict users to access some pages of your website. • It can encrypt data.
  • 4. Characteristics of PHP • Performance • Portability • Simplicity • Open Source • Community Support • Third-Party Application Support • Security • Flexibility • Familiarity
  • 5. "Hello World" Script in PHP <html> <head> <title>Hello World</title> <body> <?php echo "Hello, World!";?> </body> </html> All PHP code must be included inside one of the three special markup tags <?php PHP code goes here ?> <? PHP code goes here ?> <script language="php"> PHP code goes here </script>
  • 6. SYNTAX OVERVIEW • Escaping to PHP The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The mechanism for doing so is known as 'escaping to PHP.' There are four ways to do this: Canonical PHP tags: <?php...?> Short-open (SGML-style) tags: <?...?> ASP-style tags :<%...%> HTML script tags : <script language="PHP">...</script>
  • 7. • Commenting PHP Code Single-line comment <? # This is a comment, and # This is the second line of the comment // This is a comment too. Each style comments only print "An example with single line comments"; ?> Multi-lines comments <? /* This is a comment with multiline Author : Parameswar Purpose: Multiline Comments Demo Subject: PHP */ print "An example with multi line comments"; ?>
  • 8. PHP is whitespace insensitive $four = 2 + 2; // single spaces $four <tab>=<tab>2<tab>+<tab>2 ; // spaces and tabs $four = 2+ 2; // multiple lines PHP is case sensitive <html> <body> <? $capital = 67; print("Variable capital is $capital<br>"); print("Variable CaPiTaL is $CaPiTaL<br>"); ?> </body> </html> Statements or expressions terminated by semicolons
  • 9. VARIABLE TYPES To store the information we use a variable. Here are the most important things to know about variables in PHP. 1. All variables are denoted with a dollar sign ($). 2. The value of a variable is the value of its most recent assignment. 3. Variables are assigned with “= “operator 4. Variables in PHP do not have intrinsic types 5. Variables used before they are assigned have default values. 6. PHP automatically converting types from one to another when necessary.
  • 10. PHP has eight data type Integers Doubles Booleans simple Types NULL Strings Arrays Objects compound Types Resources : are special variables that hold references to resources external to PHP
  • 11. Here Document To assign multiple lines to a single string variable using here document <?php $channel =<<<_XML_ <channel> <title>What's For Dinner<title> <link>http://menu.example.com/<link> <description>Choose what to eat tonight.</description> </channel> _XML_; echo <<<END This uses the "here document" syntax to output multiple lines with variable interpolation. Note that the here document terminator must appear on a line with just a semicolon. no extra whitespace! <br /> END; print $channel; ?>
  • 12. Variable Naming Rules for naming a variable 1.Variable names must begin with a letter or underscore character. 2.A variable name can consist of numbers, letters, underscores but you cannot use characters like + , - , % , ( , ) . & , etc 3.There is no size limit for variables.
  • 13. Variables Scope Local variables a variable declared in a function is considered local <? $x = 4; function assignx () { $x = 0; print "$x inside function is $x. "; } assignx(); print "$x outside of function is $x. "; ?>
  • 14. Function Parameters Function parameters are declared after the function name and inside parentheses. They are declared much like a typical variable <? // multiply a value by 10 and return it to the caller function multiply ($value) { $value = $value * 10; return $value; } $retval = multiply (10); Print "Return value is $retvaln"; ?>
  • 15. Global Variables a global variable can be accessed in any part of the program placing the keyword GLOBAL in front of the variable that should be recognized as global <? $somevar = 15; function addit() { GLOBAL $somevar; $somevar++; print "Somevar is $somevar"; } addit(); ?>
  • 16. Static Variables a static variable will not lose its value when the function exits and will still hold that value should the function be called again <? function keep_track() { STATIC $count = 0; $count++; print $count; print " "; } keep_track(); keep_track(); keep_track(); ?>
  • 17. CONSTANTS A constant is a name or an identifier for a simple value. A constant value cannot change during the execution of the script. By default a constant is case-sensitive To define a constant you have to use define() function you do not need to have a constant with a $
  • 18. constant() function: this function will return the value of the constant constant() example <?php define("MINSIZE", 50); echo MINSIZE; echo constant("MINSIZE"); // same thing as the previous line ?>
  • 19. Differences between constants and variables There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign. Constants cannot be defined by simple assignment, they may only be defined using the define() function. Constants may be defined and accessed anywhere without regard to variable scoping rules. Once the Constants have been set, may not be redefined or undefined.
  • 20. Few "magical" PHP constants __LINE__ : The current line number of the file. __FILE__ :The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path whereas in older versions it contained relative path under some circumstances. __FUNCTION__ : The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case- sensitive). In PHP 4 its value is always lowercased. __CLASS__ :The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case- sensitive). In PHP 4 its value is always lowercased. __METHOD_ _ : The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
  • 21. OPERATOR TYPES What is Operator? types of operators Arithmetic Operators Comparison Operators Logical (or Relational) Operators Assignment Operators Conditional (or ternary) Operators
  • 22. Arithmetic Operators + , - , *, /, %, ++, -- <html> <head><title>Arithmetical Operators</title><head> <body> <?php $a = 42; $b = 20; $c = $a + $b; echo "Addition Operation Result: $c <br/>"; $c = $a - $b; echo "Subtraction Operation Result: $c <br/>"; $c = $a * $b; echo "Multiplication Operation Result: $c <br/>"; $c = $a / $b; echo "Division Operation Result: $c <br/>"; $c = $a % $b; echo "Modulus Operation Result: $c <br/>"; $c = $a++; echo "Increment Operation Result: $c <br/>"; $c = $a--; echo "Decrement Operation Result: $c <br/>"; ?> </body> </html
  • 23. Comparison Operators ==, !=, >, <, >=, <= <html> <head><title>Comparison Operators</title><head> <body> <?php $a = 42; $b = 20; if( $a == $b ){ echo "TEST1 : a is equal to b<br/>"; }else{ echo "TEST1 : a is not equal to b<br/>"; } if( $a > $b ){ echo "TEST2 : a is greater than b<br/>"; }else{ echo "TEST2 : a is not greater than b<br/>"; } if( $a < $b ){ echo "TEST3 : a is less than b<br/>"; }else{ echo "TEST3 : a is not less than b<br/>"; }
  • 24. if( $a != $b ){ echo "TEST4 : a is not equal to b<br/>"; }else{ echo "TEST4 : a is equal to b<br/>"; } if( $a >= $b ){ echo "TEST5 : a is either greater than or equal to b<br/>"; }else{ echo "TEST5 : a is neither greater than nor equal to b<br/>"; } if( $a <= $b ){ echo "TEST6 : a is either less than or equal to b<br/>"; }else{ echo "TEST6 : a is neither less than nor equal to b<br/>"; } ?> </body> </html>
  • 25. Logical Operators And: (A and B) is true. Or: (A or B) is true. &&: (A &&B) is true. ||: (A || B) is true. !: !(A && B) is true.
  • 26. Assignment Operators =, +=,-=,*=,/=,%= <head><title>Assignment Operators</title><head> <body> <?php $a = 42; $b = 20; $c = $a + $b; /* Assignment operator */ echo "Addition Operation Result: $c <br/>"; $c += $a; /* c value was 42 + 20 = 62 */ echo "Add AND Assignment Operation Result: $c <br/>"; $c -= $a; /* c value was 42 + 20 + 42 = 104 */ echo "Subtract AND Assignment Operation Result: $c <br/>"; $c *= $a; /* c value was 104 - 42 = 62 */ echo "Multiply AND Assignment Operation Result: $c <br/>"; $c /= $a; /* c value was 62 * 42 = 2604 */ echo "Division AND Assignment Operation Result: $c <br/>"; $c %= $a; /* c value was 2604/42 = 62*/ echo "Modulus AND Assignment Operation Result: $c <br/>"; ?> </body> </html>
  • 28. <html> <head><title>Arithmetical Operators</title><head> <body> <?php $a = 10; $b = 20; /* If condition is true then assign a to result otherwise b */ $result = ($a > $b ) ? $a :$b; echo "TEST1 : Value of result is $result<br/>"; /* If condition is true then assign a to result otherwise b */ $result = ($a < $b ) ? $a :$b; echo "TEST2 : Value of result is $result<br/>"; ?> </body> </html>
  • 29. DECISION MAKING use conditional statements in your code to make your decisions if...else statement - use this statement if you want to execute a set of code when a condition is true and another if the condition is not true elseif statement - is used with the if...else statement to execute a set of code if one of several condition are true switch statement - is used if you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.
  • 30. Switch Statement <html> <body> <?php $d=date("D"); switch ($d) { case "Mon": echo "Today is Monday"; break; case "Tue": echo "Today is Tuesday"; break; case "Wed": echo "Today is Wednesday"; break; case "Thu": echo "Today is Thursday"; break; case "Fri": echo "Today is Friday"; break; case "Sat": echo "Today is Saturday"; break; case "Sun": echo "Today is Sunday"; break; default: echo "Wonder which day is this ?"; } ?> </body> </html>
  • 31. LOOP TYPES Loops in PHP are used to execute the same block of code a specified number of times for - loops through a block of code a specified number of times. while - loops through a block of code if and as long as a specified condition is true. do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true. foreach - loops through a block of code for each element in an array.
  • 32. For Loop <html> <body> <?php $a = 0; $b = 0; for( $i=0; $i<5; $i++ ) { $a += 10; $b += 5; } echo ("At the end of the loop a=$a and b=$b" ); ?> </body> </html>
  • 33. While Loop <html> <body> <?php $i = 0; $num = 50; while( $i < 10) { $num--; $i++; } echo ("Loop stopped at i = $i and num = $num" ); ?> </body> </html
  • 34. do...while loop <html> <body> <?php $i = 0; $num = 0; do { $i++; }while( $i < 10 ); echo ("Loop stopped at i = $i" ); ?> </body> </html>
  • 35. foreach loop <html> <body> <?php $array = array( 1, 2, 3, 4, 5); foreach( $array as $value ) { echo "Value is $value <br />"; } ?> </body> </html>
  • 36. break statement <html> <body> <?php $i = 0; while( $i < 10) { $i++; if( $i == 3 )break; } echo ("Loop stopped at i = $i" ); ?> </body> </html>
  • 37. continue statement <html> <body> <?php $array = array( 1, 2, 3, 4, 5); foreach( $array as $value ) { if( $value == 3 )continue; echo "Value is $value <br />"; } ?> </body> </html>
  • 38. ARRAYS Array variables are “special,” because they can hold more than one value at a time. There are three different kind of arrays Numeric array : An array with a numeric index Associative array : An array with strings as index Multidimensional array :An array containing one or more arrays and values are accessed using multiple indices
  • 39. Numeric array Example <?php // define array $fruits = array('apple', 'banana', 'pineapple', 'grape'); ?> To access this $fruits[index] here index is numeric, which starts from 0
  • 40. Associative array Example <?php // define array $fruits = array( 'a' => 'apple', 'b' => 'banana', 'p' => 'pineapple', 'g' => 'grape' ); ?> To access this $fruits[index] Here index numbers are replaced with user-defined strings, or “keys.”
  • 41. Assigning Array Values Two ways u can assign values to arrays(both numeric and associate ) Method 1: same as previous Method 2: numeric <?php // define array $cars[0] = 'Ferrari'; $cars[1] = 'Porsche'; $cars[2] = 'Jaguar'; $cars[3] = 'Lamborghini'; $cars[4] = 'Mercedes'; ?>
  • 42. Associate <?php // define array $data['username'] = 'john'; $data['password'] = 'secret'; $data['host'] = '192.168.0.1'; ?> To access a value from an array in a script echo 'The password is: ' . $data['password'];
  • 43. Modifying Array Values example <?php // define array $meats = array( 'fish', 'chicken', 'ham', 'lamb' ); // change 'ham' to 'turkey' $meats[2] = 'turkey'; ?> To remove an element from an array use the unset() function on the corresponding key or index:
  • 44. Multidimensional Arrays(Nesting Arrays) Example <?php // define nested array $phonebook = array( array( 'name' => 'Raymond Rabbit', 'tel' => '1234567', 'email' => 'ray@bunnyplanet.in', ), array( 'name' => 'David Duck', 'tel' => '8562904', 'email' => 'dduck@duckpond.corp', ), array( 'name' => 'Harold Horse', 'tel' => '5942033', 'email' => 'kingharold@farmersmarket.horsestuff.com', ) ); ?>
  • 45. To access a value from nested array, use the correct hierarchical sequence of indices/keys to get to the value. // access nested value echo "David Duck's number is: " .$phonebook[0]['tel']; echo " Raymond Rabbit mail id: " .$phonebook[1][‘email']; echo " name: " .$phonebook[2][‘name'];
  • 46. Strings • PHP provides many functions with which you can format and manipulate strings. Formatting Strings with PHP Specifier Description d Display argument as a decimal number b Display an integer as a binary number c Display an integer as ASCII equivalent f Display an integer as a floating-point number (double) o Display an integer as an octal number S Display argument as a string x Display an integer as a lowercase hexadecimal number X Display an integer as an uppercase hexadecimal number
  • 47. Example:str1.php(htdocs) <?php $number = 543; printf('Decimal: %d<br/>', $number); printf('Binary: %b<br/>', $number); printf('Double: %f<br/>', $number); printf('Octal: %o<br/>', $number); printf('String: %s<br/>', $number); printf('Hex (lower): %x<br/>', $number); printf('Hex (upper): %X<br/>', $number); ?>
  • 48. STRING Handling Functions String Concatenation Operator <?php $string1="Hello World"; $string2="1234"; echo $string1 . " " . $string2; ?> strlen() – function returns length of the string. <?php $string=“welcome”; Echo “the length of string is :”.strlen($string); ?>
  • 49. the strpos() function The strpos() function is used to search for a string or character within a string. example <?php echo strpos("Hello world!","world"); ?> • Splitting the string into an array – explode(seperator, string); • Joining the array elements into a single string - implode(seperator,array);
  • 50. Repeating the same string many times: str_repeat() – is used to repeat a string for a specific number of times. Reversing a string – strrev() <?php $string=“kogent- ”; echo “the repeated string is :”.str_repeat($string,5); ?> <?php $string=“kogent”; Echo “the reversed string is :”.strrev($string); ?>
  • 51. Finding current date and time • The date() function is used to format the local time and date. date(format, timestamp); format- format in which the date string to be displayed. timestamp – optional, it displays current system date and time by default.
  • 52. Some of the characters that can be used with the format parameter are as follows:  d – specifies the day of the month(from 01 to 31)  D – textual representation of the day in three letters  F – full textual representation of a month(january)  t – specifies number of days in the given month  g – specifies 12 – hour format of an hour (1 to 12)  l – specifies full textual representation of a day  h - specifies 12 – hour format of an hour (01 to 12)  i – specifies minutes with leading zeros (00 to 59)  s – specifies seconds with leading zeros (00 to 59)  Y – four digit representation of a year  a – specifies a lowercase am or pm  S – specifies the english ordinal suffix for the day of month(st,nd,rd, or th) <?php date_default_timezone_set('UTC'); echo date('l'). '<br>'; echo date('l dS of F Y h: i: s a'); ?>
  • 53. Functions Advantages It reduces duplication within a program A function is created once but used many times Debugging and testing a program becomes easier when the program is subdivided into functions.
  • 54. Creating and Invoking Functions <?php // function definition // print today's weekday name function whatIsToday() { echo "Today is " . date('l', mktime()); } // function invocation whatIsToday(); ?>
  • 55. Function Using Arguments <?php // calculate perimeter of rectangle // p = 2 * (l+w) function getPerimeter($length, $width) { $perimeter = 2 * ($length + $width); echo "The perimeter of a rectangle of length $length units and width $width units is: $perimeter units"; } // function invocation with arguments getPerimeter(4,2); ?>
  • 56. Function with return value <?php // function definition // calculate perimeter of rectangle // p = 2 * (l+w) function getPerimeter($length, $width) { $perimeter = 2 * ($length + $width); return $perimeter; } // function invocation with arguments echo 'The perimeter of a rectangle of length 4 units and width 2 units is: ' . getPerimeter(4,2) . ' units'; ?>
  • 57. Setting Default Argument Values <?php // generate e-mail address from supplied values function buildAddress($username, $domain = ‘gmail.com') { return $username . '@' . $domain; } // function invocation // without optional argument echo 'My e-mail address is ' . buildAddress('john'); // function invocation // with optional argument echo 'My e-mail address is ' . buildAddress('jane', 'cooldomain.net'); ?>
  • 58. Using Dynamic Argument Lists <?php // function definition // calculate average of supplied values function calcAverage() { $args = func_get_args(); //returns the actual argument values, as an array $count = func_num_args(); // returns the number of arguments passed to a function $sum = array_sum($args); $avg = $sum / $count; return $avg; } // function invocation with 3 arguments echo calcAverage(3,6,9); // function invocation with 8 arguments echo calcAverage(100,200,100,300,50,150,250,50); ?>
  • 59. Form Handling Simple form <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html> get
  • 60. welcome.php <html> < body> Welcome <?php echo $_POST["name"]; ?><br> Your email address is: <?php echo $_POST["email"]; ?> < /body> < /html> --------------------------------------------------------------------- The same result could also be achieved using the HTTP GET _get
  • 61. GET vs. POST vs REQUEST Both GET and POST create an array. This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user. Both GET and POST are treated as $_GET and $_POST. These are superglobals $_GET is an array of variables passed to the current script via the URL parameters. $_POST is an array of variables passed to the current script via the HTTP POST method. We may also use the $_REQUEST superglobal, if you do not care about the source of your request data.
  • 62. Connecting to database(MySql) • Php is providing php_mysql.dll library with number of functionalities to connect with mysql databse. • Mysql is open source RDBMS. It supports number of objects like tables,views, etc. • The default username for mysql db is “root” and it does not contain any password. • We can connect to mysql db through a command prompt by executing mysql.exe file c:/xampp/mysql/bin>mysql.exe mysql>create database dbname; mysql>use dbname;
  • 63. phpmyadmin • It is a GUI used to connect with mysql db. • It is available with xampp download. • The url address to open phpmyadmin is http://localhost/phpmyadmin. insert – we can insert records in a table browse – we can browse the table records structure – to change the structure of a table sql – we can execute our sql statements export – we can export database tables into text files,pdf,excell,etc. import – we can import the exported file empty – we can delete the table records drop – we can delete the table structure
  • 64. My sql interaction with php • php_mysql.dll provides more functions to connect with mysql database.  mysql_connect: By using this we can create a connection between php and mysql database.it contains 3 arguments:  servername  Username  password  mysql_select_db: to select database from mysql server, arguments are sql statement and connection id.  mysql_query: To execute sql query in mysql database. arguments are sql statement and connection id.  mysql_error: To get the error messages while executing mysql statements.  mysql_errno: To get the error number while executing mysql statements.
  • 65. To create connection between mysql and php <?php if($con=mysql_connect(“localhost”, “root”, “ ”)) { echo “connected”. “<br>”; echo $con; // resource type } else echo mysql_error(); ?>
  • 66. Creating database <?php $con=mysql_connect("localhost","root"); if(mysql_query("create database student",$con)) echo "database created"; else echo mysql_error(); ?>