PHP Notes
PHP Notes
PHP tutorial for beginners and professionals provides in-depth knowledge of PHP scripting
language. Our PHP tutorial will help you to learn PHP scripting language easily. This PHP
tutorial covers all the topics of PHP such as introduction, control statements, functions, array,
string, file handling, form handling, regular expression, date and time, object-oriented
programming in PHP, math, PHP MySQL, PHP with Ajax, PHP with jQuery and PHP with
XML. PHP is a open source, interpreted and object-oriented scripting language i.e. executed at
server side. It is used to develop web applications (an application i.e. executed at server side
and generates dynamic page).
What is PHP
o PHP stands for Hypertext Preprocessor.
o PHP is an interpreted language, i.e., there is no need for compilation.
o PHP is a server-side scripting language.
o PHP is faster than other scripting languages, for example, ASP and JSP.
o PHP is an interpreted language, i.e. there is no need for compilation.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.
PHP Features.
o Performance: Script written in PHP executes much faster then those scripts written in
other languages such as JSP & ASP.
o Open Source Software: PHP source code is free available on the web, you can
developed all the version of PHP according to your requirement without paying any
cost.
o Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX
operating system. A PHP application developed in one OS can be easily executed in
other OS also.
o Compatibility: PHP is compatible with almost all local servers used today like Apache,
IIS etc.
o Embedded: PHP code can be easily embedded within HTML tags and script.
Install PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It
is available for all operating systems. There are many AMP options available in the market that
are given below:
o WAMP for Windows
o LAMP for Linux
o MAMP for Mac
o SAMP for Solaris
o FAMP for FreeBSD
o XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some
other components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail etc.
If you are on Windows and don't want Perl and other features of XAMPP, you should go for
WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.
PHP Example
It is very easy to create a simple PHP example. To do so, create a file and write HTML tags +
PHP code and save this file with .php extension. All PHP code goes between php tag. A syntax
of PHP tag is given below:
<?php
//your code here
?>
Let's see a simple PHP example where we are writing some text using PHP echo command.
File: first.php
<!DOCTYPE>
<html>
<body>
<?php
echo "<h2>Hello First PHP</h2>";
?>
</body>
</html>
Output:
Hello First PHP
PHP Echo
PHP echo is a language construct not a function, so you don't need to use parenthesis with it.
But if you want to use more than one parameters, it is required to use parenthesis. The syntax
of PHP echo is given below:
void echo ( string $arg1 [, string $... ] )
PHP echo statement can be used to print string, multi line strings, escaping characters, variable,
array etc.
PHP echo: printing string
File: echo1.php
<?php
echo "Hello by PHP echo";
?>
Output:
Hello by PHP echo
PHP echo: printing multi line string
File: echo2.php
<?php
echo "Hello by PHP echo
this is multi line
text printed by
PHP echo statement
";
?>
Output:
Hello by PHP echo this is multi line text printed by PHP echo statement
File: echo3.php
<?php
echo "Hello escape \"sequence\" characters";
?>
Output:
Hello escape "sequence" characters
PHP echo: printing variable value
File: echo4.php
<?php
$msg="Hello JavaTpoint PHP";
echo "Message is: $msg";
?>
Output:
Message is: Hello JavaTpoint PHP
PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with
the argument list. Unlike echo, it always returns 1. The syntax of PHP print is given below:
int print(string $arg)
PHP print statement can be used to print string, multi line strings, escaping characters, variable,
array etc.
PHP print: printing string
File: print1.php
<?php
print "Hello by PHP print ";
print ("Hello by PHP print()");
?>
Output:
Hello by PHP print Hello by PHP print()
PHP print: printing multi line string
File: print2.php
<?php
print "Hello by PHP print
this is multi line
text printed by
PHP print statement
";
?>
Output:
Hello by PHP print this is multi line text printed by PHP print statement
PHP print: printing escaping characters
File: print3.php
<?php
print "Hello escape \"sequence\" characters by PHP print";
?>
Output:
Hello escape "sequence" characters by PHP print
PHP print: printing variable value
File: print4.php
<?php
$msg="Hello print() in PHP";
print "Message is: $msg";
?>
Output:
Message is: Hello print() in PHP
PHP Variables
A variable in PHP is a name of memory location that holds data. A variable is a temporary
storage that is used to store data temporarily.
In PHP, a variable is declared using $ sign followed by variable name.
Syntax of declaring a variable in PHP is given below:
$variablename=value;
PHP Variable: Declaring string, integer and float
Let's see the example to store string, integer and float values in PHP variables.
File: variable1.php
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
Output:
string is: hello string
integer is: 200
float is: 44.6
PHP Variable: Sum of two variables
File: variable2.php
<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
Output:
11
PHP Variable: case sensitive
In PHP, variable names are case sensitive. So variable name "color" is different from Color,
COLOR, COLor etc.
File: variable3.php
<?php
$color="red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
Output:
My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is
PHP Variable: Rules
PHP variables must start with letter or underscore only.
PHP variable can't be start with numbers and special symbols.
File: variablevalid.php
<?php
$a="hello";//letter (valid)
$_b="hello";//underscore (valid)
echo "$a <br/> $_b";
?>
Output:
hello
hello
File: variableinvalid.php
<?php
$4c="hello";//number (invalid)
$*d="hello";//special symbol (invalid)
echo "$4c <br/> $*d";
?>
Output:
Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE)
or '$' in C:\wamp\www\variableinvalid.php on line 2
Example 1
<?php
$x = "abc";
$$x = 200;
echo $x."<br/>";
echo $$x."<br/>";
echo $abc;
?>
Output:
In the above example, we have assigned a value to the variable x as abc. Value of reference
variable $$x is assigned as 200.
Now we have printed the values $x, $$x and $abc.
Example2
<?php
$x="U.P";
$$x="Lucknow";
echo $x. "<br>";
echo $$x. "<br>";
echo "Capital of $x is " . $$x;
?>
Output:
In the above example, we have assigned a value to the variable x as U.P. Value of reference
variable $$x is assigned as Lucknow.
Now we have printed the values $x, $$x and a string.
Example3
<?php
$name="Cat";
${$name}="Dog";
${${$name}}="Monkey";
echo $name. "<br>";
echo ${$name}. "<br>";
echo $Cat. "<br>";
echo ${${$name}}. "<br>";
echo $Dog. "<br>";
?>
Output:
In the above example, we have assigned a value to the variable name Cat. Value of reference
variable ${$name} is assigned as Dog and ${${$name}} as Monkey.
Now we have printed the values as $name, ${$name}, $Cat, ${${$name}} and $Dog.
PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the script.
PHP constants can be defined by 2 ways:
1. Using define() function
2. Using const keyword
PHP constants follow the same PHP variable rules. For example, it can be started with letter or
underscore only.
Conventionally, PHP constants should be defined in uppercase letters.
PHP constant: define()
Let's see the syntax of define() function in PHP.
define(name, value, case-insensitive)
1. name: specifies the constant name
2. value: specifies the constant value
3. case-insensitive: Default value is false. It means it is case sensitive by default.
Let's see the example to define PHP constant using define().
File: constant1.php
<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>
Output:
Hello JavaTpoint PHP
File: constant2.php
<?php
define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
echo MESSAGE;
echo message;
?>
Output:
Hello JavaTpoint PHPHello JavaTpoint PHP
File: constant3.php
<?php
define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
echo MESSAGE;
echo message;
?>
Output:
Hello JavaTpoint PHP
Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message
PHP constant: const keyword
The const keyword defines constants at compile time. It is a language construct not a function.
It is bit faster than define().
It is always case sensitive.
File: constant4.php
<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
Output:
Hello const by JavaTpoint PHP
Magic Constants
Magic constants are the predefined constants in PHP which get changed on the basis of their
use. They start with double underscore (__) and ends with double underscore.
They are similar to other predefined constants but as they change their values with the context,
they are called magic constants.
There are eight magical constants defined in the below table. They are case-insensitive.
Name Description
__FILE__ Represents full path and file name of the file. If it is used inside
an include, name of included file is returned.
__METHOD__ Represents the name of the class method where it is used. The
method name is returned as it was declared.
Example
Let's see an example for each of the above magical constants.
PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. For example:
$num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.
PHP Operators can be categorized in following forms:
o Arithmetic Operators
o Comparison Operators
o Bitwise Operators
o Logical Operators
o String Operators
o Incrementing/Decrementing Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators
o Assignment Operators
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
o Unary Operators: works on single operands such as ++, -- etc.
o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".
PHP Operators Precedence
Let's see the precedence of PHP operators with associativity.
Operators Additional Information Associativity
[ array() Left
** arithmetic Right
++ -- ~ (int) (float) (string) (array) increment/decrement and right
(object) (bool) @ types
| bitwise OR left
|| logical OR left
?: ternary left
or logical left
PHP If Else
PHP if else statement is used to test condition. There are various ways to use if statement in
PHP.
o if
o if-else
o if-else-if
o nested if
PHP If Statement
PHP if statement is executed if condition is true.
Syntax
if(condition){
//code to be executed
}
Example
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
Output:
12 is less than 100
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works like
PHP if-else-if statement.
Syntax
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
PHP Switch Example
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Output:
number is equal to 20
endwhile;
PHP While Loop Example
<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
Output:
1
2
3
4
5
6
7
8
9
10
Alternative Example
<?php
$n=1;
while($n<=10):
echo "$n<br/>";
$n++;
endwhile;
?>
Output:
1
2
3
4
5
6
7
8
9
10
PHP Break
PHP break statement breaks the execution of current for, while, do-while, switch and for-each
loop. If you use break inside inner loop, it breaks the execution of inner loop only.
Syntax
jump statement;
break;
PHP Break: inside loop
Let's see a simple example to break the execution of for loop if value of i is equal to 5.
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}
}
?>
Output:
1
2
3
4
5
PHP Break: inside inner loop
The PHP break statement breaks the execution of inner loop only.
<?php
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){
echo "$i $j<br/>";
if($i==2 && $j==2){
break;
}
}
}
?>
Output:
11
12
13
21
22
31
32
33
PHP Break: inside switch statement
The PHP break statement breaks the flow of switch case also.
<?php
$num=200;
switch($num){
case 100:
echo("number is equals to 100");
break;
case 200:
echo("number is equal to 200");
break;
case 50:
echo("number is equal to 300");
break;
default:
echo("number is not equal to 100, 200 or 500");
}
?>
Output:
number is equal to 200
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument
list and return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive
function also.
Advantage of PHP Functions
Code Reusability: PHP functions are defined only once and can be invoked many times, like
in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the
use of function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to
understand the flow of the application because every logic is divided in the form of functions.
Note: Function name must be start with letter and underscore only like other labels in PHP. It
can't be start with numbers or special symbols.
Example 2
Let's understand PHP call by value concept through another example.
<?php
function increment($i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
Output:
10
Example 2
<?php
function greeting($first="Sonoo",$last="Jaiswal"){
echo "Greeting: $first $last<br/>";
}
greeting();
greeting("Rahul");
greeting("Michael","Clark");
?>
Output:
Greeting: Sonoo Jaiswal
Greeting: Rahul Jaiswal
Greeting: Michael Clark
Example 3
<?php
function add($n1=10,$n2=10){
$n3=$n1+$n2;
echo "Addition is: $n3<br/>";
}
add();
add(20);
add(40,40);
?>
Output:
Addition is: 20
Addition is: 30
Addition is: 80
display(1);
?>
Output:
1
2
3
4
5
Example 2 : Factorial Number
<?php
function factorial($n)
{
if ($n < 0)
return -1; /*Wrong value*/
if ($n == 0)
return 1; /*Terminating condition*/
return ($n * factorial ($n -1));
}
echo factorial(5);
?>
Output:
120
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.
Advantage of PHP Array
Less Code: We don't need to define multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
Sorting: We can sort the elements of array.
File: array1.php
<?php
$size=array("Big","Medium","Short");
echo "Size: $size[0], $size[1] and $size[2]";
?>
Output:
Size: Big, Medium and Short
File: array2.php
<?php
$size[0]="Big";
$size[1]="Medium";
$size[2]="Short";
echo "Size: $size[0], $size[1] and $size[2]";
?>
Output:
Size: Big, Medium and Short
Traversing PHP Indexed Array
We can easily traverse array in PHP using foreach loop. Let's see a simple example to traverse
all the elements of PHP array.
File: array3.php
<?php
$size=array("Big","Medium","Short");
foreach( $size as $s )
{
echo "Size is: $s<br />";
}
?>
Output:
Size is: Big
Size is: Medium
Size is: Short
Count Length of PHP Indexed Array
PHP provides count() function which returns length of an array.
<?php
$size=array("Big","Medium","Short");
echo count($size);
?>
Output:
3
File: arrayassociative1.php
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
Output:
Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000
File: arrayassociative2.php
<?php
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
Output:
Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000
Traversing PHP Associative Array
By the help of PHP for each loop, we can easily traverse the elements of PHP associative array.
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
foreach($salary as $k => $v) {
echo "Key: ".$k." Value: ".$v."<br/>";
}
?>
Output:
Key: Sonoo Value: 550000
Key: Vimal Value: 250000
Key: Ratan Value: 200000
1 Sonoo 400000
2 John 500000
3 Rahul 300000
File: multiarray.php
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
PHP String
A PHP string is a sequence of characters i.e. used to store and manipulate text. There are 4
ways to specify string in PHP.
o single quoted
o double quoted
o heredoc syntax
o newdoc syntax (since PHP 5.3)
Single Quoted PHP String
We can create a string in PHP by enclosing text in a single quote. It is the easiest way to specify
string in PHP.
<?php
$str='Hello text within single quote';
echo $str;
?>
Output:
Hello text within single quote
We can store multiple line text, special characters and escape sequences in a single quoted PHP
string.
<?php
$str1='Hello text
multiple line
text within single quoted string';
$str2='Using double "quote" directly inside single quoted string';
$str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
Hello text multiple line text within single quoted string
Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string
Note: In single quoted PHP strings, most escape sequences and variables will not be
interpreted. But, we can use single quote through \' and backslash through \\ inside single
quoted PHP strings.
<?php
$num1=10;
$str1='trying variable $num1';
$str2='trying backslash n and backslash t inside single quoted string \n \t';
$str3='Using single quote \'my quote\' and \\backslash';
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
trying variable $num1
trying backslash n and backslash t inside single quoted string \n \t
Using single quote 'my quote' and \backslash
Double Quoted PHP String
In PHP, we can specify string through enclosing text within double quote also. But escape
sequences and variables will be interpreted using double quote PHP strings.
<?php
$str="Hello text within double quote";
echo $str;
?>
Output:
Hello text within double quote
Now, you can't use double quote directly inside double quoted string.
<?php
$str1="Using double "quote" directly inside double quoted string";
echo $str1;
?>
Output:
Parse error: syntax error, unexpected 'quote' (T_STRING) in C:\wamp\www\string1.php on
line 2
We can store multiple line text, special characters and escape sequences in a double quoted
PHP string.
<?php
$str1="Hello text
multiple line
text within double quoted string";
$str2="Using double \"quote\" with backslash inside double quoted string";
$str3="Using escape sequences \n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
Hello text multiple line text within double quoted string
Using double "quote" with backslash inside double quoted string
Using escape sequences in double quoted string
In double quoted strings, variable will be interpreted.
<?php
$num1=10;
echo "Number is: $num1";
?>
Output:
Number is: 10
PHP String Functions
PHP provides various string functions to access and manipulate strings. A list of important
PHP string functions are given below.
1) PHP strtolower() function
The strtolower() function returns string in lowercase letter.
Syntax
string strtolower ( string $string )
Example
<?php
$str="My name is KHAN";
$str=strtolower($str);
echo $str;
?>
Output:
my name is khan
2) PHP strtoupper() function
The strtoupper() function returns string in uppercase letter.
Syntax
string strtoupper ( string $string )
Example
<?php
$str="My name is KHAN";
$str=strtoupper($str);
echo $str;
?>
Output:
MY NAME IS KHAN
3) PHP ucfirst() function
The ucfirst() function returns string converting first character into uppercase. It doesn't change
the case of other characters.
Syntax
string ucfirst ( string $str )
Example
<?php
$str="my name is KHAN";
$str=ucfirst($str);
echo $str;
?>
Output:
My name is KHAN
4) PHP lcfirst() function
The lcfirst() function returns string converting first character into lowercase. It doesn't change
the case of other characters.
Syntax
string lcfirst ( string $str )
Example
<?php
$str="MY name IS KHAN";
$str=lcfirst($str);
echo $str;
?>
Output:
mY name IS KHAN
5) PHP ucwords() function
The ucwords() function returns string converting first character of each word into uppercase.
Syntax
string ucwords ( string $str )
Example
<?php
$str="my name is Sonoo jaiswal";
$str=ucwords($str);
echo $str;
?>
Output:
My Name Is Sonoo Jaiswal
6) PHP strrev() function
The strrev() function returns reversed string.
Syntax
string strrev ( string $string )
Example
<?php
$str="my name is Sonoo jaiswal";
$str=strrev($str);
echo $str;
?>
Output:
lawsiaj oonoS si eman ym
7) PHP strlen() function
The strlen() function returns length of the string.
Syntax
int strlen ( string $string )
Example
<?php
$str="my name is Sonoo jaiswal";
$str=strlen($str);
echo $str;
?>
Output:
24
PHP Math
PHP provides many predefined math constants and functions that can be used to perform
mathematical operations.
PHP Math: abs() function
The abs() function returns absolute value of given number. It returns an integer value but if you
pass floating point value, it returns a float value.
Syntax
number abs ( mixed $number )
Example
<?php
echo (abs(-7)."<br/>"); // 7 (integer)
echo (abs(7)."<br/>"); //7 (integer)
echo (abs(-7.2)."<br/>"); //7.2 (float/double)
?>
Output:
7
7
7.2
PHP Math: ceil() function
The ceil() function rounds fractions up.
Syntax
float ceil ( float $value )
Example
<?php
echo (ceil(3.3)."<br/>");// 4
echo (ceil(7.333)."<br/>");// 8
echo (ceil(-4.8)."<br/>");// -4
?>
Output:
4
8
-4
PHP Math: floor() function
The floor() function rounds fractions down.
Syntax
float floor ( float $value )
Example
<?php
echo (floor(3.3)."<br/>");// 3
echo (floor(7.333)."<br/>");// 7
echo (floor(-4.8)."<br/>");// -5
?>
Output:
3
7
-5
PHP Math: sqrt() function
The sqrt() function returns square root of given argument.
Syntax
float sqrt ( float $arg )
Example
<?php
echo (sqrt(16)."<br/>");// 4
echo (sqrt(25)."<br/>");// 5
echo (sqrt(7)."<br/>");// 2.6457513110646
?>
Output:
4
5
2.6457513110646
PHP Math: decbin() function
The decbin() function converts decimal number into binary. It returns binary number as a
string.
Syntax
string decbin ( int $number )
Example
<?php
echo (decbin(2)."<br/>");// 10
echo (decbin(10)."<br/>");// 1010
echo (decbin(22)."<br/>");// 10110
?>
Output:
10
1010
10110
PHP Math: dechex() function
The dechex() function converts decimal number into hexadecimal. It returns hexadecimal
representation of given number as a string.
Syntax
string dechex ( int $number )
Example
<?php
echo (dechex(2)."<br/>");// 2
echo (dechex(10)."<br/>");// a
echo (dechex(22)."<br/>");// 16
?>
Output:
2
a
16
PHP Math: decoct() function
The decoct() function converts decimal number into octal. It returns octal representation of
given number as a string.
Syntax
string decoct ( int $number )
Example
<?php
echo (decoct(2)."<br/>");// 2
echo (decoct(10)."<br/>");// 12
echo (decoct(22)."<br/>");// 26
?>
Output:
2
12
26
PHP Math: base_convert() function
The base_convert() function allows you to convert any base number to any base number. For
example, you can convert hexadecimal number to binary, hexadecimal to octal, binary to octal,
octal to hexadecimal, binary to decimal etc.
Syntax
string base_convert ( string $number , int $frombase , int $tobase )
Example
<?php
$n1=10;
echo (base_convert($n1,10,2)."<br/>");// 1010
?>
Output:
1010
PHP Math: bindec() function
The bindec() function converts binary number into decimal.
Syntax
number bindec ( string $binary_string )
Example
<?php
echo (bindec(10)."<br/>");// 2
echo (bindec(1010)."<br/>");// 10
echo (bindec(1011)."<br/>");// 11
?>
Output:
2
10
11
PHP Math Functions
Let's see the list of important PHP math functions.
Function Description
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
echo ("Page Views: ".$_SESSION['counter']);
?>
PHP Destroying Session
PHP session_destroy() function is used to destroy all session variables completely.
File: session3.php
<?php
session_start();
session_destroy();
?>
PHP File Handling
PHP File System allows us to create file, read file line by line, read file character by character,
write file, append file, delete file and close file.
PHP Open File
PHP fopen() function is used to open file or URL and returns resource. The fopen() function
accepts two arguments: $filename and $mode. The $filename represents the file to be opended
and $mode represents the file mode for example read-only, read-write, write-only etc.
Syntax
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource
$context ]] )
PHP Open File Mode
Mode Description
r Opens file in read-only mode. It places the file pointer at the beginning of the
file.
r+ Opens file in read-write mode. It places the file pointer at the beginning of the
file.
w Opens file in write-only mode. It places the file pointer to the beginning of the
file and truncates the file to zero length. If file is not found, it creates a new
file.
w+ Opens file in read-write mode. It places the file pointer to the beginning of the
file and truncates the file to zero length. If file is not found, it creates a new
file.
a Opens file in write-only mode. It places the file pointer to the end of the file.
If file is not found, it creates a new file.
a+ Opens file in read-write mode. It places the file pointer to the end of the file.
If file is not found, it creates a new file.
x Creates and opens file in write-only mode. It places the file pointer at the
beginning of the file. If file is found, fopen() function returns FALSE.
print $formated_date;
?>
It will produce following result:
seconds = 27
minutes = 25
hours = 11
mday = 12
wday = 6
mon = 5
year = 2007
yday = 131
weekday = Saturday
month = May
0 = 1178994327
Today's date: 12/5/2007
Parameter Description
format: Required. Specifies the format of the timestamp
timestamp: Optional. Specifies a timestamp. Default is the current date and time
The date() optionally accepts a time stamp if ommited then current date and time will be used.
Any other data you include in the format string passed to date() will be included in the return
value.
Following table lists the codes that a format string can contain:
Format Description Example
A 'am' or 'pm' lowercase pm
A 'AM' or 'PM' uppercase PM
D Day of month, a number with leading zeroes 20
D Day of week (three letters) Thu
F Month name January
H Hour (12-hour format – leading zeroes) 12
H Hour (24-hour format – leading zeroes) 22
G Hour (12-hour format – no leading zeroes) 12
G Hour (24-hour format – no leading zeroes) 22
I Minutes ( 0 – 59 ) 23
J Day of the month (no leading zeroes 20
l (Lower 'L') Day of the week Thursday
L Leap year ('1' for yes, '0' for no) 1
M Month of year (number – leading zeroes) 1
M Month of year (three letters) Jan
Thu, 21 Dec
R The RFC 2822 formatted date 2000 16:01:07
+0200
N Month of year (number – no leading zeroes) 2
S Seconds of hour 20
U Time stamp 948372444
Y Year (two digits) 06
Y Year (four digits) 2006
Z Day of year (0 – 365) 206
Z Offset in seconds from GMT +5
Try out following example:
<?php
print date("m/d/y G.i:s<br>", time());
print "Today is ";
print date("j of F Y, \a\\t g.i a", time());
?>
It will produce following result:
01/20/00 13.27:55
Today is 20 of January 2000, at 1.27 pm
What is MySQL
MySQL is a fast, easy to use relational database. It is currently the most popular open-source
database. It is very commonly used in conjunction with PHP scripts to create powerful and
dynamic server-side applications.
MySQL is used for many small and big businesses. It is developed, marketed and supported by
MySQL AB, a Swedish company. It is written in C and C++.
PHP MySQL Connect
Since PHP 5.5, mysql_connect() extension is deprecated. Now it is recommended to use one
of the 2 alternatives.
o mysqli_connect()
o PDO::__construct()
PHP mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL database. It
returns resource if connection is established or null.
Syntax
resource mysqli_connect (server, username, password)
PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if
connection is closed or false.
Syntax
bool mysqli_close(resource $resource_link)
PHP MySQL Connect Example
Example
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($conn);
?>
Output:
Connected successfully
PHP MySQL Create Database
Since PHP 4.3, mysql_create_db() function is deprecated. Now it is recommended to use one
of the 2 alternatives.
o mysqli_query()
o PDO::__query()
PHP MySQLi Create Database Example
Example
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
mysqli_close($conn);
?>
Output:
Connected successfully
Table emp5 created successfully
PHP MySQL Insert Record
PHP mysql_query() function is used to insert record in a table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.
o mysqli_query()
o PDO::__query()
PHP MySQLi Insert Record Example
Example
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
mysqli_close($conn);
?>
Output:
Connected successfully
Record inserted successfully
PHP MySQL Update Record
PHP mysql_query() function is used to update record in a table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.
o mysqli_query()
o PDO::__query()
PHP MySQLi Update Record Example
Example
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$id=2;
$name="Rahul";
$salary=80000;
$sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";
if(mysqli_query($conn, $sql)){
echo "Record updated successfully";
}else{
echo "Could not update record: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
Output:
Connected successfully
Record updated successfully
PHP MySQL Delete Record
PHP mysql_query() function is used to delete record in a table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.
o mysqli_query()
o PDO::__query()
PHP MySQLi Delete Record Example
Example
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$id=2;
$sql = "delete from emp4 where id=$id";
if(mysqli_query($conn, $sql)){
echo "Record deleted successfully";
}else{
echo "Could not deleted record: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
Output:
Connected successfully
Record deleted successfully
PHP MySQL Select Query
PHP mysql_query() function is used to execute select query. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.
o mysqli_query()
o PDO::__query()
There are two other MySQLi functions used in select query.
o mysqli_num_rows(mysqli_result $result): returns number of rows.
o mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each
key of the array represents the column name of the table. It return NULL if there are no
more rows.
PHP MySQLi Select Query Example
Example
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
Here, you can see that that the COUNT function calculates the total number of officers in the
table.
MySQL sum() function
The MySQL sum() function is used to return the total summed value of an expression.
Syntax:
SELECT SUM(aggregate_expression)
FROM tables
[WHERE conditions];
Parameter explanation
aggregate_expression: It specifies the column or expression that will be summed.
table_name: It specifies the tables, from where you want to retrieve records. There must be at
least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for the
records to be selected.
MySQL sum() function example
Consider a table named "employees", having the following data.