SlideShare uma empresa Scribd logo
1 de 103
P.H.P.
Full forms
 Hyper text pre processor
 Personal home page
Use of php
 PHP is a powerful tool for making dynamic and
interactive Web pages.
 PHP is the widely-used, free, and efficient
alternative to competitors such as Microsoft's
ASP.
Developed by
 Main developer
 Rasmus ladroff 1995
 Modification by 1997
 Zeev suraski
 Andi gotmans
Work on client server architecture
 Client sends request to server.
 Server accept request and reply response in
HTML format
advantages
 Use for code security
 Use for create dynamic web pages
 For power full database connectivity
 PHP is an open source software
 PHP is free to download and use
P.H.P. file
 PHP files can contain text, HTML tags and scripts
 PHP files are returned to the browser as plain
HTML
 PHP files have a file extension of ".php", ".php3",
or ".phtml
Why P.H.P.
 PHP runs on different platforms (Windows, Linux,
Unix, etc.)
 PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
 PHP is FREE to download from the official PHP
resource: www.php.net
 PHP is easy to learn and runs efficiently on the
server side
Server architecture
Server information
 Apache server use to compile P.H.P. code.
 Apache server compile php code and returns
output in html format to browser.
 In entire document all the html and java script
code execute by client browser and P.H.P. code
compile by server
Working with server
 P.H.P. files are run on apache server.
save all the P.H.P. files in document root
default save in c:xampphtdocs
Server software
 Xampp
combination of apache server and mysql database.
Wampp
apaches server software.
Comment in php
 // single line comment
 /* */ multiline comment
Tag of php
// starting tag of php
<?php
 // ending tag of php
?>
Other style to write P.H.P. code
Short hand style
<?
?>
script type style
<script language=“php”>
</script>
Printing content in page.
 Use “echo” function or “print” function
 Ex. echo” welcome to P.H.P. “;
Variables
 All the variables declare with “dollar ” sign.
Ex. $a = 10;
P.H.P. is loosely typed language
 In PHP, a variable does not need to be declared
before adding a value to it.
 In the example above, notice that we did not have
to tell PHP which data type the variable is.
 PHP automatically converts the variable to the
correct data type, depending on its value.
 In a strongly typed programming language, you
have to declare (define) the type and name of the
variable before using it.
To run P.H.P. code
 Write In address bar of web browser.
http://localhost/foldername/filename
Localhost : default host name of P.H.P. server
P.H.P. run on port no. 80
Example of variable
 $a = 10;
 All data type accept with same variable.
 Default data type is variant.
 gettype() : use to get data type of
variables.
Must remember
P.H.P. is totally case sensitive language.
all the statements of P.H.P. is terminated with semi
colon ( ; )
must save all the files with ( .php ) extension
concatenation of two string with (.) dot sign
Valid variable names.
 $a valid name.
 $1 not valid name
 $asc_asd valid name
 $_aaa valid name
 $~aa not valid name
 $aa-aa not valid name
 Note : allows only a-z, A-Z, 1-9 , _ in variable
name
Type casting of variables
 Variable (data type to cast) variable.
 Ex.
$abc = “100”;
$total = (integer) $abc;
operators
 Relational
 Arithmetic
 Logical
 Assignment
 Increment / decrement
Relational operators
 < less than
 > greater than
 <= less than or equal
 => greater than and equal
 == equals
 != not equals
 <> not equals
Arithmetic operators
 + summation
 - subtraction
 * multiplication
 / division
 % modulation
logical operators
 || or operator
 && and operator
 ! Not operator
|| operator ( chart )
Condition 1 Condition 2 Result
True False True
False True True
False False False
True True True
&& operator ( chart )
Condition 1 Condition 2 Result
True False False
False True False
False False False
True True True
! Not ( chart )
Condition 1 Condition 2 Result
True False False
False True False
True True False
False False True
Assignment operator
= use as assignment operator.
, use as special operator
Increment and decrement
operator
++ use as increment operator
- - use as decrement operator
Conditional statements
 If
 If else
 If else if
 Switch case
If condition
 If(condition)
{
executable part
}
If else
 if(condition )
{
Executable part if condition is true.
}
else
{
execute when condition is false.
}
Nested if condition
 if( condition 1)
{
if(condition 2)
{
executable part
}
}
Switch case
 Switch (expression)
{
case : // match 1
{
executable part;
break;
}
case : // match 2
{
executable part;
break;
}
default
{
}
}
Array in P.H.P.
 Simple array
$a = array();
 $a = array(‘abc’ , ’def’ , ’ghi’ , ’jkl’);
 Associate array
$a = array(“name”=>”Abc”, “city”=>”rajkot”);
Array continue. . . .
 Numeric array - An array with a numeric index
 Associative array - An array where each ID key
is associated with a value
 Multidimensional array - An array containing
one or more arrays
Looping structure
• For loop
• While loop
Entry
Control loop
• Do while loop
Exit control
loop
• For each loopfor each
While loop
 while( condition )
{
executable part,
increment / decrement
}
While loop example
 I = 0;
 while( I < 5)
{
echo I;
}
o/p
0
1
2
3
4
Do while loop
 do
{
executable part;
increment / decrement
}while(condition);
For loop
 for( initialization ; condition ;
increment/decrement)
{
executable part;
}
For each loop
 Use to print array elements
foreach( array variable as variable )
{
executable parts
}
For each loop
 $student =
array(“kalpesh”,”kaushik”,”virendra”,”sanjay”,”hite
sh”);
foreach ( $student as $s)
{
echo “name of student is ”.$s . “<br>”;
}
Other keywords
 break
 continue
 exit
Scope of variables.
 Global
 Local
 Static
 Parameter
Functions in P.H.P.
 Simple function
function functionName()
{
code to be executed;
}
Functions with parameters
 <?php
function writeName($fname)
{
echo $fname ;
}
Function with return value
 <?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
 ?>
Math functions
 abs()
Returns absolute value.
 base_convert()
convert a number from one to another
Math continue……
 bindec()
convert binary number to decimal numbers.
 ceil()
return nearest top integer.
 floor()
return nearest integer from down side
Math functions….
 min()
 max()
 pow()
 pi()
 sqrt()
String functions
 trim() remove spaces
 rtrim() remove space from right side
 ltrim() remove space from left side
 strtolower convert string to lower case
 strtoupper convert string to upper
case
 substr creating sub string
 strrev returns string in reverse
 strlen returns the length of string
 ord ASCII value of characters.
String functions
 print print any string
 printf print string
 join convert string in to
array
 chr ASCII values
 wordwrap(string,width,break,cut) word wraping
 strpos return index of given
char
 similar_text(string1,string2,percent) find similarity in
2 strings
 str_replace(find,replace,string,count) replace in string
 str_ireplace(find,replace,string,count) case
insensitive replace
 str_word_count(string,return,char) count total
words
Array functions
Date functions
 date()
 getdate()
 time()
 localtime()
P.H.P. form handling. (example)
 Welcome.html
 <form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
< input type="submit" />
< /form>
Data receive methods
 Data sending methods
 GET
 POST
Receive data with all methods
 Welcome <?php echo $_POST["fname"]; ?>!<br
/>
You are <?php echo $_POST["age"]; ?> years old
 Welcome <?php echo $_GET["fname"]; ?>!<br />
You are <?php echo $_GET["age"]; ?> years old..
 Welcome <?php echo $_REQUEST["fname"];
?>!<br />
You are <?php echo $_REQUEST["age"]; ?>
years old.
Receiving parameters
 Data.php
Welcome <?php echo $_POST["fname"]; ?>!<br
/>
You are <?php echo $_POST["age"]; ?> years
old.
Include keyword
 To include and created file in P.H.P. code
ex.
include (“connection.php”);
File handling in P.H.P.
 <?php
$file=fopen("welcome.txt","r");
 ?>
 fopen() use to open any file,
in fopen function have two parameters first is file
name and second is opening mode of file.
List of modes.
 Modes Description
 r Read only. Starts at the beginning of
the file
 r+ Read/Write. Starts at the beginning of
the file.
 w Write only. Opens and clears the
contents of file; or creates a new
file if it doesn't exist
 w+ Read/Write. Opens and clears the
contents of file; or creates a new file if
it doesn't exist
File mode cont……
 a Append. Opens and writes to the end
of the file or creates a new file if it doesn't
exist
 a+ Read/Append. Preserves file content
by writing to the end of the file
 x Write only. Creates a new file. Returns
FALSE and an error if file already exists
 x+ Read/Write. Creates a new file.
Returns FALSE and an error if file already
exists
 <?php
$file=fopen("welcome.txt","r") or exit("Unable to open
file!");
?>
 Close file
fclose($file);
Find end of file
The feof() function checks if the "end-of-file"
(EOF) has been reached.
The feof() function is useful for looping through
data of unknown length.
 if (feof($file)) echo "End of file";
Read lines from text file
 <?php
$file = fopen("welcome.txt", "r") or exit("Unable to open
file!");
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
Read characters from text file
 <?php
$file=fopen("welcome.txt","r") or exit("Unable to open
file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
File functions
 fopen()
 fclose()
 fgetc()
 fgets()
 fclose()
 copy()
 file()
File upload
 Select file from location
 Print information of file
 Copy file in target folder
 Print message
Cookies in P.H.P.
 setcookie(name, value, expire, path, domain);
 Name = name of cookies
 Value = value of cookies
 Expire = expire date of cookies
 Path = cookie storage path
 Domain = domain of cookies
Cookies Example
 <?php
setcookie("user", “demo", time()+3600);
?>
 Another example of cookies
 <?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
Note : value of $expire is 1 month.
Read cookies
 <?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
Another example of cookies
 <?php
if (isset($_COOKIE["user"]))
echo "Welcome " .
$_COOKIE["user"] ;
else
echo "Welcome guest!<br />";
?>
How to delete cookies
 <?php
// specify time in negative
setcookie("user", "", time()-3600);
?>
 Note : no any other way to delete cookies from
server side.
Session
 When you are working with an application, you
open it, do some changes and then you close it.
This is much like a Session. The computer knows
who you are. It knows when you start the
application and when you end. But on the internet
there is one problem: the web server does not
know who you are and what you do because the
HTTP address doesn't maintain state.
 Note : session use to maintain state of user.
Creating a new session in P.H.P.
 $_SESSION[“ name of your session ”] = “value of
session”

Access session
 $variable name = $_SESSION[“session name”];
 Delete session
 unset(“name of your session”);
Isset function
 isset function use to check variable is set or not.
 isset function returns Boolean values.
 If variable is isset function returns true either
returns false.
Error handling in P.H.P.
 <?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>
Try catch block
 function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
try
{
checkNum(2);
echo 'If you see this, the number is 1 or below';
}
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
Database
Table
2
Table
1
Databas
e
How to connect with database
???
 Use mysql_connect()
$con =
mysql_connect(“hostname",“username",“password")
;
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
Default values
 Host = localhost
 Username= root
 Password = “”(Null)
For closing the connection
<?php
$con = mysql_connect("localhost",“root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_close($con);
?>
Select database from entire
system
 mysql_select_db(“database name", [ reference of
database]);
Insert values in table
 INSERT INTO table_name VALUES (value1,
value2, value3,...)
 Ex .
 Insert into demo ( 10,’abc’,’rajkot’)
Example to insert data in table
 <?php
$con = mysql_connect("localhost",“root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
Fetch data from table.
 SELECT column_name(s) FROM table_name
 Or
 Select * from table name where condition.
Where clause
 $con = mysql_connect("localhost",“root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons
WHERE FirstName=‘abc'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
Update query
 mysql_query("UPDATE Persons SET Age=36
WHERE FirstName=‘amit' AND
LastName=‘mehta'");
Delete query
 DELETE FROM table_name
WHERE some_column = some_value
 Ex. Delete * from table1 where username =
‘ankit’;
Other data base functions……
 mysql_affected_rows()
Returns no of rows affected by query.
mostly use to update and delete querys
Example
 <?php
$con =
mysql_connect("localhost","mysql_user","mysql_pwd"
);
if (!$con)
{
die("Could not connect: " . mysql_error());
}
mysql_select_db("mydb");
mysql_query("DELETE FROM mytable WHERE id <
5");
$rc = mysql_affected_rows();
echo "Records deleted: " . $rc;
mysql_close($con);
?>
mysql_fetch_array()
 Use to
 After the data is retrieved, this function moves to
the next row in the recordset. Each subsequent
call to mysql_fetch_array() returns the next row in
the recordset retrieve data in array format.
Example
 <?php
$con = mysql_connect("localhost", “root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * from Person WHERE
Lastname='Refsnes'";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
mysql_close($con);
?>
Mode of arrays
 mysql_fetch_array($result,MYSQL_NUM)
 mysql_fetch_array($result,MYSQL_ASSOC)
 mysql_fetch_array($result,MYSQL_BOTH)
 Note : default mode is both
mysql_num_rows()
 The mysql_num_rows() function returns the
number of rows in a recordset.
This function returns FALSE on failure
$sql = "SELECT * FROM person";
$result = mysql_query($sql,$con);
echo mysql_num_rows($result);
Errors in mysql
 mysql_error()
 mysql_errno()
SERVER object
 Methods
$_SERVER['DOCUMENT_ROOT']
Returns path of document root
$_SERVER['HTTP_USER_AGENT']
returns browser information
$_SERVER['REMOTE_PORT']
returns port number
$_SERVER['REMOTE_ADDR']
returns ip address of server
$_SERVER['SERVER_NAME']
returns name of server
$_SERVER['SCRIPT_FILENAME']
returns path of current file with file name

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Css Ppt
Css PptCss Ppt
Css Ppt
 
Php
PhpPhp
Php
 
PHP
PHPPHP
PHP
 
Java script
Java scriptJava script
Java script
 
CSS for Beginners
CSS for BeginnersCSS for Beginners
CSS for Beginners
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
Lesson 2 php data types
Lesson 2   php data typesLesson 2   php data types
Lesson 2 php data types
 
Java script
Java scriptJava script
Java script
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
 
Javascript
JavascriptJavascript
Javascript
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 

Destaque

Destaque (14)

PHP 7 new engine
PHP 7 new enginePHP 7 new engine
PHP 7 new engine
 
PHP 7 performances from PHP 5
PHP 7 performances from PHP 5PHP 7 performances from PHP 5
PHP 7 performances from PHP 5
 
Php internal architecture
Php internal architecturePhp internal architecture
Php internal architecture
 
Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)
 
PHP WTF
PHP WTFPHP WTF
PHP WTF
 
Internet of Things With PHP
Internet of Things With PHPInternet of Things With PHP
Internet of Things With PHP
 
PHP, Under The Hood - DPC
PHP, Under The Hood - DPCPHP, Under The Hood - DPC
PHP, Under The Hood - DPC
 
PHP Optimization
PHP OptimizationPHP Optimization
PHP Optimization
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
 
How PHP Works ?
How PHP Works ?How PHP Works ?
How PHP Works ?
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
 
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
[Community Open Camp] 給 PHP 開發者的 VS Code 指南[Community Open Camp] 給 PHP 開發者的 VS Code 指南
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
 
LaravelConf Taiwan 2017 開幕
LaravelConf Taiwan 2017 開幕LaravelConf Taiwan 2017 開幕
LaravelConf Taiwan 2017 開幕
 
Route 路由控制
Route 路由控制Route 路由控制
Route 路由控制
 

Semelhante a Php

course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpoint
webhostingguy
 
Php1
Php1Php1
Php1
Reka
 
Php1(2)
Php1(2)Php1(2)
Php1(2)
Reka
 

Semelhante a Php (20)

Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
Day1
Day1Day1
Day1
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
PHP-Part1
PHP-Part1PHP-Part1
PHP-Part1
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics
 
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
 
course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpoint
 
Free PHP Book Online | PHP Development in India
Free PHP Book Online | PHP Development in IndiaFree PHP Book Online | PHP Development in India
Free PHP Book Online | PHP Development in India
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting language
 
Php intro by sami kz
Php intro by sami kzPhp intro by sami kz
Php intro by sami kz
 
Php advance
Php advancePhp advance
Php advance
 
Php1
Php1Php1
Php1
 
Php1(2)
Php1(2)Php1(2)
Php1(2)
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Php essentials
Php essentialsPhp essentials
Php essentials
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 

Mais de Shyam Khant (7)

Unit2.data type, operators, control structures
Unit2.data type, operators, control structuresUnit2.data type, operators, control structures
Unit2.data type, operators, control structures
 
Introducing to core java
Introducing to core javaIntroducing to core java
Introducing to core java
 
C++
C++C++
C++
 
C++ theory
C++ theoryC++ theory
C++ theory
 
C Theory
C TheoryC Theory
C Theory
 
SQL
SQLSQL
SQL
 
Hashing 1
Hashing 1Hashing 1
Hashing 1
 

Último

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Último (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 

Php

  • 2. Full forms  Hyper text pre processor  Personal home page
  • 3. Use of php  PHP is a powerful tool for making dynamic and interactive Web pages.  PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
  • 4. Developed by  Main developer  Rasmus ladroff 1995  Modification by 1997  Zeev suraski  Andi gotmans
  • 5. Work on client server architecture  Client sends request to server.  Server accept request and reply response in HTML format
  • 6. advantages  Use for code security  Use for create dynamic web pages  For power full database connectivity  PHP is an open source software  PHP is free to download and use
  • 7. P.H.P. file  PHP files can contain text, HTML tags and scripts  PHP files are returned to the browser as plain HTML  PHP files have a file extension of ".php", ".php3", or ".phtml
  • 8. Why P.H.P.  PHP runs on different platforms (Windows, Linux, Unix, etc.)  PHP is compatible with almost all servers used today (Apache, IIS, etc.)  PHP is FREE to download from the official PHP resource: www.php.net  PHP is easy to learn and runs efficiently on the server side
  • 10. Server information  Apache server use to compile P.H.P. code.  Apache server compile php code and returns output in html format to browser.  In entire document all the html and java script code execute by client browser and P.H.P. code compile by server
  • 11. Working with server  P.H.P. files are run on apache server. save all the P.H.P. files in document root default save in c:xampphtdocs
  • 12. Server software  Xampp combination of apache server and mysql database. Wampp apaches server software.
  • 13. Comment in php  // single line comment  /* */ multiline comment
  • 14. Tag of php // starting tag of php <?php  // ending tag of php ?>
  • 15. Other style to write P.H.P. code Short hand style <? ?> script type style <script language=“php”> </script>
  • 16. Printing content in page.  Use “echo” function or “print” function  Ex. echo” welcome to P.H.P. “;
  • 17. Variables  All the variables declare with “dollar ” sign. Ex. $a = 10;
  • 18. P.H.P. is loosely typed language  In PHP, a variable does not need to be declared before adding a value to it.  In the example above, notice that we did not have to tell PHP which data type the variable is.  PHP automatically converts the variable to the correct data type, depending on its value.  In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.
  • 19. To run P.H.P. code  Write In address bar of web browser. http://localhost/foldername/filename Localhost : default host name of P.H.P. server P.H.P. run on port no. 80
  • 20. Example of variable  $a = 10;  All data type accept with same variable.  Default data type is variant.  gettype() : use to get data type of variables.
  • 21. Must remember P.H.P. is totally case sensitive language. all the statements of P.H.P. is terminated with semi colon ( ; ) must save all the files with ( .php ) extension concatenation of two string with (.) dot sign
  • 22. Valid variable names.  $a valid name.  $1 not valid name  $asc_asd valid name  $_aaa valid name  $~aa not valid name  $aa-aa not valid name  Note : allows only a-z, A-Z, 1-9 , _ in variable name
  • 23. Type casting of variables  Variable (data type to cast) variable.  Ex. $abc = “100”; $total = (integer) $abc;
  • 24. operators  Relational  Arithmetic  Logical  Assignment  Increment / decrement
  • 25. Relational operators  < less than  > greater than  <= less than or equal  => greater than and equal  == equals  != not equals  <> not equals
  • 26. Arithmetic operators  + summation  - subtraction  * multiplication  / division  % modulation
  • 27. logical operators  || or operator  && and operator  ! Not operator
  • 28. || operator ( chart ) Condition 1 Condition 2 Result True False True False True True False False False True True True
  • 29. && operator ( chart ) Condition 1 Condition 2 Result True False False False True False False False False True True True
  • 30. ! Not ( chart ) Condition 1 Condition 2 Result True False False False True False True True False False False True
  • 31. Assignment operator = use as assignment operator. , use as special operator
  • 32. Increment and decrement operator ++ use as increment operator - - use as decrement operator
  • 33. Conditional statements  If  If else  If else if  Switch case
  • 35. If else  if(condition ) { Executable part if condition is true. } else { execute when condition is false. }
  • 36. Nested if condition  if( condition 1) { if(condition 2) { executable part } }
  • 37. Switch case  Switch (expression) { case : // match 1 { executable part; break; } case : // match 2 { executable part; break; } default { } }
  • 38. Array in P.H.P.  Simple array $a = array();  $a = array(‘abc’ , ’def’ , ’ghi’ , ’jkl’);  Associate array $a = array(“name”=>”Abc”, “city”=>”rajkot”);
  • 39. Array continue. . . .  Numeric array - An array with a numeric index  Associative array - An array where each ID key is associated with a value  Multidimensional array - An array containing one or more arrays
  • 40. Looping structure • For loop • While loop Entry Control loop • Do while loop Exit control loop • For each loopfor each
  • 41. While loop  while( condition ) { executable part, increment / decrement }
  • 42. While loop example  I = 0;  while( I < 5) { echo I; } o/p 0 1 2 3 4
  • 43. Do while loop  do { executable part; increment / decrement }while(condition);
  • 44. For loop  for( initialization ; condition ; increment/decrement) { executable part; }
  • 45. For each loop  Use to print array elements foreach( array variable as variable ) { executable parts }
  • 46. For each loop  $student = array(“kalpesh”,”kaushik”,”virendra”,”sanjay”,”hite sh”); foreach ( $student as $s) { echo “name of student is ”.$s . “<br>”; }
  • 47. Other keywords  break  continue  exit
  • 48. Scope of variables.  Global  Local  Static  Parameter
  • 49. Functions in P.H.P.  Simple function function functionName() { code to be executed; }
  • 50. Functions with parameters  <?php function writeName($fname) { echo $fname ; }
  • 51. Function with return value  <?php function add($x,$y) { $total=$x+$y; return $total; }  ?>
  • 52. Math functions  abs() Returns absolute value.  base_convert() convert a number from one to another
  • 53. Math continue……  bindec() convert binary number to decimal numbers.  ceil() return nearest top integer.  floor() return nearest integer from down side
  • 54. Math functions….  min()  max()  pow()  pi()  sqrt()
  • 55. String functions  trim() remove spaces  rtrim() remove space from right side  ltrim() remove space from left side  strtolower convert string to lower case  strtoupper convert string to upper case  substr creating sub string  strrev returns string in reverse  strlen returns the length of string  ord ASCII value of characters.
  • 56. String functions  print print any string  printf print string  join convert string in to array  chr ASCII values  wordwrap(string,width,break,cut) word wraping  strpos return index of given char  similar_text(string1,string2,percent) find similarity in 2 strings  str_replace(find,replace,string,count) replace in string  str_ireplace(find,replace,string,count) case insensitive replace  str_word_count(string,return,char) count total words
  • 58. Date functions  date()  getdate()  time()  localtime()
  • 59. P.H.P. form handling. (example)  Welcome.html  <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> < input type="submit" /> < /form>
  • 60. Data receive methods  Data sending methods  GET  POST
  • 61. Receive data with all methods  Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old  Welcome <?php echo $_GET["fname"]; ?>!<br /> You are <?php echo $_GET["age"]; ?> years old..  Welcome <?php echo $_REQUEST["fname"]; ?>!<br /> You are <?php echo $_REQUEST["age"]; ?> years old.
  • 62. Receiving parameters  Data.php Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old.
  • 63. Include keyword  To include and created file in P.H.P. code ex. include (“connection.php”);
  • 64. File handling in P.H.P.  <?php $file=fopen("welcome.txt","r");  ?>  fopen() use to open any file, in fopen function have two parameters first is file name and second is opening mode of file.
  • 65. List of modes.  Modes Description  r Read only. Starts at the beginning of the file  r+ Read/Write. Starts at the beginning of the file.  w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist  w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist
  • 66. File mode cont……  a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist  a+ Read/Append. Preserves file content by writing to the end of the file  x Write only. Creates a new file. Returns FALSE and an error if file already exists  x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
  • 67.  <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); ?>  Close file fclose($file);
  • 68. Find end of file The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length.  if (feof($file)) echo "End of file";
  • 69. Read lines from text file  <?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?>
  • 70. Read characters from text file  <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?>
  • 71. File functions  fopen()  fclose()  fgetc()  fgets()  fclose()  copy()  file()
  • 72. File upload  Select file from location  Print information of file  Copy file in target folder  Print message
  • 73. Cookies in P.H.P.  setcookie(name, value, expire, path, domain);  Name = name of cookies  Value = value of cookies  Expire = expire date of cookies  Path = cookie storage path  Domain = domain of cookies
  • 74. Cookies Example  <?php setcookie("user", “demo", time()+3600); ?>  Another example of cookies  <?php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ?> Note : value of $expire is 1 month.
  • 75. Read cookies  <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?>
  • 76. Another example of cookies  <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] ; else echo "Welcome guest!<br />"; ?>
  • 77. How to delete cookies  <?php // specify time in negative setcookie("user", "", time()-3600); ?>  Note : no any other way to delete cookies from server side.
  • 78. Session  When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.  Note : session use to maintain state of user.
  • 79. Creating a new session in P.H.P.  $_SESSION[“ name of your session ”] = “value of session” 
  • 80. Access session  $variable name = $_SESSION[“session name”];  Delete session  unset(“name of your session”);
  • 81. Isset function  isset function use to check variable is set or not.  isset function returns Boolean values.  If variable is isset function returns true either returns false.
  • 82. Error handling in P.H.P.  <?php if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?>
  • 83. Try catch block  function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } try { checkNum(2); echo 'If you see this, the number is 1 or below'; } catch(Exception $e) { echo 'Message: ' .$e->getMessage(); }
  • 85. How to connect with database ???  Use mysql_connect() $con = mysql_connect(“hostname",“username",“password") ; if (!$con) { die('Could not connect: ' . mysql_error()); }
  • 86. Default values  Host = localhost  Username= root  Password = “”(Null)
  • 87. For closing the connection <?php $con = mysql_connect("localhost",“root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_close($con); ?>
  • 88. Select database from entire system  mysql_select_db(“database name", [ reference of database]);
  • 89. Insert values in table  INSERT INTO table_name VALUES (value1, value2, value3,...)  Ex .  Insert into demo ( 10,’abc’,’rajkot’)
  • 90. Example to insert data in table  <?php $con = mysql_connect("localhost",“root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con); ?>
  • 91. Fetch data from table.  SELECT column_name(s) FROM table_name  Or  Select * from table name where condition.
  • 92. Where clause  $con = mysql_connect("localhost",“root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons WHERE FirstName=‘abc'"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br />"; }
  • 93. Update query  mysql_query("UPDATE Persons SET Age=36 WHERE FirstName=‘amit' AND LastName=‘mehta'");
  • 94. Delete query  DELETE FROM table_name WHERE some_column = some_value  Ex. Delete * from table1 where username = ‘ankit’;
  • 95. Other data base functions……  mysql_affected_rows() Returns no of rows affected by query. mostly use to update and delete querys
  • 96. Example  <?php $con = mysql_connect("localhost","mysql_user","mysql_pwd" ); if (!$con) { die("Could not connect: " . mysql_error()); } mysql_select_db("mydb"); mysql_query("DELETE FROM mytable WHERE id < 5"); $rc = mysql_affected_rows(); echo "Records deleted: " . $rc; mysql_close($con); ?>
  • 97. mysql_fetch_array()  Use to  After the data is retrieved, this function moves to the next row in the recordset. Each subsequent call to mysql_fetch_array() returns the next row in the recordset retrieve data in array format.
  • 98. Example  <?php $con = mysql_connect("localhost", “root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("test_db",$con); $sql = "SELECT * from Person WHERE Lastname='Refsnes'"; $result = mysql_query($sql,$con); print_r(mysql_fetch_array($result)); mysql_close($con); ?>
  • 99. Mode of arrays  mysql_fetch_array($result,MYSQL_NUM)  mysql_fetch_array($result,MYSQL_ASSOC)  mysql_fetch_array($result,MYSQL_BOTH)  Note : default mode is both
  • 100. mysql_num_rows()  The mysql_num_rows() function returns the number of rows in a recordset. This function returns FALSE on failure $sql = "SELECT * FROM person"; $result = mysql_query($sql,$con); echo mysql_num_rows($result);
  • 101. Errors in mysql  mysql_error()  mysql_errno()
  • 102. SERVER object  Methods $_SERVER['DOCUMENT_ROOT'] Returns path of document root $_SERVER['HTTP_USER_AGENT'] returns browser information $_SERVER['REMOTE_PORT'] returns port number
  • 103. $_SERVER['REMOTE_ADDR'] returns ip address of server $_SERVER['SERVER_NAME'] returns name of server $_SERVER['SCRIPT_FILENAME'] returns path of current file with file name