SlideShare a Scribd company logo
1 of 48
Download to read offline
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
1
1
What is PHP?
• PHP means " Hypertext Preprocessor"
• PHP is cross platform ,HTML embedded & server side web scripting language
cross platform=> PHP runs on many operating system such as windows,UNIX etc.
HTML embedded=>It can take a standard HTML page, drop in some PHP whenever
need & end up with a dynamic result.
Server Side=>PHP run on server such as apache,IIS etc
web scripting language=>It is used to write web script, not stand alone application.(PHP
programs are executed through web server)
Feature of PHP
• PHP can generate dynamic page content
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• It is open source.
• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP is easy to learn and runs efficiently on the server side
• PHP code can written in a procedure or object oriented manner.
• PHP supports a wide range of databases
1.Lexical Structure
The lexical structure of a programming language is the set of basic rules that governs how you
write programs in that language. It is the lowest-level syntax of the language and specifies such
things as what variable names look like, what characters are used for comments, and how
program statements are separated from each other.
Basic PHP Syntax
<?php
// PHP code goes here
?>
e.g
<html>
<body>
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
2
2
<?php
echo "Hello World!";
?>
</body>
</html>
It can insert HTML tag in PHP
<html>
<body>
<?php
echo "<b>Hello World!</b>";
?>
</body>
</html>
Comments in PHP
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive. But variables are case sensitive
PHP variable
Rules for PHP variables:
• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
3
3
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
• Variable names are case-sensitive
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo "String is $txt";
echo "Integer is $x";
echo "float is $y";
?>
Data type in PHP
• Integers: are whole numbers, without a decimal point, like 4195.
• float: are floating-point numbers, like 3.14159 or 49.1.
• Booleans: have only two possible values either true or false.
• NULL: is a special type that only has one value: NULL.
• Strings: are sequences of characters, like 'PHP supports string operations.'
• Arrays: are named and indexed collections of other values.
• Objects: are instances of programmer-defined classes,
• Resources: are special variables that hold references to resources external to PHP (such
as database connections, image).
PHP Constant
A constant is an identifier (name) for a simple value. The value cannot be changed during the
script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
To create a constant, use the define() function.
Syntax
define(name, value, case-insensitive)
Where
• name: Specifies the name of the constant
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
4
4
• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name should be case-insensitive. Default
is false
<?php
define("PI", 3.14);
echo PI;
?>
Variables variable
It can reference the value of variable whose name is stored in another variable
<?php
$a='hello';
$$a='world';
echo $a;
echo $$a;
?>
o/p
hello
world
Type Juggling
PHP does not require (or support) explicit type definition in variable declaration
The conversion of value from one type to another is called casting.
This kind of implicit casting is called type juggling.
<?php
$x="9hello"-1;
echo $x;
$y="3.14 pile"*2;
echo $y;
?>
o/p
8
6.28
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
5
5
Operators
1.Arithmetic Operators
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
2.Comparison Operators
Operator Name Example Result
==
Equal $x == $y
Returns true if $x is equal to
$y
$x = 100;
$y = "100";
$x == $y =>true(Because
values are equal)
===
Identical $x === $y
Returns true if $x is equal to
$y, and they are of the same
type
$x = 100;
$y = "100";
$x === $y
=>false(Because types
are not same)
!=
Not equal $x != $y
Returns true if $x is not
equal to $y
$x = 100;
$y = "100";
$x != $y
=>false(Because values
are equal)
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
6
6
<>
Not equal $x < > $y
Returns true if $x is not
equal to $y
$x = 100;
$y = "100";
$x <> $y
=>false(Because values
are equal)
!==
Not identical $x !== $y
Returns true if $x is not
equal to $y, or they are not
of the same type
$x = 100;
$y = "100";
$x !== $y
=>true(Because types are
not equal)
>
Greater than $x > $y
Returns true if $x is greater
than $y
<
Less than $x < $y
Returns true if $x is less
than $y
>= Greater than or
equal to
$x >= $y
Returns true if $x is greater
than or equal to $y
<= Less than or
equal to
$x <= $y
Returns true if $x is less
than or equal to $y
3.Logical operator
Operator Name Example Result
And And $x and $y True if both $x and $y are true
Or Or $x or $y True if either $x or $y is true
Xor Xor $x xor $y
True if either $x or $y is true, but
not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
7
7
4.Assignment operator
Assignment Same as... Description
x = y x = y
The left operand gets set to the value of the
expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
5.Increment / Decrement Operators
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
6.PHP String Operators
PHP has two operators that are specially designed for strings.
OperatorName Example Result
. Concatenation $txt1 . $txt2
Concatenation of $txt1 and
$txt2
S $txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;how it
»O/P Hello world!
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
8
8
.=
Concatenation
assignment
$txt1 .= $txt2 Appends $txt2 to $txt1
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 .= $txt2;
O/P Hello world!
Conditional Statements
1. if Statement
if (condition)
{
code to be executed if condition is true;
}
2.if...else Statement
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
3. if...elseif....else Statement
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
4. switch Statement
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from
all labels;
}
Loop
1.while Loop
Syntax
while (condition is true)
2.do...while Loop
Syntax
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
9
9
{
code to be executed;
}
e.g
<?php
$x = 1;
while($x <= 3)
{
echo "The number is: $x <br>";
$x++;
}
?>
do
{
code to be executed;
} while (condition is true);
e.g
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 3);
?>
3.for Loop
Syntax
for (init counter; test counter; increment
counter)
{
code to be executed;
}
e.g
<?php
for ($x = 0; $x <= 3; $x++)
{
echo "The number is: $x <br>";
}
?>
There are two ways the browser client can send information to the web server.
• The GET Method
• The POST Method
GET POST
The GET method sends the encoded user
information appended to the page
request. The page and the encoded
he POST method transfers information via
HTTP headers.e.g
http://www.test.com/index.htm
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
10
10
information are separated by the ?
character.e.g
http://www.test.com/index.htm?name1
=value1&name2=value2
It is by default method It is not by default method
The GET method is restricted to send
upto 1024 characters only.
The POST method does not have any
restriction on data size to be sent.
GET method is not used for password or
other sensitive information to be sent to
the server.
POST method is used for password or other
sensitive information to be sent to the server.
GET can't be used to send binary data to
the server.
POST can be used to send binary data to the
server.
1.$_GET
1.It is global array that collect information from HTML form.
2.It is used to accept values from an html form sent with method is
“get”.
<html>
<body>
<form method=”get”
action="http://localhost/b.php">
Enter value
<input type=text name=t1>
<input type="submit" name=b1
value=OK>
</form>
</body>
</html>
<?php
$a=$_GET['t1'];
echo $a;
?>
2.$_POST
1.It is global array that collect information from HTML form.
2.It is used to accept values from an html form sent with method is
“post”.
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
11
11
<html>
<body>
<form name=”frm” method=”post”
action="http://localhost/b.php">
Enter value
<input type=text name=t1>
<input type="submit" name=b1
value=OK>
</form>
</body>
</html>
<?php
$a=$_POST['t1'];
echo $a;
?>
Retrieve form’s data from various component
<html>
<body>
<form method="POST" action="http://localhost/l1.php">
Ename:
<input type="text" name="t1">
<br>
<br>
Designation:
<input type="text" name="t2">
<br>
<br>
Department:
<select name="k">
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
12
12
<option value="computer">computer</option>
<option value="electronic">electronic</option>
<option value="mathematics">mathematics</option>
</select>
<br>
<br>
Gender:
<input type="radio" name="r" value="Male">Male
<input type="radio" name="r" value="Female">Female
<br>
<br>
<input type="submit" value="submit">
<input type="reset" value="reset">
</form>
</body>
</html>
l1.php
<?php
$s1=$_POST['t1'];
$s2=$_POST['t2'];
$s3=$_POST['k'];
$s4=$_POST['r'];
echo "<br>Ename is $s1";
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
13
13
echo "<br>Designation is $s2";
echo "<br>Department is $s3";
echo "<br>Gender is $s4";
?>
Functions
User Defined Functions
A function is a block of statements that can be used repeatedly in a program.
A function will be executed by a call to the function
Create a User Defined Function
Syntax
function functionName()
{
code to be executed;
}
<?php
function display()
{
echo "Hello world!";
}
display(); // call the function
?>
PHP Function Arguments
1.
<?php
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
14
14
function add($a,$b)
{
$c=$a+$b;
echo "Addition is $c<br>";
}
add(2,3);
?>
Returning values
<?php
function add($a,$b)
{
$c=$a+$b;
return $c;
}
$c=add(2,3);
echo "Addition is $c";
?>
Variables Scope
PHP has three different variable scopes:
• local
• global
• static
1.Global
A variable declared outside a function has a GLOBAL SCOPE
They can be access from any part of the program.
The global keyword is used to access a global variable from within a function
<?php
$x = 5;
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
15
15
$y = 10;
function add()
{
global $x, $y;
$y = $x + $y;
}
add();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds
the name of the variable.
<?php
$x = 5;
$y = 10;
function add()
{
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
}
add();
echo $y; // outputs 15
?>
2.Local
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function
<?php
function display()
{
$y=5;
echo $y;
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
16
16
}
display();
?>
3.Static
A static variable retains the value between calls to a function but it is visible only within that
function
<?php
function display()
{
static $x=0;
echo $x;
$x++;
}
display ();
display ();
display ();
?>
Default Argument Value
<?php
function add($a,$b=4)
{
$c=$a+$b;
echo "Addition is $c<br>";
}
add(2);
?>
Variable-length argument lists(Variable parameter)
PHP 4 and above has support for variable-length argument lists in user-defined functions.
PHP provide 3 function
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
17
17
int func_num_args ( )
Returns the number of arguments passed into the current user-defined function.
array func_get_args ( )
It return array of all parameter provided to the function.
mixed func_get_arg ( int arg_num)
It return a specific argument from the parameter.
<?php
function display()
{
for($i=0;$i<func_num_args();$i++)
{
echo func_get_arg($i);
}
}
display(1,2,3);
?>
Variable functions
PHP supports the concept of variable functions. This means that if a variable name has
parentheses appended to it, PHP will look for a function with the same name as whatever the
variable evaluates to, and will attempt to execute it.
<?php
function disp1()
{
echo "disp1 fuction <br>";
}
function disp2($arg)
{
echo "disp2 function $arg";
}
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
18
18
$func = 'disp1';
$func();
$func = 'disp2';
$func("hello");
?>
Anonymous functions
PHP allows programmer to write the function without name is called anonymous.
To create anonymous function create_function is used
Syntax
string create_function ( string $args , string $code )
<?php
$newfunc = create_function('$a,$b', 'return ($a + $b);');
echo $newfunc(2, 3);
?>
String
A string type can be specified in 3 different ways:
1 single quoted
2 double quoted
3 heredoc
1 Single quoted String
PHP support the strings to be enclosed in single quotes.Single quoted string do not interpolate
variables.The variables name in the string is not expanded except escape sequence character.
<?php
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
19
19
$a=5;
echo 'Value is $a';
?>
o/p
value is $a
2.Double quoted string
Double quoted strings interpolate variables and expand the many PHP escape sequences.
<?php
$a=5;
echo “Value is $a”;
?>
o/p
value is 5
Escaped characters
Sequence Meaning
n linefeed
r carriage return
t horizontal tab
v vertical tab
f form feed
 backslash
$ dollar sign
" double-quote
[0-7]
the sequence of characters matching the regular expression is a character in octal
notation
x[0-9A-Fa-
f]
the sequence of characters matching the regular expression is a character in
hexadecimal notation
3. using heredoc
Single quoted & double quoted string allow strings in single line.
To write multiline strings into the program a heredoc is used.
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
20
20
The <<< identifier is used in PHP,to tell the language that the string is written with heredoc.
<?php
$a= <<< ed
It is php
It is server script
ed;
echo $a;
?>
Printing String
1. echo
The echo() allow to print many strings.
Syntax
echo(strings)
<?php
$str1="Hello world!";
$str2="What a nice day!";
echo $str1 . " " . $str2;
?>
2.print
The print() allow to print one or more strings.
Syntax
print(strings)
<?php
$str1="Hello world!";
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
21
21
$str2="What a nice day!";
print $str1 . " " . $str2;
?>
Note:The print() function is slightly slower than echo().
3.printf
The printf() function outputs a formatted string.
It is similar to printf() function in c Language.
%d - Signed decimal number (negative, zero or positive)
%f - Floating-point number (local settings aware)
%s - String
Syntax
printf(format,arg1,arg2 ,argn)
<?php
$name="amol";
$age=18;
printf("name is %s",$name);
printf("age is %d",$age);
?>
4.print_r
The print_r() debugging function
used to print human-readable information about a variable.
Syntax
Return value print_r(expression)
Where
Expression=>The expression to be printed
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
22
22
Return value=>To capture the output in a variable, parameter should set TRUE. Default value is
FALSE.
<?php
$name="amol";
print_r($name);
?>
o/p
amol
<?php
$a = array(“name”=>”amol”,”class”=>”ty”);
print_r($a);
?>
o/p
Array ( [name] => amol [class] => ty )
5.var_dump()
The var_dump()debugging function is used
to display structured information (type and value) about one or more variables
Syntax
var_dump(variable1);
<?php
$a=4;
$b=1.5;
var_dump($a);
var_dump($b);
?>
o/p
int 4
float 1.5
<?php
$a = array('name'=>'amol','class'=>'ty');
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
23
23
var_dump($a);
?>
o/p
array
'name' => string 'amol' (length=4)
'class' => string 'ty' (length=2)
Difference var_dump & print_r
1.The var_dump() function displays structured information (type and value) about one or more
variables.
2.The print_r() function displays human-readable information about a variable.
3.print_r function loops infinitely while var_dump cuts off after visiting the same element three
times
Array in php
Array: An array is a data structure that stores one or more similar type of values in a single
value.
1.Single dimension array
PHP array type
1.Indexed array - An array with a numeric index. Values are stored and accessed in linear
fashion.index always start with 0
Index Array
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
24
24
<?php
$a = array(1,2,3);
print_r($a);
?>
o/p
Array ( [0] => 1 [1] => 2 [2] => 3 )
2.Associative Array:An array with a string index(key)
Associative Array
<?php
$a = array("rollno"=>"1",
"name"=>"amol", "class"=>"ty");
print_r($a);
?>
o/p
Array ( [rollno] => 1 [name] =>
amol [class] => ty)
Traversing Array in php
1 Using foreach loop
Syntax
foreach ($array as $value)
{
// code
}
Numeric index array Associative array
<?php
$colors = array("red", "green", "blue",
"yellow");
foreach ($colors as $value)
<?php
$a = array("rollno"=>"1", "name"=>"amol",
"class"=>"ty");
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
25
25
{
echo "$value <br>";
}
?>
o/p
red
green
yellow
foreach($a as $x => $val)
{
echo "Key=" . $x ;
echo " Value=".$val;
echo "<br>";
}
?>
o/p
Key=rollno Value=1
Key=name Value=amol
Key=class Value=ty
2.Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
2.Associative Array
<?php
$a=array(
array("rollno"=>"1", "name"=>"amol",
"class"=>"ty"),
array("rollno"=>"2", "name"=>"amit",
"class"=>"ty"),
);
print_r($a);
?>
o/p
Array ( [0] => Array ( [rollno] => 1 [name] =>
amol [class] => ty ) [1] => Array ( [rollno] => 2
[name] => amit [class] => ty ) )
1.Index Array
<?php
$a=array(array(1,2),array(33,22));
print_r($a);
?>
o/p
Array ( [0] => Array ( [0] => 1 [1] => 2 )
[1] => Array ( [0] => 33 [1] => 22 ) )
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
26
26
Using iterator function
1.current():Returns the element currently pointed by the iterstor
2.next():Moves the iterator to the next element in the array & return it.
3.prev():Moves the iterator to the previous element in the array & return it.
4.reset():Moves the iterator to the first element in the array & return it.
5.end():Moves the iterator to the end element in the array & return it.
<?php
$colors = array("red", "green", "blue", "yellow");
echo "<br> current element".current($colors);
echo "<br> next element".next($colors);
echo "<br> prevous element".prev($colors);
echo "<br> reset element".reset($colors);
echo "<br> end element".end($colors);
?>
Sorting Array
1.Sort 2.rsort 3.asort
The sort() function sorts an
indexed array in ascending
order.
<?php
$a=array(4,6,2,);
sort($a);
print_r($a);
?>
o/p
Array ( [0] => 2 [1] => 4 [2]
=> 6 )
The rsort() function sorts an
indexed array in descending
order.
<?php
$a=array(4,6,2);
rsort($a);
print_r($a);
?>
o/p
Array ( [0] => 6 [1] => 4 [2]
=> 2 )
Sort an associative array in
ascending order, according to
the value
<?php
$a=array("amol"=>"16","ami
t"=>"13");
asort($a);
print_r($a);
?>
o/p
Array ( [amit] => 13 [amol]
=> 16 )
4.ksort 5.arsort 6.krsort
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
27
27
Sort an associative array in
ascending order, according to
the key
<?php
$a=array("amol"=>"13","ami
t"=>"16");
ksort($a);
print_r($a);
?>
o/p
Array ( [amit] => 16 [amol]
=> 13 )
Sort an associative array in
descending order, according
to the value
<?php
$a=array("amol"=>"11","ami
t"=>"14");
arsort($a);
print_r($a);
?>
o/p
Array ( [amit] => 14 [amol]
=> 11 )
Sort an associative array in
descending order, according
to the key
<?php
$a=array("amol"=>"13","ami
t"=>"16");
krsort($a);
print_r($a);
?>
o/p
Array ( [amol] => 13 [amit]
=> 16 )
Converting between array &variables
Creating array from a array Creating array from variable
1.extract 2.Compact
This function atomically creates
local variable from a array
Syntax
extract(arrayname)
<?php
$a = array("rollno"=>"1",
"name"=>"amol", "class"=>"ty");
extract($a);
echo $rollno;
echo $name;
echo $class;
?>
o/p 1 amol ty
It Create an array from variables
Syntax
compact(var1,var2...)
<?php
$rollno = 1;
$name = "amol";
$a = compact("rollno","name");
print_r($a)
?>
o/p
Array ( [rollno] => 1 [name] => amol )
Adding & Removing array function
1.Array_push() 2.Array_pop()
The array_push() function inserts one
or more elements to the end of an
array.
Syntax
array_push(array,value1,value2...)
<?php
$a=array("red");
The array_pop() function deletes the last element of
an array.
Syntax
array_pop(array)
<?php
$a=array("red","yellow");
array_pop($a);
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
28
28
array_push($a,"yellow");
print_r($a);
?>
o/p
Array ( [0] => red [1] => yellow )
print_r($a);
?>
o/p
Array ( [0] => red )
3.array_shift() 4.array_splice()
The array_shift() function removes the
first element from an array, and returns
the value of the removed element
Syntax
array_shift(array)
<?php
$a=array("a"=>"red","b"=>"green","c"
=>"blue");
echo array_shift($a);
print_r($a);
?>
o/p
red
Array ( [b] => green [c] => blue )
It removes selected elements from an array and
replaces it with new elements. The function also
returns an array with the removed elements.
Syntax
array_splice(array,start,length,array)
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d
"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>
o/p
Array ( [0] => purple [1] => orange [c] => blue [d]
=> yellow )
5.Array_flip() 6.shuffle
The array_flip() function
flips/exchanges all keys with their
associated values in an array
Syntax
array_flip(array);
<?php
$a1=array("a"=>"red","b"=>"green");
The shuffle() function randomizes the order of the
elements in the array.
Syntax
shuffle(array)
<?php
$my_array = array("a"=>"red","b"=>"green");
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
29
29
$result=array_flip($a1);
print_r($result);
?>
o/p
Array ( [red] => a [green] => b )
shuffle($my_array);
print_r($my_array);
?>
o/p
Array ( [0] => green [1] => red )
7.count 8.array_merge
The count() function returns the
number of elements in an array
<?php
$cars=array("green","red");
echo count($cars);
?>
o/p
2
The array_merge() function merges one or more
arrays into one array.
Syntax
array_merge(array1,array2,array3...)
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
o/p
Array ( [0] => red [1] => green [2] => blue [3] =>
yellow )
9.array_intersect 10 array_diff
The array_intersect() function
compares the values of two (or more)
arrays, and returns the matches.
Syntax
array_intersect(array1,array2,array3...
);
<?php
$a1=array("red","yellow");
$a2=array("blue","yellow");
print_r(array_intersect($a1,$a2));
?>
Array ( [1] => yellow )
The array_diff() function compares the values of
two (or more) arrays, and returns the differences.
Syntax
array_diff(array1,array2,array3...);
<?php
$a1=array("red","yellow");
$a2=array("blue","yellow");
print_r(array_diff($a1,$a2));
?>
o/p
Array ( [0] => red )
12 array_unshift
The array_unshift() function inserts new elements to an array. The new array values will be
inserted in the beginning of the array.
Syntax
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
30
30
array_unshift(array,value1,value2,value3...)
<?php
$a=array("red","green");
array_unshift($a,"blue");
print_r($a);
?>
o/p
Array ( [0] => blue [1] => red [2] => green )
COMPARING FUNCTION
1.EXACT COMPRISION
1.strcmp()
Compare two strings (case-sensitive) & This
function returns following result:
• 0 - if the two strings are equal
• <0 - if string1 is less than string2
• >0 - if string1 is greater than string2
Syntax
strcmp(string1,string2);
<?php
echo strcmp("Hello","Hello");
?>
o/p 0
2. strcasecmp()
The strcasecmp() function compares two
strings but case-insensitive & return below
result
• 0 - if the two strings are equal
• <0 - if string1 is less than string2
• >0 - if string1 is greater than string2
Syntax
strcasecmp(string1,string2);
<?php
echo strcmp("Hello","hello");
?>
o/p
0
3. strncmp()
The strncmp() function compares two strings
& This function returns following result:
• 0 - if the two strings are equal
• <0 - if string1 is less than string2
• >0 - if string1 is greater than string2
Syntax
4.strncasecmp()
String comparison of the first n characters
(case-insensitive) insensitive & return below
result
• 0 - if the two strings are equal
• <0 - if string1 is less than string2
• >0 - if string1 is greater than string2
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
31
31
2. APPROXIMATE EQUALITY
1.soundex()
2.metaphone()
This function see whether two strings are
approximate equal in their pronunciation.
metaphone() is more accurate than
soundex(), because metaphone() knows the
basic rules of English pronunciation
syntax
soundex(string)
metaphone(string)
<?php
$v1=”no”;
$v2=”know”;
If(soundex($v1)==soundex($v2))
echo “$v1 sound $v2 using soundex”;
else
echo “$v1 not sound $v2 using soundex”;
echo "<br>";
If(metaphone ($v1)== metaphone ($v2))
echo “$v1 sound $v2 using metapone”;
else
echo “$v1 not sound $v2 using metaphone”;
?>
o/p
strncmp(string1,string2,length)
<?php
echo strncmp("Hello","Hello",2);
?>
o/p
1
Syntax
strncasecmp(string1,string2,length)
<?php
echo strncasecmp("Hello world!","hello
earth!",6);
?>
o/p
0
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
32
32
4.levenshtein()
This function calculates the similarity of two string based on how many characters must be
added, substituted or remove to make them the same.
Syntax
levenshtein(string1,string2,insert,replace,delete)
Parameter Description
string1 Required. First string to compare
string2 Required. Second string to compare
Insert Optional. The cost of inserting a character.
Replace Optional. The cost of replacing a character.
Delete Optional. The cost of deleting a character.
Return Value: Returns the Levenshtein distance between the two argument strings or -1
<?php
$c=levenshtein("sun","son");
echo $c;
?>
o/p
1
3.Manipulating & Searching String
1.substr() 2.substr_count()
The substr() function returns a part of a
string
Syntax
substr(string,start,length)
The substr_count() function counts the number of
times a substring occurs in a string.
Syntax
substr_count(string,substring,start,length)
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
33
33
ParameterDescription
string
Required. Specifies the string
to return a part of
start
Required. Specifies where to
start in the string
length
Optional. Specifies the length
of the returned string. Default
is to the end of the string.
<?php
$c=substr("hello world",3);
echo $c;
?>
o/p
lo world
ParameterDescription
String Required. Specifies the string to check
substring
Required. Specifies the string to search
for
Start
Optional. Specifies where in string to
start searching
Length
Optional. Specifies the length of the
search
Return
Value:
Returns the the number of times the
substring occurs in the string
<?php
$str="That is php is";
echo substr_count($str,"is");
?>
o/p
2
3.substr_replace()
The substr_replace() function replaces a part of a string with another string.
Syntax
substr_replace(string,replacement,start,length)
Parameter Description
String Required. Specifies the string to check
replacement Required. Specifies the string to insert
Start Required. Specifies where to start replacing in the string
Length
Optional. Specifies how many characters should be replaced. Default is the
same length as the string.
Return Value: Returns the replaced string.
<?php
echo substr_replace("Hello world","earth",6);
?>
o/p
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
34
34
Maintaining State
Http protocol is stateless so that it doesn’t maintain state.
To maintain state in 3 ways
1 Cookies
2 Session
Cookies
• A cookie is often used to identify a user. A cookie is a small file
that the server embeds on the user's computer.
Each time the same computer requests a page with a browser, it will send the cookie too.
• Cookies are simple text.
• Cookies are stored on the client’s machine(web browser) but not on server.
• A URL is stored with each cookie and it is used by the browser to determine whether it
should sent the cookie to the web server or not.
• A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure);
Parameter Description
Name Required. Specifies the name of the cookie
Value Optional. Specifies the value of the cookie
Expire
Optional. Specifies when the cookie expires.
The value: time()+86400*30, will set the cookie to expire in 30 days. If this
parameter is omitted or set to 0, the cookie will expire at the end of the
session (when the browser closes). Default is 0
Path
Optional. This specifies the directories for which cookie is valid. / allowed
the cookie to be valid for all directories and files on the web server. If set to
"/php/", the cookie will only be available within the php directory and all
sub-directories of php. The default value is the current directory that the
cookie is being set in
Domain
Optional. Specifies the domain name of the cookie. To make the cookie
available on all subdomains of example.com, set domain to "example.com".
Setting it to www.example.com will make the cookie only available in the
www subdomain
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
35
35
Secure
Optional. Specifies whether or not the cookie should only be transmitted
over a secure HTTPS connection. TRUE indicates that the cookie will only
be set if a secure connection exists. Default is FALSE
• To retrieve cookie value using $_COOKIE[] global array
Eg
$_COOKIE[“username”]
• Delete a Cookie using setcookie function
Eg
setcookie(“bca”,””);
<?php
if(!isset($_COOKIE[“bca”]))
{
setcookie(“bca”, “sy”, time() + (86400 * 30), "/");
}
else
{
echo "Value is: " . $_COOKIE[“bca”];
}
?>
Advantage of Cookie
1.Cookie are used for authenticating, tracking & mainting specific information about user.
Disadvantage of Cookie
1.Cookies ONLY persist until browser closes UNLESS it specify expirey date.
2.It can’t have more than 20 cookies.
Session
• A session is a way to store information (in variables) to be used across multiple pages.
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
36
36
• A session creates a file in a temporary directory on the server where registered session
variables and their values are stored. This data will be available to all pages on the site
during that visit.
Session_start()
• Before storing user information in php session is to be started using session_start()
function.
• This must be at the very beginning of the code before any HTML or text is sent.
• This function checks if a session is already started and if no, then it starts.
• Session variables are stored in an associative global array called as $_SESSION[].
• Syntax
session_start();
session_id()
• When a session is created a unique session ID is created.
• Session work by creating a Unique Identification Number(UID) for each visitor & storing
variables based on this ID.
• Session identifier is known as session id(SID)
• E.g echo session_id()
Session variables
Use $_SESSION[] associative array for storing and retrieving of session data
• To set value using session
<?php
session_start();
$_SESSION["course"] = "bca";
$_SESSION["subj"] = "php";
echo "Session variables are set.";
echo $_SESSION["course"] ;
echo $_SESSION["subj"];
?>
• To remove all global session variables and destroy the session, use session_unset()
and session_destroy()
Session Cookie
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
37
37
Session are more secure because the data is
retained on the server
Cookies are easier to program
It store data in server IT stored data in client
Session allow for more data to be stored It required less
Used to maintain state throughout your web
application
Used to retrieve small pieces of information
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
38
38
Databases
1.Use a Database –specific extension.
This done by following steps.
1. Create a connection to MySQL Database.
2. Create a database (can be done in MySql)
3. Create a table(Can be done in MySql)
4. Execute Query(Select or any other)
5. Display Result in an HTML Table.
6. Close the connection.
1.Open the Connection.
Before we can access data in a database, it must create a connection to database.
This is done by mysql_connect() function.
Syntax
mysql_connect(servername,username,password)
servername: Optional. Specifies the server to connect to (can also include a port number. e.g.
"hostname:port" or a path to a local socket for the localhost). Default value is "localhost:3306"
username: Optional. Specifies the username to log in with.
Password:Optional. Specifies the password to log in with. Default is ""
e.g
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
39
39
<?php
$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
2.Close Connection
The mysql_close() function closes a MySQL connection.
This function returns TRUE on success, or FALSE on failure.
Syntax
mysql_close(connection)
connection: Optional. Specifies the MySQL connection to close.
If not specified, the last connection opened by mysql_connect() is used.
3. mysql_select_db()
The mysql_select_db() function sets the active MySQL database.This function returns TRUE on
success, or FALSE on failure.
Syntax
mysql_select_db(database,connection)
4.Execute Query
The mysql_query() function executes a query on a MySQL database.This function returns the
query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure.
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
40
40
Syntax
mysql_query(query,connection)
Query: Required.
Specifies the SQL query to send
(should not end with a semicolon).
Connection: Optional.
Specifies the MySQL connection.
If not specified, the last connection opened by mysql_connect() .
Eg1
<?php
$con = mysql_connect("localhost",”root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db("bca ", $con);
if (!$db)
{
die (" Error in test_db : " . mysql_error());
}
$sql = "SELECT * FROM student";
$result=mysql_query($sql,$con);
// some code
mysql_close($con);
?>
Eg2
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
41
41
Create a new database with the mysql_query() function:
<?php
$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$sql = "CREATE DATABASE my_db";
if (mysql_query($sql,$con))
{
echo "Database my_db created";
}
else
{
echo "Error creating database: " . mysql_error();
}
?>
Eg3
To create table
<?php
$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db("bca", $con);
if (!$db)
{
die (" Error in test_db : " . mysql_error());
}
$sql=”create table student (sno int primary key,name varchar(20),per float)”;
if (mysql_query($sql,$con))
{
echo " Table created";
}
else
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
42
42
{
echo "Error creating in table: " . mysql_error();
}
?>
5.Accessing Row in Resultset
1.mysql_fetch_array()
The mysql_fetch_array() function returns a row from a recordset as an associative array and/or a
numeric array.
Syntax
mysql_fetch_array(data,array_type)
Data: Required. Specifies which data pointer to use. The data pointer is the result from the
mysql_query() function
Array_type: Optional. Specifies what kind of array to return.
Possible values:
• MYSQL_ASSOC - Associative array
• MYSQL_NUM - Numeric array
• MYSQL_BOTH - Default. Both associative and numeric array
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db("bca",$con);
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
43
43
$sql = "SELECT * from student";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_array($result,MYSQL_NUM));
mysql_close($con);
?>
2.mysql_result()
The mysql_result() function returns the value of a field in a recordset.
This function returns the field value on success, or FALSE on failure.
Syntax
mysql_result(data,row,field)
Data: Required. Specifies which result handle to use.
Row: Required. Specifies which row number to get. Row numbers start at 0
Field: Optional. Specifies which field to get. Can be field offset, field name or table.fieldname. If
this parameter is not defined mysql_result() gets the first field from the specified row
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db("bca",$con);
$sql = "SELECT * from student";
$result = mysql_query($sql,$con);
echo mysql_result($result,0,0);
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
44
44
echo mysql_result($result,0,1);
echo mysql_result($result,0,2);
mysql_close($con);
?>
3.To get number of rows in Result.
mysql_num_rows()
The mysql_num_rows() function returns the number of rows in a recordset.
This function returns FALSE on failure.
Syntax
mysql_num_rows(data)
Data: Required. Specifies which data pointer to use. The data pointer is the result from the
mysql_query() function
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db("bca",$con);
$sql = "SELECT * FROM student";
$result = mysql_query($sql,$con);
echo mysql_num_rows($result);
mysql_close($con);
?>
4. To get number of affected rows in Result.
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
45
45
mysql_affected_rows()
The mysql_affected_rows() function returns the number of affected rows in the previous MySQL
operation.
This function returns the number of affected rows on success, or -1 if the last operation failed.
Syntax
mysql_affected_rows(connection)
<?php
$con = mysql_connect("localhost",”root","");
if (!$con)
{
die("Could not connect: " . mysql_error());
}
mysql_select_db("bca");
mysql_query("DELETE FROM student WHERE rollno <3");
$rc = mysql_affected_rows();
echo "Records deleted: " . $rc;
mysql_close($con);
?>
RELATIONAL DATABASE AND SQL.
• Execute DDL statements
It can execute create,drop alter statements.
• Execute DML statements
1.Using select statements
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
46
46
}
$db= mysql_select_db("bca",$con);
if (!$db)
{
die('Error in selected database: ' . mysql_error());
}
$i=0;
$sql = "SELECT * from student";
$result = mysql_query($sql,$con);
$numrow = mysql_numrows($result);
While($i< $numrow)
{
echo mysql_result($result,$i,0);
echo mysql_result($result,$i,1);
echo mysql_result($result,$i,2);
$i++;
}
mysql_close($con);
?>
2.Using insert statements
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db= mysql_select_db("bca", $con);
if (!$db)
{
die('Error in selected database: ' . mysql_error());
}
$s1=666;
$s2="anil";
$s3=77.44;
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
47
47
$sql = "insert into student values($s1,'$s2',$s3)";
mysql_query($sql,$con) or die("insert failed");
echo "insert successfully";
mysql_close($con);
?>
3.Using update statements
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db= mysql_select_db("bca", $con);
if (!$db)
{
die('Error in selected database: ' . mysql_error());
}
$s1=666;
$s2="hhh";
$sql = "update student set sname='$s2' where rollno=$s1";
mysql_query($sql,$con) or die("update failed");
Echo "update successfully";
mysql_close($con);
?>
3.Using delete statements
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
Vision Academy2005
(9822506209/9823037693)
(SACHIN SIR MCS,SET)
Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY)
PHP
48
48
die('Could not connect: ' . mysql_error());
}
$db= mysql_select_db("bca", $con);
if (!$db)
{
die('Error in selected database: ' . mysql_error());
}
$s1=666;
$sql = "delete from student where sno=$s1";
mysql_query($sql,$con) or die("delete failed");
Echo "delete successfully";
mysql_close($con);
?>
Sending Email
<?php
$to = "bcs@gmail.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: visionacademy@gmail.com" ;
mail($to,$subject,$txt,$headers) or die(“failed email”);
?>
For Details Visit:
VISION ACADEMYSince 2005
Prof. Sachin Sir(MCS in Scientific Computing From ISSC,UOP,SET)
Classes For
BCS/BCA/BBA(CA)BE(COMP/IT)/Diploma/MCA/MCS/BBA/MBA
(Comp/Maths/Stats/Acc/Project Guidance)
9822506209/9823037693
http://www.visionacademe.com
Branch1:Nr SM Joshi Clg, Malwadi Rd Hadapsar(Nr Avirat Classes)
Branch2:Nr AM Clg,Allahabad Bank,Aditya Gold Society Mahadevnager

More Related Content

What's hot

What's hot (20)

Web 9 | OOP in PHP
Web 9 | OOP in PHPWeb 9 | OOP in PHP
Web 9 | OOP in PHP
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101
 
PHP Conference Asia 2016
PHP Conference Asia 2016PHP Conference Asia 2016
PHP Conference Asia 2016
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
OOP is more than Cars and Dogs
OOP is more than Cars and Dogs OOP is more than Cars and Dogs
OOP is more than Cars and Dogs
 
Twig tips and tricks
Twig tips and tricksTwig tips and tricks
Twig tips and tricks
 
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and DogsOOP Is More Than Cars and Dogs
OOP Is More Than Cars and Dogs
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Dsl
DslDsl
Dsl
 
SQL Devlopment for 10 ppt
SQL Devlopment for 10 pptSQL Devlopment for 10 ppt
SQL Devlopment for 10 ppt
 
Web 10 | PHP with MySQL
Web 10 | PHP with MySQLWeb 10 | PHP with MySQL
Web 10 | PHP with MySQL
 
Twig Brief, Tips&Tricks
Twig Brief, Tips&TricksTwig Brief, Tips&Tricks
Twig Brief, Tips&Tricks
 
Dependency Injection Smells
Dependency Injection SmellsDependency Injection Smells
Dependency Injection Smells
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Web 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHPWeb 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHP
 
SOLID code in practice - creating good object oriented PHP application @ WDI...
SOLID code in practice  - creating good object oriented PHP application @ WDI...SOLID code in practice  - creating good object oriented PHP application @ WDI...
SOLID code in practice - creating good object oriented PHP application @ WDI...
 
Practice exam php
Practice exam phpPractice exam php
Practice exam php
 

Similar to Vision academy classes bcs_bca_bba_sybba_php

From CakePHP to Laravel
From CakePHP to LaravelFrom CakePHP to Laravel
From CakePHP to LaravelJason McCreary
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit universityMandakini Kumari
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboardsDenis Ristic
 
Zend Certification PHP 5 Sample Questions
Zend Certification PHP 5 Sample QuestionsZend Certification PHP 5 Sample Questions
Zend Certification PHP 5 Sample QuestionsJagat Kothari
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 
Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfShaimaaMohamedGalal
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHPBradley Holt
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics McSoftsis
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
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 MySQLArti Parab Academics
 

Similar to Vision academy classes bcs_bca_bba_sybba_php (20)

php.pdf
php.pdfphp.pdf
php.pdf
 
Php
PhpPhp
Php
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
From CakePHP to Laravel
From CakePHP to LaravelFrom CakePHP to Laravel
From CakePHP to Laravel
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
 
Zend Certification PHP 5 Sample Questions
Zend Certification PHP 5 Sample QuestionsZend Certification PHP 5 Sample Questions
Zend Certification PHP 5 Sample Questions
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdf
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
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
 

Recently uploaded

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 

Recently uploaded (20)

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

Vision academy classes bcs_bca_bba_sybba_php

  • 1. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 1 1 What is PHP? • PHP means " Hypertext Preprocessor" • PHP is cross platform ,HTML embedded & server side web scripting language cross platform=> PHP runs on many operating system such as windows,UNIX etc. HTML embedded=>It can take a standard HTML page, drop in some PHP whenever need & end up with a dynamic result. Server Side=>PHP run on server such as apache,IIS etc web scripting language=>It is used to write web script, not stand alone application.(PHP programs are executed through web server) Feature of PHP • PHP can generate dynamic page content • PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) • It is open source. • PHP is compatible with almost all servers used today (Apache, IIS, etc.) • PHP is easy to learn and runs efficiently on the server side • PHP code can written in a procedure or object oriented manner. • PHP supports a wide range of databases 1.Lexical Structure The lexical structure of a programming language is the set of basic rules that governs how you write programs in that language. It is the lowest-level syntax of the language and specifies such things as what variable names look like, what characters are used for comments, and how program statements are separated from each other. Basic PHP Syntax <?php // PHP code goes here ?> e.g <html> <body>
  • 2. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 2 2 <?php echo "Hello World!"; ?> </body> </html> It can insert HTML tag in PHP <html> <body> <?php echo "<b>Hello World!</b>"; ?> </body> </html> Comments in PHP <?php // This is a single-line comment # This is also a single-line comment /* This is a multiple-lines comment block that spans over multiple lines */ ?> In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive. But variables are case sensitive PHP variable Rules for PHP variables: • A variable starts with the $ sign, followed by the name of the variable • A variable name must start with a letter or the underscore character
  • 3. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 3 3 • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) • Variable names are case-sensitive <?php $txt = "Hello world!"; $x = 5; $y = 10.5; echo "String is $txt"; echo "Integer is $x"; echo "float is $y"; ?> Data type in PHP • Integers: are whole numbers, without a decimal point, like 4195. • float: are floating-point numbers, like 3.14159 or 49.1. • Booleans: have only two possible values either true or false. • NULL: is a special type that only has one value: NULL. • Strings: are sequences of characters, like 'PHP supports string operations.' • Arrays: are named and indexed collections of other values. • Objects: are instances of programmer-defined classes, • Resources: are special variables that hold references to resources external to PHP (such as database connections, image). PHP Constant A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). To create a constant, use the define() function. Syntax define(name, value, case-insensitive) Where • name: Specifies the name of the constant
  • 4. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 4 4 • value: Specifies the value of the constant • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false <?php define("PI", 3.14); echo PI; ?> Variables variable It can reference the value of variable whose name is stored in another variable <?php $a='hello'; $$a='world'; echo $a; echo $$a; ?> o/p hello world Type Juggling PHP does not require (or support) explicit type definition in variable declaration The conversion of value from one type to another is called casting. This kind of implicit casting is called type juggling. <?php $x="9hello"-1; echo $x; $y="3.14 pile"*2; echo $y; ?> o/p 8 6.28
  • 5. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 5 5 Operators 1.Arithmetic Operators Operator Name Example Result + Addition $x + $y Sum of $x and $y - Subtraction $x - $y Difference of $x and $y * Multiplication $x * $y Product of $x and $y / Division $x / $y Quotient of $x and $y % Modulus $x % $y Remainder of $x divided by $y 2.Comparison Operators Operator Name Example Result == Equal $x == $y Returns true if $x is equal to $y $x = 100; $y = "100"; $x == $y =>true(Because values are equal) === Identical $x === $y Returns true if $x is equal to $y, and they are of the same type $x = 100; $y = "100"; $x === $y =>false(Because types are not same) != Not equal $x != $y Returns true if $x is not equal to $y $x = 100; $y = "100"; $x != $y =>false(Because values are equal)
  • 6. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 6 6 <> Not equal $x < > $y Returns true if $x is not equal to $y $x = 100; $y = "100"; $x <> $y =>false(Because values are equal) !== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type $x = 100; $y = "100"; $x !== $y =>true(Because types are not equal) > Greater than $x > $y Returns true if $x is greater than $y < Less than $x < $y Returns true if $x is less than $y >= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y <= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y 3.Logical operator Operator Name Example Result And And $x and $y True if both $x and $y are true Or Or $x or $y True if either $x or $y is true Xor Xor $x xor $y True if either $x or $y is true, but not both && And $x && $y True if both $x and $y are true || Or $x || $y True if either $x or $y is true ! Not !$x True if $x is not true
  • 7. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 7 7 4.Assignment operator Assignment Same as... Description x = y x = y The left operand gets set to the value of the expression on the right x += y x = x + y Addition x -= y x = x - y Subtraction x *= y x = x * y Multiplication x /= y x = x / y Division x %= y x = x % y Modulus 5.Increment / Decrement Operators Operator Name Description ++$x Pre-increment Increments $x by one, then returns $x $x++ Post-increment Returns $x, then increments $x by one --$x Pre-decrement Decrements $x by one, then returns $x $x-- Post-decrement Returns $x, then decrements $x by one 6.PHP String Operators PHP has two operators that are specially designed for strings. OperatorName Example Result . Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2 S $txt1 = "Hello"; $txt2 = " world!"; echo $txt1 . $txt2;how it »O/P Hello world!
  • 8. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 8 8 .= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1 $txt1 = "Hello"; $txt2 = " world!"; echo $txt1 .= $txt2; O/P Hello world! Conditional Statements 1. if Statement if (condition) { code to be executed if condition is true; } 2.if...else Statement if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; } 3. if...elseif....else Statement if (condition) { code to be executed if condition is true; } elseif (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; } 4. switch Statement switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; case label3: code to be executed if n=label3; break; ... default: code to be executed if n is different from all labels; } Loop 1.while Loop Syntax while (condition is true) 2.do...while Loop Syntax
  • 9. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 9 9 { code to be executed; } e.g <?php $x = 1; while($x <= 3) { echo "The number is: $x <br>"; $x++; } ?> do { code to be executed; } while (condition is true); e.g <?php $x = 1; do { echo "The number is: $x <br>"; $x++; } while ($x <= 3); ?> 3.for Loop Syntax for (init counter; test counter; increment counter) { code to be executed; } e.g <?php for ($x = 0; $x <= 3; $x++) { echo "The number is: $x <br>"; } ?> There are two ways the browser client can send information to the web server. • The GET Method • The POST Method GET POST The GET method sends the encoded user information appended to the page request. The page and the encoded he POST method transfers information via HTTP headers.e.g http://www.test.com/index.htm
  • 10. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 10 10 information are separated by the ? character.e.g http://www.test.com/index.htm?name1 =value1&name2=value2 It is by default method It is not by default method The GET method is restricted to send upto 1024 characters only. The POST method does not have any restriction on data size to be sent. GET method is not used for password or other sensitive information to be sent to the server. POST method is used for password or other sensitive information to be sent to the server. GET can't be used to send binary data to the server. POST can be used to send binary data to the server. 1.$_GET 1.It is global array that collect information from HTML form. 2.It is used to accept values from an html form sent with method is “get”. <html> <body> <form method=”get” action="http://localhost/b.php"> Enter value <input type=text name=t1> <input type="submit" name=b1 value=OK> </form> </body> </html> <?php $a=$_GET['t1']; echo $a; ?> 2.$_POST 1.It is global array that collect information from HTML form. 2.It is used to accept values from an html form sent with method is “post”.
  • 11. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 11 11 <html> <body> <form name=”frm” method=”post” action="http://localhost/b.php"> Enter value <input type=text name=t1> <input type="submit" name=b1 value=OK> </form> </body> </html> <?php $a=$_POST['t1']; echo $a; ?> Retrieve form’s data from various component <html> <body> <form method="POST" action="http://localhost/l1.php"> Ename: <input type="text" name="t1"> <br> <br> Designation: <input type="text" name="t2"> <br> <br> Department: <select name="k">
  • 12. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 12 12 <option value="computer">computer</option> <option value="electronic">electronic</option> <option value="mathematics">mathematics</option> </select> <br> <br> Gender: <input type="radio" name="r" value="Male">Male <input type="radio" name="r" value="Female">Female <br> <br> <input type="submit" value="submit"> <input type="reset" value="reset"> </form> </body> </html> l1.php <?php $s1=$_POST['t1']; $s2=$_POST['t2']; $s3=$_POST['k']; $s4=$_POST['r']; echo "<br>Ename is $s1";
  • 13. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 13 13 echo "<br>Designation is $s2"; echo "<br>Department is $s3"; echo "<br>Gender is $s4"; ?> Functions User Defined Functions A function is a block of statements that can be used repeatedly in a program. A function will be executed by a call to the function Create a User Defined Function Syntax function functionName() { code to be executed; } <?php function display() { echo "Hello world!"; } display(); // call the function ?> PHP Function Arguments 1. <?php
  • 14. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 14 14 function add($a,$b) { $c=$a+$b; echo "Addition is $c<br>"; } add(2,3); ?> Returning values <?php function add($a,$b) { $c=$a+$b; return $c; } $c=add(2,3); echo "Addition is $c"; ?> Variables Scope PHP has three different variable scopes: • local • global • static 1.Global A variable declared outside a function has a GLOBAL SCOPE They can be access from any part of the program. The global keyword is used to access a global variable from within a function <?php $x = 5;
  • 15. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 15 15 $y = 10; function add() { global $x, $y; $y = $x + $y; } add(); echo $y; // outputs 15 ?> PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. <?php $x = 5; $y = 10; function add() { $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y']; } } add(); echo $y; // outputs 15 ?> 2.Local A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function <?php function display() { $y=5; echo $y;
  • 16. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 16 16 } display(); ?> 3.Static A static variable retains the value between calls to a function but it is visible only within that function <?php function display() { static $x=0; echo $x; $x++; } display (); display (); display (); ?> Default Argument Value <?php function add($a,$b=4) { $c=$a+$b; echo "Addition is $c<br>"; } add(2); ?> Variable-length argument lists(Variable parameter) PHP 4 and above has support for variable-length argument lists in user-defined functions. PHP provide 3 function
  • 17. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 17 17 int func_num_args ( ) Returns the number of arguments passed into the current user-defined function. array func_get_args ( ) It return array of all parameter provided to the function. mixed func_get_arg ( int arg_num) It return a specific argument from the parameter. <?php function display() { for($i=0;$i<func_num_args();$i++) { echo func_get_arg($i); } } display(1,2,3); ?> Variable functions PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. <?php function disp1() { echo "disp1 fuction <br>"; } function disp2($arg) { echo "disp2 function $arg"; }
  • 18. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 18 18 $func = 'disp1'; $func(); $func = 'disp2'; $func("hello"); ?> Anonymous functions PHP allows programmer to write the function without name is called anonymous. To create anonymous function create_function is used Syntax string create_function ( string $args , string $code ) <?php $newfunc = create_function('$a,$b', 'return ($a + $b);'); echo $newfunc(2, 3); ?> String A string type can be specified in 3 different ways: 1 single quoted 2 double quoted 3 heredoc 1 Single quoted String PHP support the strings to be enclosed in single quotes.Single quoted string do not interpolate variables.The variables name in the string is not expanded except escape sequence character. <?php
  • 19. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 19 19 $a=5; echo 'Value is $a'; ?> o/p value is $a 2.Double quoted string Double quoted strings interpolate variables and expand the many PHP escape sequences. <?php $a=5; echo “Value is $a”; ?> o/p value is 5 Escaped characters Sequence Meaning n linefeed r carriage return t horizontal tab v vertical tab f form feed backslash $ dollar sign " double-quote [0-7] the sequence of characters matching the regular expression is a character in octal notation x[0-9A-Fa- f] the sequence of characters matching the regular expression is a character in hexadecimal notation 3. using heredoc Single quoted & double quoted string allow strings in single line. To write multiline strings into the program a heredoc is used.
  • 20. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 20 20 The <<< identifier is used in PHP,to tell the language that the string is written with heredoc. <?php $a= <<< ed It is php It is server script ed; echo $a; ?> Printing String 1. echo The echo() allow to print many strings. Syntax echo(strings) <?php $str1="Hello world!"; $str2="What a nice day!"; echo $str1 . " " . $str2; ?> 2.print The print() allow to print one or more strings. Syntax print(strings) <?php $str1="Hello world!";
  • 21. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 21 21 $str2="What a nice day!"; print $str1 . " " . $str2; ?> Note:The print() function is slightly slower than echo(). 3.printf The printf() function outputs a formatted string. It is similar to printf() function in c Language. %d - Signed decimal number (negative, zero or positive) %f - Floating-point number (local settings aware) %s - String Syntax printf(format,arg1,arg2 ,argn) <?php $name="amol"; $age=18; printf("name is %s",$name); printf("age is %d",$age); ?> 4.print_r The print_r() debugging function used to print human-readable information about a variable. Syntax Return value print_r(expression) Where Expression=>The expression to be printed
  • 22. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 22 22 Return value=>To capture the output in a variable, parameter should set TRUE. Default value is FALSE. <?php $name="amol"; print_r($name); ?> o/p amol <?php $a = array(“name”=>”amol”,”class”=>”ty”); print_r($a); ?> o/p Array ( [name] => amol [class] => ty ) 5.var_dump() The var_dump()debugging function is used to display structured information (type and value) about one or more variables Syntax var_dump(variable1); <?php $a=4; $b=1.5; var_dump($a); var_dump($b); ?> o/p int 4 float 1.5 <?php $a = array('name'=>'amol','class'=>'ty');
  • 23. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 23 23 var_dump($a); ?> o/p array 'name' => string 'amol' (length=4) 'class' => string 'ty' (length=2) Difference var_dump & print_r 1.The var_dump() function displays structured information (type and value) about one or more variables. 2.The print_r() function displays human-readable information about a variable. 3.print_r function loops infinitely while var_dump cuts off after visiting the same element three times Array in php Array: An array is a data structure that stores one or more similar type of values in a single value. 1.Single dimension array PHP array type 1.Indexed array - An array with a numeric index. Values are stored and accessed in linear fashion.index always start with 0 Index Array
  • 24. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 24 24 <?php $a = array(1,2,3); print_r($a); ?> o/p Array ( [0] => 1 [1] => 2 [2] => 3 ) 2.Associative Array:An array with a string index(key) Associative Array <?php $a = array("rollno"=>"1", "name"=>"amol", "class"=>"ty"); print_r($a); ?> o/p Array ( [rollno] => 1 [name] => amol [class] => ty) Traversing Array in php 1 Using foreach loop Syntax foreach ($array as $value) { // code } Numeric index array Associative array <?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) <?php $a = array("rollno"=>"1", "name"=>"amol", "class"=>"ty");
  • 25. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 25 25 { echo "$value <br>"; } ?> o/p red green yellow foreach($a as $x => $val) { echo "Key=" . $x ; echo " Value=".$val; echo "<br>"; } ?> o/p Key=rollno Value=1 Key=name Value=amol Key=class Value=ty 2.Multidimensional Arrays A multidimensional array is an array containing one or more arrays. 2.Associative Array <?php $a=array( array("rollno"=>"1", "name"=>"amol", "class"=>"ty"), array("rollno"=>"2", "name"=>"amit", "class"=>"ty"), ); print_r($a); ?> o/p Array ( [0] => Array ( [rollno] => 1 [name] => amol [class] => ty ) [1] => Array ( [rollno] => 2 [name] => amit [class] => ty ) ) 1.Index Array <?php $a=array(array(1,2),array(33,22)); print_r($a); ?> o/p Array ( [0] => Array ( [0] => 1 [1] => 2 ) [1] => Array ( [0] => 33 [1] => 22 ) )
  • 26. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 26 26 Using iterator function 1.current():Returns the element currently pointed by the iterstor 2.next():Moves the iterator to the next element in the array & return it. 3.prev():Moves the iterator to the previous element in the array & return it. 4.reset():Moves the iterator to the first element in the array & return it. 5.end():Moves the iterator to the end element in the array & return it. <?php $colors = array("red", "green", "blue", "yellow"); echo "<br> current element".current($colors); echo "<br> next element".next($colors); echo "<br> prevous element".prev($colors); echo "<br> reset element".reset($colors); echo "<br> end element".end($colors); ?> Sorting Array 1.Sort 2.rsort 3.asort The sort() function sorts an indexed array in ascending order. <?php $a=array(4,6,2,); sort($a); print_r($a); ?> o/p Array ( [0] => 2 [1] => 4 [2] => 6 ) The rsort() function sorts an indexed array in descending order. <?php $a=array(4,6,2); rsort($a); print_r($a); ?> o/p Array ( [0] => 6 [1] => 4 [2] => 2 ) Sort an associative array in ascending order, according to the value <?php $a=array("amol"=>"16","ami t"=>"13"); asort($a); print_r($a); ?> o/p Array ( [amit] => 13 [amol] => 16 ) 4.ksort 5.arsort 6.krsort
  • 27. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 27 27 Sort an associative array in ascending order, according to the key <?php $a=array("amol"=>"13","ami t"=>"16"); ksort($a); print_r($a); ?> o/p Array ( [amit] => 16 [amol] => 13 ) Sort an associative array in descending order, according to the value <?php $a=array("amol"=>"11","ami t"=>"14"); arsort($a); print_r($a); ?> o/p Array ( [amit] => 14 [amol] => 11 ) Sort an associative array in descending order, according to the key <?php $a=array("amol"=>"13","ami t"=>"16"); krsort($a); print_r($a); ?> o/p Array ( [amol] => 13 [amit] => 16 ) Converting between array &variables Creating array from a array Creating array from variable 1.extract 2.Compact This function atomically creates local variable from a array Syntax extract(arrayname) <?php $a = array("rollno"=>"1", "name"=>"amol", "class"=>"ty"); extract($a); echo $rollno; echo $name; echo $class; ?> o/p 1 amol ty It Create an array from variables Syntax compact(var1,var2...) <?php $rollno = 1; $name = "amol"; $a = compact("rollno","name"); print_r($a) ?> o/p Array ( [rollno] => 1 [name] => amol ) Adding & Removing array function 1.Array_push() 2.Array_pop() The array_push() function inserts one or more elements to the end of an array. Syntax array_push(array,value1,value2...) <?php $a=array("red"); The array_pop() function deletes the last element of an array. Syntax array_pop(array) <?php $a=array("red","yellow"); array_pop($a);
  • 28. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 28 28 array_push($a,"yellow"); print_r($a); ?> o/p Array ( [0] => red [1] => yellow ) print_r($a); ?> o/p Array ( [0] => red ) 3.array_shift() 4.array_splice() The array_shift() function removes the first element from an array, and returns the value of the removed element Syntax array_shift(array) <?php $a=array("a"=>"red","b"=>"green","c" =>"blue"); echo array_shift($a); print_r($a); ?> o/p red Array ( [b] => green [c] => blue ) It removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Syntax array_splice(array,start,length,array) <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d "=>"yellow"); $a2=array("a"=>"purple","b"=>"orange"); array_splice($a1,0,2,$a2); print_r($a1); ?> o/p Array ( [0] => purple [1] => orange [c] => blue [d] => yellow ) 5.Array_flip() 6.shuffle The array_flip() function flips/exchanges all keys with their associated values in an array Syntax array_flip(array); <?php $a1=array("a"=>"red","b"=>"green"); The shuffle() function randomizes the order of the elements in the array. Syntax shuffle(array) <?php $my_array = array("a"=>"red","b"=>"green");
  • 29. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 29 29 $result=array_flip($a1); print_r($result); ?> o/p Array ( [red] => a [green] => b ) shuffle($my_array); print_r($my_array); ?> o/p Array ( [0] => green [1] => red ) 7.count 8.array_merge The count() function returns the number of elements in an array <?php $cars=array("green","red"); echo count($cars); ?> o/p 2 The array_merge() function merges one or more arrays into one array. Syntax array_merge(array1,array2,array3...) <?php $a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_merge($a1,$a2)); ?> o/p Array ( [0] => red [1] => green [2] => blue [3] => yellow ) 9.array_intersect 10 array_diff The array_intersect() function compares the values of two (or more) arrays, and returns the matches. Syntax array_intersect(array1,array2,array3... ); <?php $a1=array("red","yellow"); $a2=array("blue","yellow"); print_r(array_intersect($a1,$a2)); ?> Array ( [1] => yellow ) The array_diff() function compares the values of two (or more) arrays, and returns the differences. Syntax array_diff(array1,array2,array3...); <?php $a1=array("red","yellow"); $a2=array("blue","yellow"); print_r(array_diff($a1,$a2)); ?> o/p Array ( [0] => red ) 12 array_unshift The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array. Syntax
  • 30. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 30 30 array_unshift(array,value1,value2,value3...) <?php $a=array("red","green"); array_unshift($a,"blue"); print_r($a); ?> o/p Array ( [0] => blue [1] => red [2] => green ) COMPARING FUNCTION 1.EXACT COMPRISION 1.strcmp() Compare two strings (case-sensitive) & This function returns following result: • 0 - if the two strings are equal • <0 - if string1 is less than string2 • >0 - if string1 is greater than string2 Syntax strcmp(string1,string2); <?php echo strcmp("Hello","Hello"); ?> o/p 0 2. strcasecmp() The strcasecmp() function compares two strings but case-insensitive & return below result • 0 - if the two strings are equal • <0 - if string1 is less than string2 • >0 - if string1 is greater than string2 Syntax strcasecmp(string1,string2); <?php echo strcmp("Hello","hello"); ?> o/p 0 3. strncmp() The strncmp() function compares two strings & This function returns following result: • 0 - if the two strings are equal • <0 - if string1 is less than string2 • >0 - if string1 is greater than string2 Syntax 4.strncasecmp() String comparison of the first n characters (case-insensitive) insensitive & return below result • 0 - if the two strings are equal • <0 - if string1 is less than string2 • >0 - if string1 is greater than string2
  • 31. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 31 31 2. APPROXIMATE EQUALITY 1.soundex() 2.metaphone() This function see whether two strings are approximate equal in their pronunciation. metaphone() is more accurate than soundex(), because metaphone() knows the basic rules of English pronunciation syntax soundex(string) metaphone(string) <?php $v1=”no”; $v2=”know”; If(soundex($v1)==soundex($v2)) echo “$v1 sound $v2 using soundex”; else echo “$v1 not sound $v2 using soundex”; echo "<br>"; If(metaphone ($v1)== metaphone ($v2)) echo “$v1 sound $v2 using metapone”; else echo “$v1 not sound $v2 using metaphone”; ?> o/p strncmp(string1,string2,length) <?php echo strncmp("Hello","Hello",2); ?> o/p 1 Syntax strncasecmp(string1,string2,length) <?php echo strncasecmp("Hello world!","hello earth!",6); ?> o/p 0
  • 32. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 32 32 4.levenshtein() This function calculates the similarity of two string based on how many characters must be added, substituted or remove to make them the same. Syntax levenshtein(string1,string2,insert,replace,delete) Parameter Description string1 Required. First string to compare string2 Required. Second string to compare Insert Optional. The cost of inserting a character. Replace Optional. The cost of replacing a character. Delete Optional. The cost of deleting a character. Return Value: Returns the Levenshtein distance between the two argument strings or -1 <?php $c=levenshtein("sun","son"); echo $c; ?> o/p 1 3.Manipulating & Searching String 1.substr() 2.substr_count() The substr() function returns a part of a string Syntax substr(string,start,length) The substr_count() function counts the number of times a substring occurs in a string. Syntax substr_count(string,substring,start,length)
  • 33. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 33 33 ParameterDescription string Required. Specifies the string to return a part of start Required. Specifies where to start in the string length Optional. Specifies the length of the returned string. Default is to the end of the string. <?php $c=substr("hello world",3); echo $c; ?> o/p lo world ParameterDescription String Required. Specifies the string to check substring Required. Specifies the string to search for Start Optional. Specifies where in string to start searching Length Optional. Specifies the length of the search Return Value: Returns the the number of times the substring occurs in the string <?php $str="That is php is"; echo substr_count($str,"is"); ?> o/p 2 3.substr_replace() The substr_replace() function replaces a part of a string with another string. Syntax substr_replace(string,replacement,start,length) Parameter Description String Required. Specifies the string to check replacement Required. Specifies the string to insert Start Required. Specifies where to start replacing in the string Length Optional. Specifies how many characters should be replaced. Default is the same length as the string. Return Value: Returns the replaced string. <?php echo substr_replace("Hello world","earth",6); ?> o/p
  • 34. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 34 34 Maintaining State Http protocol is stateless so that it doesn’t maintain state. To maintain state in 3 ways 1 Cookies 2 Session Cookies • A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. • Cookies are simple text. • Cookies are stored on the client’s machine(web browser) but not on server. • A URL is stored with each cookie and it is used by the browser to determine whether it should sent the cookie to the web server or not. • A cookie is created with the setcookie() function. Syntax setcookie(name, value, expire, path, domain, secure); Parameter Description Name Required. Specifies the name of the cookie Value Optional. Specifies the value of the cookie Expire Optional. Specifies when the cookie expires. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0 Path Optional. This specifies the directories for which cookie is valid. / allowed the cookie to be valid for all directories and files on the web server. If set to "/php/", the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory that the cookie is being set in Domain Optional. Specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to "example.com". Setting it to www.example.com will make the cookie only available in the www subdomain
  • 35. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 35 35 Secure Optional. Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE • To retrieve cookie value using $_COOKIE[] global array Eg $_COOKIE[“username”] • Delete a Cookie using setcookie function Eg setcookie(“bca”,””); <?php if(!isset($_COOKIE[“bca”])) { setcookie(“bca”, “sy”, time() + (86400 * 30), "/"); } else { echo "Value is: " . $_COOKIE[“bca”]; } ?> Advantage of Cookie 1.Cookie are used for authenticating, tracking & mainting specific information about user. Disadvantage of Cookie 1.Cookies ONLY persist until browser closes UNLESS it specify expirey date. 2.It can’t have more than 20 cookies. Session • A session is a way to store information (in variables) to be used across multiple pages.
  • 36. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 36 36 • A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit. Session_start() • Before storing user information in php session is to be started using session_start() function. • This must be at the very beginning of the code before any HTML or text is sent. • This function checks if a session is already started and if no, then it starts. • Session variables are stored in an associative global array called as $_SESSION[]. • Syntax session_start(); session_id() • When a session is created a unique session ID is created. • Session work by creating a Unique Identification Number(UID) for each visitor & storing variables based on this ID. • Session identifier is known as session id(SID) • E.g echo session_id() Session variables Use $_SESSION[] associative array for storing and retrieving of session data • To set value using session <?php session_start(); $_SESSION["course"] = "bca"; $_SESSION["subj"] = "php"; echo "Session variables are set."; echo $_SESSION["course"] ; echo $_SESSION["subj"]; ?> • To remove all global session variables and destroy the session, use session_unset() and session_destroy() Session Cookie
  • 37. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 37 37 Session are more secure because the data is retained on the server Cookies are easier to program It store data in server IT stored data in client Session allow for more data to be stored It required less Used to maintain state throughout your web application Used to retrieve small pieces of information
  • 38. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 38 38 Databases 1.Use a Database –specific extension. This done by following steps. 1. Create a connection to MySQL Database. 2. Create a database (can be done in MySql) 3. Create a table(Can be done in MySql) 4. Execute Query(Select or any other) 5. Display Result in an HTML Table. 6. Close the connection. 1.Open the Connection. Before we can access data in a database, it must create a connection to database. This is done by mysql_connect() function. Syntax mysql_connect(servername,username,password) servername: Optional. Specifies the server to connect to (can also include a port number. e.g. "hostname:port" or a path to a local socket for the localhost). Default value is "localhost:3306" username: Optional. Specifies the username to log in with. Password:Optional. Specifies the password to log in with. Default is "" e.g
  • 39. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 39 39 <?php $con = mysql_connect("localhost","mysql_user","mysql_pwd"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code mysql_close($con); ?> 2.Close Connection The mysql_close() function closes a MySQL connection. This function returns TRUE on success, or FALSE on failure. Syntax mysql_close(connection) connection: Optional. Specifies the MySQL connection to close. If not specified, the last connection opened by mysql_connect() is used. 3. mysql_select_db() The mysql_select_db() function sets the active MySQL database.This function returns TRUE on success, or FALSE on failure. Syntax mysql_select_db(database,connection) 4.Execute Query The mysql_query() function executes a query on a MySQL database.This function returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure.
  • 40. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 40 40 Syntax mysql_query(query,connection) Query: Required. Specifies the SQL query to send (should not end with a semicolon). Connection: Optional. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() . Eg1 <?php $con = mysql_connect("localhost",”root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db = mysql_select_db("bca ", $con); if (!$db) { die (" Error in test_db : " . mysql_error()); } $sql = "SELECT * FROM student"; $result=mysql_query($sql,$con); // some code mysql_close($con); ?> Eg2
  • 41. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 41 41 Create a new database with the mysql_query() function: <?php $con = mysql_connect("localhost","mysql_user","mysql_pwd"); if (!$con) { die('Could not connect: ' . mysql_error()); } $sql = "CREATE DATABASE my_db"; if (mysql_query($sql,$con)) { echo "Database my_db created"; } else { echo "Error creating database: " . mysql_error(); } ?> Eg3 To create table <?php $con = mysql_connect("localhost","mysql_user","mysql_pwd"); if (!$con) { die('Could not connect: ' . mysql_error()); } $db = mysql_select_db("bca", $con); if (!$db) { die (" Error in test_db : " . mysql_error()); } $sql=”create table student (sno int primary key,name varchar(20),per float)”; if (mysql_query($sql,$con)) { echo " Table created"; } else
  • 42. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 42 42 { echo "Error creating in table: " . mysql_error(); } ?> 5.Accessing Row in Resultset 1.mysql_fetch_array() The mysql_fetch_array() function returns a row from a recordset as an associative array and/or a numeric array. Syntax mysql_fetch_array(data,array_type) Data: Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function Array_type: Optional. Specifies what kind of array to return. Possible values: • MYSQL_ASSOC - Associative array • MYSQL_NUM - Numeric array • MYSQL_BOTH - Default. Both associative and numeric array <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db = mysql_select_db("bca",$con);
  • 43. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 43 43 $sql = "SELECT * from student"; $result = mysql_query($sql,$con); print_r(mysql_fetch_array($result,MYSQL_NUM)); mysql_close($con); ?> 2.mysql_result() The mysql_result() function returns the value of a field in a recordset. This function returns the field value on success, or FALSE on failure. Syntax mysql_result(data,row,field) Data: Required. Specifies which result handle to use. Row: Required. Specifies which row number to get. Row numbers start at 0 Field: Optional. Specifies which field to get. Can be field offset, field name or table.fieldname. If this parameter is not defined mysql_result() gets the first field from the specified row <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db = mysql_select_db("bca",$con); $sql = "SELECT * from student"; $result = mysql_query($sql,$con); echo mysql_result($result,0,0);
  • 44. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 44 44 echo mysql_result($result,0,1); echo mysql_result($result,0,2); mysql_close($con); ?> 3.To get number of rows in Result. mysql_num_rows() The mysql_num_rows() function returns the number of rows in a recordset. This function returns FALSE on failure. Syntax mysql_num_rows(data) Data: Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db = mysql_select_db("bca",$con); $sql = "SELECT * FROM student"; $result = mysql_query($sql,$con); echo mysql_num_rows($result); mysql_close($con); ?> 4. To get number of affected rows in Result.
  • 45. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 45 45 mysql_affected_rows() The mysql_affected_rows() function returns the number of affected rows in the previous MySQL operation. This function returns the number of affected rows on success, or -1 if the last operation failed. Syntax mysql_affected_rows(connection) <?php $con = mysql_connect("localhost",”root",""); if (!$con) { die("Could not connect: " . mysql_error()); } mysql_select_db("bca"); mysql_query("DELETE FROM student WHERE rollno <3"); $rc = mysql_affected_rows(); echo "Records deleted: " . $rc; mysql_close($con); ?> RELATIONAL DATABASE AND SQL. • Execute DDL statements It can execute create,drop alter statements. • Execute DML statements 1.Using select statements <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error());
  • 46. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 46 46 } $db= mysql_select_db("bca",$con); if (!$db) { die('Error in selected database: ' . mysql_error()); } $i=0; $sql = "SELECT * from student"; $result = mysql_query($sql,$con); $numrow = mysql_numrows($result); While($i< $numrow) { echo mysql_result($result,$i,0); echo mysql_result($result,$i,1); echo mysql_result($result,$i,2); $i++; } mysql_close($con); ?> 2.Using insert statements <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db= mysql_select_db("bca", $con); if (!$db) { die('Error in selected database: ' . mysql_error()); } $s1=666; $s2="anil"; $s3=77.44;
  • 47. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 47 47 $sql = "insert into student values($s1,'$s2',$s3)"; mysql_query($sql,$con) or die("insert failed"); echo "insert successfully"; mysql_close($con); ?> 3.Using update statements <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect: ' . mysql_error()); } $db= mysql_select_db("bca", $con); if (!$db) { die('Error in selected database: ' . mysql_error()); } $s1=666; $s2="hhh"; $sql = "update student set sname='$s2' where rollno=$s1"; mysql_query($sql,$con) or die("update failed"); Echo "update successfully"; mysql_close($con); ?> 3.Using delete statements <?php $con = mysql_connect("localhost", "root", ""); if (!$con) {
  • 48. Vision Academy2005 (9822506209/9823037693) (SACHIN SIR MCS,SET) Classes For BCA/BCS/BBA(CA)/MCS/MCA/MCS/BE(ANY) PHP 48 48 die('Could not connect: ' . mysql_error()); } $db= mysql_select_db("bca", $con); if (!$db) { die('Error in selected database: ' . mysql_error()); } $s1=666; $sql = "delete from student where sno=$s1"; mysql_query($sql,$con) or die("delete failed"); Echo "delete successfully"; mysql_close($con); ?> Sending Email <?php $to = "bcs@gmail.com"; $subject = "My subject"; $txt = "Hello world!"; $headers = "From: visionacademy@gmail.com" ; mail($to,$subject,$txt,$headers) or die(“failed email”); ?> For Details Visit: VISION ACADEMYSince 2005 Prof. Sachin Sir(MCS in Scientific Computing From ISSC,UOP,SET) Classes For BCS/BCA/BBA(CA)BE(COMP/IT)/Diploma/MCA/MCS/BBA/MBA (Comp/Maths/Stats/Acc/Project Guidance) 9822506209/9823037693 http://www.visionacademe.com Branch1:Nr SM Joshi Clg, Malwadi Rd Hadapsar(Nr Avirat Classes) Branch2:Nr AM Clg,Allahabad Bank,Aditya Gold Society Mahadevnager