Вы находитесь на странице: 1из 38

MODULE 4

PHP
INTRODUCTION

 PHP : Hypertext Pre-Processor,


 Open source general-purpose scripting language.
 It is a cross-platform,
 HTML-embedded server-side scripting language and is especially suited for web
development.
FEATURES CONT…

 PHP is an open source software.


 PHP is a server-side scripting language and is used for websites and the web
applications.
 PHP scripts are executed on the server.
 PHP supports a wide range of databases.
 PHP runs on various platforms like Linux, Windows, Unix etc.
 PHP supports most web servers (for example Apache, IIS).
 PHP converses with several network protocols.
INSTALLATION

 XAMPP Package : Installation of Apache, PHP, MySQL, and PHPMyAdmin


 https://www.apachefriends.org/download.html
 Open a web browser and type localhost in the address bar to check successfull
installation.
 Create a php file save file with .php extension in htdocs folder.
 To run php file: http://localhost/file.php
 Syntax : <?php
.
.
.
?>
HOW IT WORKS?

Request page: Hello.php


Web Server Request Data
Client/
Web PHP Response Data MySQL
Browser Response page:
Interpreter
HTML Output

Request File
File
Response Files Server
ECHO / PRINT

 PHP echo statement can be used to print string, multi line strings,
escaping characters, variable, array etc.
 Returns nothing.
 Syntax : void echo ( string $arg1 [, string $... ] )  echo "Hello by PHP echo";

 PHP print statement can be used to print string, multi line strings,
escaping characters, variable, array etc.
 Returns 1.
 Syntax: int print(string $arg)  print "Hello by PHP print ";
VARIABLES
 A variable is a temporary storage that is used to store data temporarily.
 In PHP, a variable is declared using $ sign followed by variable name.
 Syntax : $variablename=value;
Variable:
 Variable: Rules Declaring string, integer
 Variable names begin with a dollar sign ( $ ). and float
Eg : $str="hello";
 PHP variables must start with letter or underscore only. $x=200;
 PHP variable can't be start with numbers and special symbols $y=44.6;

 variable names are case sensitive.


 PHP is a loosely typed language as it automatically converts the variable to its
correct data type.
$ 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.
DATA TYPES

 Scalar Types
 boolean
 integer
 float
 String

 Compound Types
 array
 object
OPERATORS

 Unary Operators: works on single operands such as ++, -- etc.


 Binary Operators: works on two operands such as binary
 Arithmetic Operator : +, -, *, / ,%
 Assignment Operator : =,+=,-=,*=, /=
 Comparison Operator: <, >, <=, >=, ==, !=
 Logical Operator : &&, ||, !
 Ternary Operators: works on three operands such as “(condition)?(exp1):(exp2)".
COMMENTS

 Single Line Comments


 //Comments are here
 #Comments are here

 Multi-Line Comments
 /* Comments are here */
CONTROL STATEMENTS

1. if- else : Example :


if(condition){
$num=12;
// do something if($num%2==0){
}else{ echo "$num is even number";
}else{
// do something echo "$num is odd number";
} }
2. switch Example :
$OE=“WDA”;
switch(expression){
case value1: switch($OE){
//code to be executed case ”WDA”:
break;
echo(“Welcome to Web"); break;

case value2: case ”cpp”:


//code to be executed echo(“welcome to cpp"); break;
break; case ”signals:
...... echo(“welcome to signals"); break;
default: default:
code to be executed } echo(“all welcome");
}
3. while
Example :
while(condition):
//code to be executed $n=1;
while($n<=10){
echo "$n";
endwhile; (optional) $n++;
}
4. do…..while Example :
do{
$n=1;
//code to be executed do{
}while(condition); echo "$n<br/>";
$n++;
}while($n<=10);
5. for Example :
for(initialization; condition;
couting): for($n=1;$n>5;$n++){
echo "$n";
//code to be executed }
6. break Example :
if()/while()/for()/switch(){ for($i=1;$i<=10;$i++){
break echo "$i <br/>";
} if($i==5){
break;

• Break statement breaks the execution of current for, while, do-while,


switch and for-each loop.
• Break: inside switch statement.
FUNCTIONS
1.Without Arguments
Syntax:
i) function display(){
function functionname(){
echo “hello”
//code to be executed
}
}
display()
function_name()
ii) function data_pass(){
return “hello”;
}
$msg=data_pass();
2. Call By Value 3. Call By Reference
function myname($name){ function myname(&$name){
echo "Hello $name"; $name=“TY”;
} echo "Hello $name";
$n=“All"; }
myname("Sonoo"); $n=“All";
myname($n); myname($n);
4. Default Argument 5.Variable Length Argument Function
• use 3 ellipses (dots) before the argument
name.
function myname($class=“TY”, $sub=“OE”)
Syntax : function add(...$numbers) {
{ echo "Hello”. $class.$sub;
$sum = 0;
}
foreach ($numbers as $n) {
$c=“civil”; $s=“phy”;
$sum += $n;
myname($c,$s);
}
myname($c);
return $sum;
myname();
}
ARRAYS
1. Indexed Array :
 PHP index is represented by number starts from 0.
 Example :
 $branch=array(“ELN","Mech",“CSE");  branch[0]/[1]/[2]
 $branch[0]=“ELN“; $branch[1]="Mech“; $branch[2]=“CSE");  branch[0]/[1]/[2]
 Traverse :foreach($branch as $b) {}
 Size : count($branch);
 Ordering : sort($branch); rsort($branch);
 Printing : print_r($branch)
2. Associative Array :
 associate name/label with each array elements in PHP using => symbol.
 Example :
 $city=array(“MH"=>“Mumbai",“KN"=>“Mysore",“WB"=>“Kolkata");
$city[“MH”]
 $city[“MH“]=“Mumbai“;$city[“KN“]=“Mysore“;$city[“WB“]=“Kolk
ata"; 
$city[“KN”]
 Traverse :foreach($city as $key => $val) {}
 Size : count($city);
 Ordering : values: asort($city); arsort($city); key: ksort($city);
3. Multidimensional Array :
 multidimensional array is also known as array of arrays.
 It allows to store tabular data in an array represented by row * column.
 Example :
$students = array
(
array(1,“ABC",9.5),
array(2,“XYZ",8.5),
array(3,“PQR",9.0) );
EXTRA METHODS

 Add Elements :array_push($array, $elements)


 Remove Elements : array_pop($array)
 Add/ Remove in Middle : array_splice( $array, position, no_of
elements_to_remove, $arrayToAdd )
 Merging : array_merge($array1,$array2);
STRINGS

 Create String : $str=“mystring”; / ‘mystring’


 Escape Sequence : \n;\t \v \\ \$ \”
 Length : strlen($str)
 Assessing Characters : $str[5]
 Searching within string : strstr(original_string, text_to_search);
 Locating text in string :
 First :strpos(string, text_to_locate);
 Last : strrpos(string, text_to_locate);
 Number of Occurrences : substr_count(original_string, text_to_count );
 Replace string : str_replace(original_text, new_text, string);
 Replace portion of string : substr_replace(string,
new_text,index,Next_index);
 To Uppercase : strtoupper(string)
 To Lowercase : strtolower(string)
 First Letter Uppercase : ucfirst(string)
 First Letter Lowerca,se : lcfirst(string)
 Removing White spaces : trim(string)/ ltrim(string)/ rtrim(string)
 Padding : str_pad(string, length, string_to_add, alignment)
STR_PAD_RIGHT/ STR_PAD_LEFT / STR_PAD_BOTH

 Wrap : wordwrap(string, length)


FORMS
FILE HANDLING
 Open File : fopen(filename, mode) :
 r : Opens file in read-only mode.
 r+ :Opens file in read-write mode.
 w:Opens file in write-only mode.
 w+ : Opens file in read-write mode.
 a :Opens file in write-only mode. It places the file pointer to the end of the file. If file is
not found, it creates a new file.
 a+ :Opens file in read-write mode. It places the file pointer to the end of the file. If file is
not found, it creates a new file.
 Read File :
 fread(file_pointer, size) : to read data of the file.

 fgets(file_pointer) : to read single line from the file.

 fgetc(file_pointer) : to read single character from the file.


 Write File :
 fwrite(file_pointer, content) : to write content of the string into file.

 Append to File :
 fwrite(file_pointer, content) : to write content of the string into file.

 Delete File :
 unlink(file_name) : to delete file.
 fclose(file_pointer) : close file
 feof(file_pointer) : reach end of file
 filesize(file_name) : size of file.
COOKIE

 Cookies are a mechanism for storing data in the remote browser and thus tracking
or identifying return users.
 A cookie can only be read from the domain that it has been issued from.
 Cookie is created at server side and saved to client browser.
 Each time when client sends request to the server, cookie is embedded with request.
1. Request

Client/ 2. Response + Cookies


Web Server
Browser
3. Request + Cookies
 setcookie : function is used to set cookie with HTTP response.
 Syntax : setcookie("CookieName", "CookieValue");

 $_COOKIE : super global variable is used to get cookie.


 Syntax : $_COOKIE("CookieName");

 Delete Cookie :
 Syntax : setcookie("CookieName", time()-3600);
DATABASE CONNECTIVITY

 Connect to Database :
 Syntax :mysqli_connect (server, username, password,database)
 Create Table :
 $sql = "create table student(id INT, name VARCHAR(20))”
 Syntax :mysqli_query($conn, $sql) ;
 Insert Record Table :
 $sql = “insert into table values(1,”ABC”)”
 Syntax :mysqli_query($conn, $sql) ;
DATABASE CONNECTIVITY

 Retrieve Records from Table :


 $sql = “Select * from students”;
 Syntax :mysqli_query($conn, $sql) ;
while($row = mysqli_fetch_assoc($retval)){
echo $row[“rno”] . $row[‘name’];
}
DIE / EXIT METHOD

 die(error_message)/ exit(error_message) function is used to display a message and


exit the script.
 It may be used to print alternate message .
 Instead of showing error it will show the user friendly message.

Вам также может понравиться