Unit 02

Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

DIPLOMA IN COMPUTER ENGINEERING

SEMESTER : 5
UNIT : 2

DYNAMIC WEB PAGE DEVELOPMENT


(3350702)

Prepared By : Miss Dhara H. Wagh


Lecturer In Computer Engineering Department

Government Polytechnic Gandhinagar


Introduction to PHP
 PHP was originally called “Personal Home Page” but was later termed
“PHP Hypertext Preprocessor.”
 PHP is a server-side scripting language – that is interpreted and executed
on the server
 It is an open source programming language that allows web developers to
create dynamic content that interacts with databases.
 Used to make web pages dynamic:
 provide different content depending on context
 interface with other services: database, e-mail, etc.
 authenticate users
History of PHP
 PHP was conceived by Rasmus Lerdorf in 1994 but appeared in the
market in 1995.

RASMUS LERDORF
Creator of PHP
How PHP works?

HTML code
+
xyz.php PHP code
Static HTML
Web Page Request code
PHP
HTML Response SCRIPTING
Engine

Client’s Browser

File must have .php extension Dynamic Data


(files server ,Database
server ,Webserver etc)
PHP Features
What you need to start coding

 Web Development Environment :


E.g. WAMP, LAMP, XAMPP
 Text Editor
E.g. Notepad, Notepad++, Sublime Editor ,
Adobe Dreamweaver , Visual Studio Code etc.
 Web Browser
E.g. Internet Explorer, Google Chrome,
Mozilla Firefox, Safari etc.
WAMP
Windows, Apache, MySQL, PHP

WAMP is an open source web development platform that uses windows as


the operating system, apache as the web server, mysql as the relational
database management system and PHP as the object-oriented scripting
language.
LAMP
Linux, Apache, MySQL, PHP

LAMP is an open source web development platform that uses linux as the
operating system, apache as the web server, mysql as the relational
database management system and PHP as the object-oriented scripting
language.
XAMPP

 XAMPP’s name is an acronym for:


X (to be read as “cross”, meaning cross-platform)
Apache
MariaDB
PHP
Perl
 XAMPP : is a free and open source cross-platform web server solution stack package,
consisting mainly of the Apache HTTP Server, MySQL database, and interpreters for
scripts written in the PHP and Perl programming languages.
Installing XAMPP and Sublime

 XAMPP :
 Installing XAMPP for Windows you need to download installable file from
https://www.apachefriends.org/download.html
 After downloading .exe file you need to execute the file.

 Sublime Editor :
 Installing sublime you need to download installable file from
https://www.sublimetext.com/3
 After downloading .exe file you need to execute the file
PHP File structure

Helloworld.php
Output in Web Browser
<html>
Hello World!
<head>
<title>Hello World</title>
</head> Note:
Contents of a .php file between <?php and
<body> 

?> are executed as PHP code


<?php  All other contents are output as pure
HTML
echo "Hello, World!";
 We can switch back and forth between
?> HTML and PHP "modes"
</body></html>
PHP start and end tags
 All PHP code must be included inside one of the four special
markup tags are recognised by the PHP Parser.
1. Standard PHP Tag: <?php PHP code goes here ?>
2. Short-open (SGML-style) tags: <? PHP code goes here ?>

3. HTML script tags :


<script language = "php"> PHP code goes here </script>
4. ASP-style tags: <% PHP code goes here %>

Note :Standard tags are recommended for use other tags required
to enable respective tags in php.ini configuration file
Commenting codes in PHP

1. Single-line comments : They are generally used for short


explanations or notes relevant to the local code.
Example:
<?php
# This is a comment, and
# This is the second line of the comment
// This is a comment too. Each style comments only
echo "An example with single line comments";
?>
Commenting codes in PHP

2. Multi-lines comments: They are generally used to provide pseudocode


algorithms and more detailed explanations when necessary.
Example:
<?php
/* This is a comment with multiline
Purpose: Multiline Comments Demo
Subject: PHP
*/

echo "An example with multi line comments";


?>
Output Statement :ECHO

 PHP echo is a language construct, not a function. Therefore, you don't


need to use parenthesis with it. But if you want to use more than one
parameter, it is required to use parenthesis.
 Syntax :
void echo ( string $arg1 [, string $... ] )
 echo is a statement, which is used to display the output.
 echo can be used with or without parentheses: echo(), and echo.
 echo does not return any value.
 We can pass multiple strings separated by a comma (,) in echo.
 echo is faster than the print statement.
Output Statement :Print
 Like PHP echo, PHP print is a language construct, so you don't need to use
parenthesis with the argument list. Print statement can be used with or
without parentheses: print and print(). Unlike echo, it always returns 1.
 Syntax :
int print(string $arg)
 print is a statement, used as an alternative to echo at many times to display
the output.
 print can be used with or without parentheses.
 print always returns an integer value, which is 1.
 Using print, we cannot pass multiple arguments.
 print is slower than the echo statement.
PHP Variables

 In PHP, a variable is declared using a $ sign followed by the


variable name.
Syntax: $variablename=value;
Example : $a=5;
 As PHP is a loosely typed language, so we do not need to declare
the data types of the variables. It automatically analyzes the values
and makes conversions to its correct datatype.
 After declaring a variable, it can be reused throughout the code.
 Assignment Operator (=) is used to assign the value to a variable.
Rules for Variable declaration

 A variable must start with a dollar ($) sign, followed by the variable
name.
 It can only contain alpha-numeric character and underscore (A-z, 0-9,
_).
 A variable name must start with a letter or underscore (_) character.
 A PHP variable name cannot contain spaces.
 One thing to be kept in mind that the variable name cannot start with
a number or special symbols.
 PHP variables are case-sensitive, so $name and $NAME both are
treated as different variable.
Variables examples

$word
$Word
$greenThing
$green_thing
$word4
 We can not use reserved keywords as variables like:

$this $if
$function $while
$include $break
Datatypes in PHP

1. Integers − are whole numbers, without a decimal point, like 4195


2. Doubles − are floating-point numbers, like 3.14159 or 49.1
3. Booleans − have only two possible values either true or false
4. NULL − is a special type that only has one value: NULL
5. Strings − are sequences of characters, like 'PHP supports string
operations’
6. Arrays − are named and indexed collections of other values
7. Objects − are instances of programmer-defined classes, which can
package up both other kinds of values and functions that are specific to
the class
8. Resources − are special variables that hold references to resources
external to PHP (such as database connections)s
Variables

$str=“Hello World”; string


$x=5; integer
$y=45.8; double
$a=true; boolean
$b=null; Null
$c=array(“PHP”,”PYTHON”); Array
PHP $ and $$ Variables
 The $var (single dollar) is a normal variable with the name var that
stores any value like string, integer, float, etc.
 The $$var (double dollar) is a reference variable that stores the value of
the $variable inside it.
<?php
$name=“Cat"; //Normal Variable
$$name=“Dog"; //Reference Variable
echo $name."<br/>";//Cat
echo $$name."<br/>";//Dog
echo $Cat;//Dog
?>
PHP gettype() function:

 We can determine the type of a variable


 Syntax :
string gettype($variablename);
 The function then returns the variable's type as a string.

Example :
<?php
$a = 3;
echo gettype($a) . "<br>";
?>
PHP settype() function:
 Settype function converts value from one datatype to another datatype
 Syntax :
boolean settype($variablename,$type);
 Example:
<?php
$a = "32"; // string
settype($a, "integer"); // $a is now integer
?>
var_dump function:

 The var_dump() function dumps information about one or more


variables. The information holds type and value of the variable(s).
 Syntax :
var_dump($var1[, $var2,…, $varN])
 Example:<?php
$a = 32;
echo var_dump($a) . "<br>";
$b = "Hello world!";
echo var_dump($b) . "<br>";
?>
PHP Operators

 PHP Operator is a symbol i.e used to perform operations on


operands.
 Operators are used to perform operations on variables or values.
 PHP Operators can be categorized in following forms:
Arithmetic Operators
Logical Operators
 Bitwise Operators
 Assignment Operators
 String Operators
 Inc/ Decrement Operators
 Comparison Operators
Arithmetic Operators

Operator Name Example Explanation


+ Addition $a + $b Sum of operands
- Subtraction $a - $b Difference of operands

* Multiplication $a * $b Product of operands

/ Division $a / $b Quotient of operands

% Modulus $a % $b Remainder of operands

** Exponentiation $a ** $b $a raised to the power $b


Logical Operators

Operator Name Example Explanation


and And $a and $b Return TRUE if both $a and $b are true

Or Or $a or $b Return TRUE if either $a or $b is true

xor Xor $a xor $b Return TRUE if either $ or $b is true but not both

! Not ! $a Return TRUE if $a is not true

&& And $a && $b Return TRUE if either $a and $b are true

|| Or $a || $b Return TRUE if either $a or $b is true


Bitwise Operators

Operator Name Example Explanation

& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.

| Or $a | $b Bits that are 1 in either $a or $b are set to 1

^ Xor $a ^ $b Bits that are 1 in either $a or $b are set to 0.

~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places
Assignment Operators
Operat Name Example Explanation
or
= Assign $a = $b The value of right operand is assigned to the left operand.
+= Add then $a += $b Addition same as $a = $a + $b
Assign
-= Subtract then $a -= $b Subtraction same as $a = $a - $b
Assign
*= Multiply then $a *= $b Multiplication same as $a = $a * $b
Assign
/= Divide then $a /= $b Find quotient same as $a = $a / $b
Assign
(quotient)
%= Divide then $a %= $b Find remainder same as $a = $a % $b
Assign
(remainder)
String Operators

Operator Name Example Explanation


. Concatenation $a . $b Concatenate both $a and $b

.= Concatenation and $a .= $b First concatenate $a and $b, then assign the


Assignment concatenated string to $a, e.g. $a = $a . $b
Inc/ Decrement Operators

Oper Name Exampl Explanation


ator e
++ Increment ++$a Increment the value of $a by one, then return
$a
$a++ Return $a, then increment the value of $a by
one
-- decrement --$a Decrement the value of $a by one, then return
$a
$a-- Return $a, then decrement the value of $a by
Comparison Operators
Operator Name Example Explanation
== Equal $a == $b Return TRUE if $a is equal to $b
=== Identical $a === $b Return TRUE if $a is equal to $b, and they are of same data
type
!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are not of
same data type
!= Not equal $a != $b Return TRUE if $a is not equal to $b
<> Not equal $a <> $b Return TRUE if $a is not equal to $b
< Less than $a < $b Return TRUE if $a is less than $b
> Greater than $a > $b Return TRUE if $a is greater than $b
<= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b
>= Greater than or equal to $a >= $b Return TRUE if $a is greater than or equal $b
<=> Spaceship $a <=>$b Return -1 if $a is less than $b
Return 0 if $a is equal $b
Return 1 if $a is greater than $b
Operator Precedence

Operators Additional Information Associativity


clone new clone and new non-associative
[ array() left
** arithmetic right
++ -- ~ (int) (float) (string) increment/decrement and right
(array) (object) (bool) @ types
instanceof types non-associative
! logical (negation) right
*/% arithmetic left
+-. arithmetic and string left
concatenation
Operator Precedence
Operators Additional Information Associativity
| bitwise OR left
&& logical AND left
|| logical OR left
?: ternary left
= += -= *= **= /= .= %= &= |= ^= <<= assignment right
>>= =>
and logical left
xor logical left
or logical left
, many uses (comma) left
| bitwise OR left
&& logical AND left
|| logical OR left
?: ternary left
PHP Constants

 PHP constants are name or identifier that can't be changed during the
execution of the script except for magic constants, which are not really
constants. PHP constants can be defined by 2 ways:
1. Using define() function
2. Using const keyword
 PHP constants should be defined in uppercase letters
 constants are automatically global throughout the script.
 Constants are similar to the variable except once they defined, they can never
be undefined or changed. They remain constant across the entire program.
PHP constants follow the same PHP variable rules.
PHP constant: define()

 Use the define() function to create a constant. It defines


constant at run time.
 Syntax : define(name, value, case-insensitive)

name: It specifies the constant name.


value: It specifies the constant value.
case-insensitive: Specifies whether a constant is case-
insensitive. Default value is false. It means it is case
sensitive by default.
:

PHP constant: const keyword

 The const keyword is used to create class constants. Unlike


regular properties (variables), class constants do not have an
access level specified because they are always publicly visible .
 The constant defined using const keyword are case-sensitive.

Syntax : const variable name


Example:
class Circle {
const PI = 3.14159;
}
Constant() function :
 It is used to print the value of constants using constant() function instead of
using the echo statement.
 Syntax : constant (name)
 Example: <?php
const GP="Hello const in GP";
define("MSG", "GP Gandhinagar");
echo GP,"<br>";
echo MSG, "</br>";
echo constant("GP"),"<br>";
echo constant("MSG");
?>
Magic Constants

 Magic constants are the predefined constants in PHP which get


changed on the basis of their use.
 They start with double underscore (__) and ends with double
underscore.
 They are similar to other predefined constants but as they change
their values with the context, they are called magic constants.
 There are eight magic constants that start and end with double
underscores (__).
Magic Constants(Cont.)
Sr PHP Magic Constant Description
No
1 __LINE__ It returns the current line number of the file, where this constant is used.
2 __FILE__ This magic constant returns the full path of the executed file, where the file is stored. If it is used inside
the include, the name of the included file is returned.
3 __DIR__ It returns the full directory path of the executed file. The path returned by this magic constant is
equivalent to dirname(__FILE__). This magic constant does not have a trailing slash unless it is a root
directory.
4 __FUNCTION__ This magic constant returns the function name, where this constant is used. It will return blank if it is
used outside of any function.
5 __CLASS__ It returns the class name, where this magic constant is used. __CLASS__ constant also works in traits.

6 __TRAIT__ This magic constant returns the trait name, where it is used.
7 __METHOD__ It returns the name of the class method where this magic constant is included. The method name is
returned the same as it was declared.
8 __NAMESPACE__ It returns the current namespace where it is used.
9 ClassName::class It returns the fully qualified name of the ClassName.
Control Statements

Decision Making Loop Statements


Statements
• for loop
• If statement • while loop
• if...else statement Break Continue
statement statement • do...while
• elseif statement
loop
• Nested if statements
• switch statement • foreach loop
If –else statement

 PHP if else statement is used to test condition.


 There are various ways to use if statement in PHP.

if
if-else
if-else-if
nested if
If statement

 If statement is used to executes the block of code exist inside the if


statement only if the specified condition is true
 Syntax : if(condition)
{
//code to be executed
}
Example : <?php
$num=12;
if($num<100){ echo "$num is less than 100"; }
?>
If-else statement
 If-else statement is slightly different from if statement. It executes one block
of code if the specified condition is true and another block of code if the
condition is false.
 Syntax : if(condition){ //code to be executed if true }
else{ //code to be executed if false }
 Example : <?php
$num=12;
if($num%2==0)
{ echo "$num is even number"; }
else { echo "$num is odd number"; }
?>
If-else-if Statement
 The PHP if-else-if is a special statement used to combine multiple
if...else statements. So, we can check multiple conditions using this
statement.
Syntax :
if (condition1){ //code to be executed if condition1 is true
elseif (condition2){ //code to be executed if condition2 is true }
elseif (condition3){ //code to be executed if condition3 is true .... }
else{ //code to be executed if all given conditions are false }
If-else--if Statement

 Example : <?php
$marks=69;
if ($marks<33){ echo "fail"; }
else if ($marks>=34 && $marks<50) { echo "D grade"; }
else if ($marks>=50 && $marks<65) { echo "C grade"; }
else if ($marks>=65 && $marks<80) { echo "B grade"; }
else if ($marks>=80 && $marks<90) { echo "A grade"; }
else if ($marks>=90 && $marks<100) { echo "A+ grade"; }
else { echo "Invalid input"; }
?>
Nested-if Statement

 The nested if statement contains the if block inside another if block. The
inner if statement executes only when specified condition in outer if
statement is true.
 Syntax :
if (condition) { //code to be executed if condition is true
if (condition) {//code to be executed if condition is true }
}
Nested-if Statement
Example : <?php
$age = 23;
$nationality = "Indian";
//applying conditions for voting in India on nationality and age
if ($nationality == "Indian")
{ if ($age >= 18)
{ echo "Eligible to give vote"; }
else { echo "Not eligible to give vote"; }
}
else { echo “To Vote in India your nationality Should be Indian”;}
?>
Break Statement

 PHP break statement breaks the execution of the current for, while, do-
while, switch, and for-each loop. If you use break inside inner loop, it breaks
the execution of inner loop only.
 The break keyword immediately ends the execution of the loop or switch
structure. It breaks the current flow of the program at the specified
condition and program control resumes at the next statements outside the
loop.
 The break statement can be used in all types of loops such as while, do-
while, for, foreach loop, and also with switch case.
 Syntax : jump statement;
break;
Break Statement

 Example:<?php
for($i=1;$i<=10;$i++)
{
echo "$i <br/>";
if($i==5)
{
break;
}
}
?>
Continue Statement

 The PHP continue statement is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition.
 The continue statement is used within looping and switch control structure
when you immediately jump to the next iteration.
 The continue statement can be used with all types of loops such as - for,
while, do-while, and foreach loop. The continue statement allows the user to
skip the execution of the code for the specified condition.
 Syntax: jump-statement;
continue;
Continue Statement

Example : <?php
for ($x = 0; $x < 10; $x++)
{
if ($x == 4)
{
continue;
}
echo "The number is: $x <br>";
}
?>
Switch statement

 PHP switch statement is used to execute one statement from multiple


conditions. It works like PHP if-else-if statement.
 Syntax : switch(expression){
case value1: //code to be executed
break;
case value2: //code to be executed
break;
......
default: // code to be executed if all cases are not matched;
}
Important points to be noticed about switch case:

 The default is an optional statement. Even it is not important, that default must always be
the last statement.
 There can be only one default in a switch statement. More than one default may lead to
a Fatal error.
 Each case can have a break statement, which is used to terminate the sequence of
statement.
 The break statement is optional to use in switch. If break is not used, all the statements
will execute after finding matched case value.
 PHP allows you to use number, character, string, as well as functions in switch expression.
 Nesting of switch statements is allowed, but it makes the program more complex and less
readable.
 You can use semicolon (;) instead of colon (:). It will not generate any error.
Switch statement

 Example:
<?php
$num=20;
switch($num){
case 10: echo("number is equals to 10"); break;
case 20: echo("number is equal to 20"); break;
case 30: echo("number is equal to 30"); break;
default: echo("number is not equal to 10, 20 or 30");
}
?>
For Loop

 PHP for loop can be used to traverse set of code for the specified number of
times.
 It should be used if the number of iterations is known otherwise use while
loop. This means for loop is used when you already know how many times
you want to execute a block of code.
 Syntax :
for(initialization; condition; increment/decrement)
{
//code to be executed
}
For Loop

 Example :
<?php
for($n=1;$n<=10;$n++)
{
echo "$n<br/>";
}
?>
While Loop

 PHP while loop can be used to traverse set of code like for loop.
 The while loop executes a block of code repeatedly until the condition is
FALSE. Once the condition gets FALSE, it exits from the body of loop.
 It should be used if the number of iterations is not known.
 The while loop is also called an Entry control loop because the condition is
checked before entering the loop body. This means that first the condition is
checked. If the condition is true, the block of code will be executed.
 Syntax : while(condition) while(condition):
{ //code to be executed //code to be executed
} endwhile;
While Loop

 Example:
<?php
$n=1;
while($n<=10)
{
echo "$n<br/>";
$n++;
}
?>
Do While Loop

 PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-
while loop is guaranteed to run at least once.
 The PHP do-while loop is used to execute a set of code of the program several times. If
you have to execute the loop at least once and the number of iterations is not even fixed,
it is recommended to use the do-while loop.
 It executes the code at least one time always because the condition is checked after
executing the code.It is known as Exit Control Loop
 The do-while loop is very much similar to the while loop except the condition check. The
main difference between both loops is that while loop checks the condition at the
beginning, whereas do-while loop checks the condition at the end of the loop.
 Syntax: do{ //code to be executed
}while(condition);
Do While Loop

 Example:
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
THANK YOU

You might also like