PHP PDF
PHP PDF
RACHANA BEHERA
Email-id: [email protected]
UNIT 1
INTRODUCTION TO PHP:
Evaluation of PHP:
The combination of PHP and MySQL is the most convenient approach to dynamic, database-
driven web design, holding its own in the face of challenges from integrated frameworks—
such as Ruby on Rails—that are harder to learn. Due to its open source roots (unlike the
competing Microsoft .NET Framework), it is free to implement and is therefore an extremely
popular option for web development.
At its most basic level, the request/response process consists of a web browser asking the web
server to send it a web page and the server sending back the page. The browser then takes
care of displaying the page.
For dynamic web pages, the procedure is a little more involved, because it may bring both PHP and
MySQL into the mix.
1. You enter http://server.com into your browser’s address bar.
2. Your browser looks up the IP address for server.com.
3. Your browser issues a request to that address for the web server’s home page.
4. The request crosses the Internet and arrives at the server.com web server.
5. The web server, having received the request, fetches the home page from its hard disk.
6. With the home page now in memory, the web server notices that it is a file incorporating PHP
scripting and passes the page to the PHP interpreter.
7. The PHP interpreter executes the PHP code.
8. Some of the PHP contains MySQL statements, which the PHP interpreter now passes to the
MySQL database engine.
9. The MySQL database returns the results of the statements to the PHP interpreter.
10. The PHP interpreter returns the results of the executed PHP code, along with the results from the
MySQL database, to the web server.
11. The web server returns the page to the requesting client, which displays it.
PHP:
PHP is an open-source, interpreted, and object-oriented scripting language that can be
executed at the server-side. PHP is well suited for web development. Therefore, it is used to
develop web applications (an application that executes on the server and generates the
dynamic page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP
7.4.0is the latest version of PHP, which was released on 28 November. Some important
points need to be noticed about PHP are as followed:
PHP stands for Hypertext Preprocessor.
PHP is an interpreted language, i.e., there is no need for compilation.
PHP is faster than other scripting languages, for example, ASP and JSP.
PHP is a server-side scripting language, which is used to manage the dynamic content
of the website.
PHP can be embedded into HTML.
PHP is an object-oriented language.
PHP is an open-source scripting language.
PHP is simple and easy to learn language.
Why use PHP:
PHP is a server-side scripting language, which is used to design the dynamic web applications
with MySQL database.
It handles dynamic content, database as well as session tracking for the website.
You can create sessions in PHP.
It can access cookies variable and also set cookies.
It helps to encrypt the data and apply validation.
PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many more.
Using PHP language, you can control the user to access some pages of your website.
As PHP is easy to install and set up, this is the main reason why PHP is the best language to
learn.
PHP can handle the forms, such as - collect the data from users using forms, save it into the
database, and return useful information to the user. For example - Registration form.
PHP Features:
PHP is very popular language because of its simplicity and open source. There are some important
features of PHP given below:
Performance: PHP script is executed much faster than those scripts which are written in
other languages such as JSP and ASP. PHP uses its own memory, so the server workload and
loading time is automatically reduced, which results in faster processing speed and better
performance.
Open Source: PHP source code and software are freely available on the web. You can
develop all the versions of PHP according to your requirement without paying any cost. All
its components are free to download and use.
Familiarity with syntax: PHP has easily understandable syntax. Programmers are
comfortable coding with it.
Embedded: PHP code can be easily embedded within HTML tags and script.
Platform Independent: PHP is available for WINDOWS, MAC, LINUX & UNIX operating
system. A PHP application developed in one OS can be easily executed in other OS also.
Database Support: PHP supports all the leading databases such as MySQL, SQLite, ODBC,
etc.
Error Reporting -PHP has predefined error reporting constants to generate an error notice or
warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language: PHP allows us to use a variable without declaring its data type. It
will be taken automatically at the time of execution based on the type of data it contains on its
value.
Web servers Support: PHP is compatible with almost all local servers used today like
Apache, Netscape, Microsoft IIS, etc.
Security: PHP is a secure language to develop the website. It consists of multiple layers of
security to prevent threads and malicious attacks.
Control: Different programming languages require long script or code, whereas PHP can do
the same work in a few lines of code. It has maximum control over the websites like you can
make changes easily whenever you want.
By default, PHP documents end with the extension .php. When a web server encounters this
extension in a requested file, it automatically passes it to the PHP processor. To trigger the PHP
commands, you need to learn a new tag. Here is the first part:
<?php
The first thing you may notice is that the tag has not been closed. This is because
entire sections of PHP can be placed inside this tag, and they finish only when the
closing part is encountered, which looks like this:
?>
A small PHP “Hello World” program might look like:
Example: Invoking PHP
<?php
echo "Hello world";
?>
1. <?php Output:
2. $name="Cat"; Cat
3. ${$name}="Dog"; Dog
4. ${${$name}}="Monkey"; Dog
5. echo $name. "<br>"; Monkey
6. echo ${$name}. "<br>"; Monkey
7. echo $Cat. "<br>";
8. echo ${${$name}}. "<br>";
9. echo $Dog. "<br>";
10. ?>
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.
1. <?php
3. echo MESSAGE;
4. ?>
Output:
Hello const by JavaTpoint PHP
Constant() function:
There is another way to print the value of constants using constant() function instead of using
the echo statement.
Syntax: constant (name)
File: constant5.php
1. <?php
2. define("MSG", "JavaTpoint");
4. echo constant("MSG");
6. ?>
Output:
JavaTpoint
JavaTpoint
Constant vs Variables
Constant Variables
There is no need to use the dollar To declare a variable, always use the
($) sign before constant during the dollar ($) sign before the variable.
assignment.
Constants are the variables whose The value of the variable can be
values can't be changed throughout changed.
the program.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
i.e.,-2^31 to 2^31.
Example:
1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
3. Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold
numbers with a fractional or decimal point, including a negative or positive sign.
Example:
1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>
Output:
Addition of floating numbers: 73.812
4. String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even
special characters.
String values must be enclosed either within single quotes or in double quotes. But both
are treated differently. To clarify this, see the example below:
Example:
1. <?php
2. $company = "Javatpoint";
3. //both single and double quote statements will treat different
4. echo "Hello $company";
5. echo "</br>";
6. echo 'Hello $company';
7. ?>
Output:
Hello Javatpoint
Hello $company
Compound Types:
It can hold multiple values. There are 2 compound data types in PHP.
1. array
An array is a compound data type. It can store multiple values of same data type in a single
variable.
Example:
1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and values
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM"
}
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
2. object
Objects are the instances of user-defined classes that can store both values and functions.
They must be explicitly declared.
Example:
1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>
Output:
Bike Model: Royal Enfield
Special Types:
There are 2 special data types in PHP.
1. resource
Resources are not the exact data type in PHP. Basically, these are used to store some
function calls or references to external PHP resources. For example - a database call. It
is an external resource.
2. NULL
Null is a special data type that has only one value: NULL. There is a convention of
writing it in capital letters as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
1. <?php
2. $nl = NULL;
4. ?>
Output:
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:
Arithmetic Operators:
The PHP arithmetic operators are used to perform common arithmetic operations such as
addition, subtraction, etc. with numeric values.
Operator Name Example Explanation
Assignment Operators:
The assignment operators are used to assign value to different variables. The basic assignment
operator is "=".
Operator Name Example Explanation
& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise0.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places
Comparison Operators:
Comparison operators allow comparing two values, such as number or string. Below the list of
comparison operators are given:
Operator Name Example Explanation
=== Identical $a === $b Return TRUE if $a is equal to $b, and they are of same data
type
!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are not of
same data type
<= Less than or equal $a <= $b Return TRUE if $a is less than or equal $b
to
Logical Operators:
The logical operators are used to perform bit-level operations on operands. These operators allow
the evaluation and manipulation of specific bits within the integer.
xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
String Operators:
The string operators are used to perform the operation on strings. There are two string operators
in PHP, which are given below:
Operator Name Example Explanation
Array Operators:
The array operators are used in case of array. Basically, these operators are used to compare the
values of arrays.
Operator Name Example Explanation
=== Identity $a === $b Return TRUE if $a and $b have same key/value pair of same
type in same order
!== Non- $a !== $b Return TRUE if $a is not identical to $b
Identity
Type Operators:
The type operator instanceof is used to determine whether an object, its parent and its derived
class are the same type or not. Basically, this operator determines which certain class the object
belongs to. It is used in object-oriented programming.
1. <?php
2. //class declaration
3. class Developer
4. {}
5. class Programmer
6. {}
7. //creating an object of type Developer
8. $charu = new Developer();
9. //testing the type of object
10. if( $charu instanceof Developer)
11. {
12. echo "Charu is a developer.";
13. }
14. else
15. {
16. echo "Charu is a programmer.";
17. }
18. echo "</br>";
19. var_dump($charu instanceof Developer); //It will return true.
20. var_dump($charu instanceof Programmer); //It will return false.
21. ?>
Output:
Charu is a developer.
bool(true) bool(false)
Execution Operators:
PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell
command. Execution operator and shell_exec() give the same result.
Operator Name Example Explanation
`` backticks echo `dir`; Execute the shell command and return the result.
Here, it will show the directories available in current folder.
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
Unary Operators: works on single operands such as ++, -- etc.
Binary Operators: works on two operands such as binary +, -, *, / etc.
Ternary Operators: works on three operands such as "?:".
Example
1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>
Output:
12 is even number
3. If-else-if Statement:
The PHP if-else-if is a special statement used to combine
multiple if?.else statements. So, we can check multiple
conditions using this statement.
Syntax
1. if (condition1){
2. //code to be executed if condition1 is true
3. } elseif (condition2){
4. //code to be executed if condition2 is true
5. } elseif (condition3){
6. //code to be executed if condition3 is true
7. ....
8. } else{
9. //code to be executed if all given conditions are false
10. }
Example
1. <?php
2. $marks=69;
3. if ($marks<33){
4. echo "fail";
5. }
6. else if ($marks>=34 && $marks<50) {
7. echo "D grade";
8. }
9. else if ($marks>=50 && $marks<65) {
10. echo "C grade";
11. }
12. else if ($marks>=65 && $marks<80) {
13. echo "B grade";
14. }
15. else if ($marks>=80 && $marks<90) {
16. echo "A grade";
17. }
18. else if ($marks>=90 && $marks<100) {
19. echo "A+ grade";
20. }
21. else {
22. echo "Invalid input";
23. }
24. ?>
Output:
B Grade
4. PHP nested if Statement:
The nested if statement contains the if block inside another if block. The inner if statement
executes only when specified condition in outer if statement is true.
Syntax
1. if (condition) {
2. //code to be executed if conditio
n is true
3. if (condition) {
4. //code to be executed if conditio
n is true
5. }
6. }
Example
1. <?php
2. $a = 34; $b = 56; $c = 45;
3. if ($a < $b) {
4. if ($a < $c) {
5. echo "$a is smaller than $b and $c";
6. }
7. }
8. ?>
Output:
34 is smaller than 56 and 45
5. Switch:
PHP switch statement is used to execute one
statement from multiple conditions. It works like
PHP if-else-if statement.
Syntax:
1. switch(expression){
2. case value1:
3. //code to be executed
4. break;
5. case value2:
6. //code to be executed
7. break;
8. ......
9. default:
10. code to be executed if all cases are not matched; }
Example:
1. <?php
2. $num=20;
3. switch($num){
4. case 10:
5. echo("number is equals to 10");
6. break;
7. case 20:
8. echo("number is equal to 20");
9. break;
10. case 30:
11. echo("number is equal to 30");
12. break;
13. default:
14. echo("number is not equal to 10, 20 or 30"); }
15. ?>
Output:
number is equal to 20
Doing Repetitive task with looping:
PHP for Loop:
PHP for loop can be used to traverse set of code for the specified number of times. It should
be used if the number of iterations is known otherwise use while loop. This means for loop is
used when you already know how many times you want to execute a block of code.It allows
users to put all the loop related statements in one place.
Syntax:
1. for(initialization; condition; increment/decrement){
2. //code to be executed
3. }
Example:
1. <?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?>
Output:
1
2
3
4
5
6
7
8
9
10
PHP While Loop:
PHP while loop can be used to traverse set of code like for loop. The while loop executes a
block of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it
exits from the body of loop.
It should be used if the number of iterations is not known. The while loop is also called
an Entry control loop because the condition is checked before entering the loop body. This
means that first the condition is checked. If the condition is true, the block of code will be
executed.
Syntax
1. while(condition){
2. //code to be executed
3. }
Alternative Syntax
1. while(condition):
2. //code to be executed
3.
4. endwhile;
Example
1. <?php
2. $n=1;
3. while($n<=10){
4. echo "$n<br/>";
5. $n++;
6. }
7. ?>
Output:
1
2
3
4
5
6
7
8
9
10
PHP do-while loop:
PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while
loop is guaranteed to run at least once.
The PHP do-while loop is used to execute a set of code of the program several times. If you
have to execute the loop at least once and the number of iterations is not even fixed, it is
recommended to use the do-while loop.
It executes the code at least one time always because the condition is checked after executing
the code.
The do-while loop is very much similar to the while loop except the condition check. The
main difference between both loops is that while loop checks the condition at the beginning,
whereas do-while loop checks the condition at the end of the loop.
Syntax
1. do{
2. //code to be executed
3. }while(condition);
Example
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>
Output:
1
2
3
4
5
6
7
8
9
10
PHP foreach loop:
The foreach loop is used to traverse the array elements. It works only on array and object. It
will issue an error if you try to use it with the variables of different datatype.
The foreach loop works on elements basis rather than index. It provides an easiest way to
iterate the elements of an array.
In foreach loop, we don't need to increment the value.
Syntax
1. foreach ($array as $value) {
2. //code to be executed
3. }
There is one more syntax of foreach loop.
Syntax
1. foreach ($array as $key => $element) {
2. //code to be executed
3. }
Example: PHP program to print array elements using foreach loop.
1. <?php
2. //declare array
3. $season = array ("Summer", "Winter", "Autumn", "Rainy");
4.
5. //access array elements using foreach loop
6. foreach ($season as $element) {
7. echo "$element";
8. echo "</br>";
9. }
10. ?>
Output:
Summer
Winter
Autumn
Rainy
Mixing Decisions and looping with HTML:
PHP will only processes things that are enclosed within one of its valid code blocks (such as <?php
and ?>).
RACHANA BEHERA
Email-id: [email protected]
UNIT 2
Function:
What is a function?
A function is a set of statements that performs a particular function and optionally returns a
value.
PHP function is a piece of code that can be reused many times. It can take input as argument
list and return value.
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.
Define a function:
There are thousands of built-in functions in PHP. In PHP, we can define Conditional function,
Function within Function and Recursive function also.
PHP User Defined Functions:
Besides the built-in PHP functions, it is possible to create your own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute automatically when a page loads.
A function will be executed by a call to the function.
Create a User Defined Function in PHP
A user-defined function declaration starts with the word function:
Syntax:
function functionName()
{
code to be executed;
}
Example:
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
Output:
Hello world!
PHP Function Arguments:
We can pass the information in PHP function through arguments which is separated
by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values
and Variable-length argument list.
Example to pass single argument in PHP function:
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Output:
Hello Sonoo
Hello Vimal
Hello John
Example to pass two argument in PHP function:
<?php
function sayHello($name,$age)
{
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
Recursive function:
PHP also supports recursive function call like C/C++. In such case, we call current function
within function. It is also known as recursion.
Example 1: Printing number
<?php
function display($number)
{
if($number<=5){
echo "$number <br/>";
display($number+1);
}
}
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
String Creating and accessing:
PHP string is a sequence of characters i.e., used to store and manipulate text. PHP supports
only 256-character set and so that it does not offer native Unicode support.
There are 4 ways to specify a string literal in PHP.
1. Single Quoted:
We can create a string in PHP by enclosing the text in a single-quote. It is the
easiest way to specify string in PHP. For specifying a literal single quote,
escape it with a backslash (\) and to specify a literal backslash (\) use double
backslash (\\). All the other instances with backslash such as \r or \n, will be
output same as they specified instead of having any special meaning.
Example:
<?php
$str='Hello text within single quote';
echo $str;
?>
Output:
Hello text within single quote
2. Double Quoted:
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.
Example:
<?php
$str="Hello text within double quote";
echo $str;
?>
Output:
Hello text within double quote
3. Heredoc:
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an
identifier is provided after this heredoc <<< operator, and immediately a new
line is started to write any text. To close the quotation, the string follows itself
and then again that same identifier is provided. That closing identifier must
begin from the new line without any whitespace or tab.It must contain only
alphanumeric characters and underscores, and must start with an underscore or
a non-digit character.
Example:
<?php
$str = <<<Demo
It is a valid example
Demo; //Valid code as whitespace or tab is not valid before closing
identifier
echo $str;
?>
Output:
It is a valid example
4. Newdoc:
Newdoc is similar to the heredoc, but in newdoc parsing is not done. It is also
identified with three less than symbols <<< followed by an identifier. But here
identifier is enclosed in single-quote, e.g. <<<'EXP'. Newdoc follows the same
rule as heredocs.
The difference between newdoc and heredoc is that - Newdoc is a single-
quoted stringwhereas heredoc is a double-quoted string.
Example-1:
<?php
$str = <<<'DEMO'
Welcome to javaTpoint.
DEMO;
echo $str;
echo '</br>';
echo <<< 'Demo' // Here we are not storing string content in variable
str.
Welcome to javaTpoint.
Demo;
?>
Output:
Welcome to javaTpoint.
Welcome to javaTpoint.
String Searching:
The strchr() function searches for the first occurrence of a string inside another string.
This function is an alias of the strstr() function.
This function is binary-safe.
This function is case-sensitive. For a case-insensitive search, use stristr() function.
Syntax:
strchr(string,search,before_search);
Parameter Values:
Parameter Description
string Required. Specifies the string to search
search Required. Specifies the string to search for. If this parameter is
a number, it will search for the character matching the ASCII
value of the number
before_search Optional. A boolean value whose default is "false". If set to
"true", it returns the part of the string before the first occurrence
of the search parameter.
Example:
<html>
<body>
<?php
echo strchr("Hello world!","world",true);
?>
</body>
</html>
Output:
Hello
Replacing String:
The str_replace() function replaces some characters with some other characters in a string.
This function works by the following rules:
If the string to be searched is an array, it returns an array
If the string to be searched is an array, find and replace is performed with every array
element
If both find and replace are arrays, and replace has fewer elements than find, an empty
string will be used as replace
If find is an array and replace is a string, the replace string will be used for every find
value
This function is case-sensitive. Use the str_ireplace() function to perform a case-insensitive
search. This function is binary-safe.
Syntax:
str_replace(find,replace,string,count)
Parameter Values:
Parameter Description
find Required. Specifies the value to find
replace Required. Specifies the value to replace the value in find
string Required. Specifies the string to be searched
count Optional. A variable that counts the number of replacements
Example:
<html>
<body>
<p>Search an array for the value "RED", and then replace it with "pink".</p>
<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
?>
</body>
</html>
Output:
Search an array for the value "RED", and then replace it with "pink".
Array ( [0] => blue [1] => pink [2] => green [3] => yellow )
Replacements: 1
Formatting String:
PHP features the versatile printf() and sprintf() functions that you can use to format string in
many different ways.
printf():
The printf() function outputs a formatted string.
Syntax:
printf(format,arg1,arg2,arg++)
Example:
<?php
$number=123;
printf(“%f”,$number);
?>
sprintf():
The sprintf() function writes a formatted string to a variable.
Synatx:
Sprintf(format,arg1,arg2,arg++)
Example:
<?php
$number=123;
$txt=sprintf(“%f”,$number);
echo $txt;
?>
String Related Library function:
1) strtolower():
The strtolower() function returns string in lowercase letter.
Syntax: string strtolower ( string $string )
Example:
<?php
$str="My name is Rachana";
$str=strtolower($str);
echo $str;
?>
Output:
my name is rachana
2) strtoupper():
The strtoupper() function returns string in uppercase letter.
Syntax: string strtoupper ( string $string )
Example:
<?php
$str="My name is Rachana";
$str=strtoupper($str);
echo $str;
?>
Output:
MY NAME IS RACHANA
3) ucfirst():
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 Rachana";
$str=ucfirst($str);
echo $str;
?>
Output:
My name is Rachana.
4) lcfirst():
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 RACHANA";
$str=lcfirst($str);
echo $str;
?>
Output:
mY name IS RACHANA
5) ucwords():
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) strrev():
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) strlen():
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
ARRAY:
Anatomy of an Array:
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.
There are 3 types of array in PHP:
1. Indexed Array
2. Associative Array
3. Multidimensional Array
PHP Indexed Array:
PHP indexed array is an array which is represented by an index number by default. All
elements of array are represented by an index number which starts from 0.
PHP indexed array can store numbers, strings or any object. PHP indexed array is also known
as numeric array.
There are two ways to define indexed array:
1st way:
$size=array("Big","Medium","Short");
2nd way:
$size[0]="Big";
$size[1]="Medium";
$size[2]="Short";
Example1:
<?php
$size=array("Big","Medium","Short");
echo "Size: $size[0], $size[1] and $size[2]";
?>
Output:
Size: Big, Medium and Short
Example 2:
<?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
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.
Example:
<?php
$size=array("Big","Medium","Short");
echo count($size);
?>
Output:
3
PHP Associative Array:
PHP allows you to associate name/label with each array elements in PHP using => symbol.
Such way, you can easily remember the element because each element is represented by label
than an incremented number.
There are two ways to define associative array:
1st way:
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
2nd way:
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
Example 1:
<?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
Example 2:
<?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.
Example:
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
foreach($salary as $k => $v) {
echo "Key: ".$k." Value: ".$v."<br/>";
}
?>
Output:
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
Some useful Library function:
is_array():
The is_array() function checks whether a variable is an array or not.
This function returns true (1) if the variable is an array, otherwise it returns false/nothing.
Syntax: is_array(variable);
Example: <html>
<body>
<?php
$a = "Hello";
echo "a is " . is_array($a) . "<br>";
$b = array("red", "green", "blue");
echo "b is " . is_array($b) . "<br>";
$c = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "c is " . is_array($c) . "<br>";
$d = "red, green, blue";
echo "d is " . is_array($d) . "<br>";
?>
</body>
</html>
Output: a is
b is 1
c is 1
d
count():
This function is used to return the number of elements in an array.
Syntax: count(variable)
Example: <html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
</body>
</html>
Output: 3
sort():
Sort the elements of the array in ascending order.
Synatx: sort(variable)
Example:
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>
Output:
BMW
Toyota
Volvo
shuffle():
The shuffle() function randomizes the order of the elements in the array.
This function assigns new keys for the elements in the array. Existing keys will be removed
(See Example below).
Syntax: shuffle(array)
Example:
<html>
<body>
<?php
$my_array = array("red","green","blue","yellow","purple");
shuffle($my_array);
print_r($my_array);
?>
<p>Refresh the page to see how shuffle() randomizes the order of the elements in
the array.</p>
</body>
</html>
Output:
Array ( [0] => green [1] => purple [2] => yellow [3] => red [4] => blue )
Refresh the page to see how shuffle() randomizes the order of the elements in the
array.
compact():
The compact() function creates an array from variables and their values.
Any strings that does not match variable names will be skipped.
Syntax: compact(var1, var2...)
Example:
<html>
<body>
<?php
$firstname = "Peter";
$lastname = "Griffin";
$age = "41";
$result = compact("firstname", "lastname", "age");
print_r($result);
?>
</body>
</html>
Output:
Array ( [firstname] => Peter [lastname] => Griffin [age] => 41 )
reset():
The reset() function moves the internal pointer to the first element of the array.
Related methods:
current() - returns the value of the current element in an array
end() - moves the internal pointer to, and outputs, the last element in the array
next() - moves the internal pointer to, and outputs, the next element in the array
prev() - moves the internal pointer to, and outputs, the previous element in the array
each() - returns the current element key and value, and moves the internal pointer forward
Syntax: reset(array)
Example:
<html>
<body>
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
echo current($people) . "<br>"; // The current element is Peter
echo next($people) . "<br>"; // The next element of Peter is Joe
echo current($people) . "<br>"; // Now the current element is Joe
echo prev($people) . "<br>"; // The previous element of Joe is Peter
echo end($people) . "<br>"; // The last element is Cleveland
echo prev($people) . "<br>"; // The previous element of Cleveland is Glenn
echo current($people) . "<br>"; // Now the current element is Glenn
echo reset($people)."<br>";//Moves the internal pointer to the first element of the array(peter)
echo next($people) . "<br>" . "<br>"; // The next element of Peter is Joe
print_r (each($people));
?>
Output:
Peter
Joe
Joe
Peter
Cleveland
Glenn
Glenn
Peter
Joe
Array ( [1] => Joe [value] => Joe [0] => 1 [key] => 1 )
INSTITUTE OF MANAGEMENT AND INFORMATION TECHNOLOGY
RACHANA BEHERA
Email-id: [email protected]
UNIT 3
Handling Html Form with Php:
The main way that website users interact with PHP and MySQL is through the use of HTML forms.
Handling forms is a multipart process.
First a form is created, into which a user can enter the required details. This data is then sent to the
web server, where it is interpreted, often with some error checking. If the PHP code identifies one or
more fields that require re-entering, the form may be redisplayed with an error message.
When the code is satisfied with the accuracy of the input, it takes some action that usually involves
the database, such as entering details about a purchase.
To build a form, you must have at least the following elements:
An opening <form> and closing </form> tag
A submission type specifying either a Get or Post method
One or more input fields
The destination URL to which the form data is to be submitted
$_GET:
Information sent from a form with the GET method is visible to everyone (all variable
names and values are displayed in the URL).
GET also has limits on the amount of information to send. The limitation is about
2000 characters. However, because the variables are displayed in the URL, it is
possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
GET should NEVER be used for sending passwords or other sensitive information!
Example:
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
"welcome_get.php" :
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
$_POST:
Information sent from a form with the POST method is invisible to others (all
names/values are embedded within the body of the HTTP request) and has no limits
on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary
input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to
bookmark the page.
Example:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
“welcome.php”
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
Input Types:
HTML forms are very versatile and allow you to submit a wide range of input types, from
text boxes and text areas to checkboxes, radio buttons, and more.
Text boxes: The input type you will probably use most often is the text box. It accepts a
wide range of alphanumeric text and other characters in a single-line box. The general format
of a text box input is as follows:
<input type="text" name="name" size="size" maxlength="length" value="value">
Text areas: When you need to accept input of more than a short line of text, use a text area.
This is similar to a text box, but, because it allows multiple lines, it has some different
attributes. Its general format looks like this:
<textarea name="name" cols="width" rows="height" wrap="type"></textarea>
Checkboxes: When you want to offer a number of different options to a user, from which
he can select one or more items, checkboxes are the way to go. Here is the format to use:
<input type="checkbox" name="name" value="value" checked="checked">
If you include the checked attribute, the box is already checked when the browser is
displayed.
Radio button: Radio buttons are named after the push-in preset buttons found on many
older radios, where any previously depressed button pops back up when another is pressed.
They are used when you want only a single value to be returned from a selection of two or
more options. All the buttons in a group must use the same name and, because only a single
value is returned, you do not have to pass an array.
<input type=”radio” name=”name” value=”value”>
Hidden fields: Sometimes it is convenient to have hidden form fields so that you can keep
track of the state of form entry. For example, you might wish to know whether a form has
already been submitted. You can achieve this by adding some HTML in your PHP code, such
as the following:
echo '<input type="hidden" name="submitted" value="yes">'
This is a simple PHP echo statement that adds an input field to the HTML form.
<select>: The <select> tag lets you create a drop-down list of options, offering either single
or multiple selections. It conforms to the following syntax:
<select name="name" size="size" multiple="multiple">
The attribute size is the number of lines to display. Clicking on the display causes a list to
drop down, showing all the options. If you use the multiple attribute, a user can select
multiple options from the list by pressing the Ctrl key when clicking.
Example:
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>
File: login.php
<?php
$name=$_POST["name"];//receiving name field value in $name variable
$password=$_POST["password"];
echo "Welcome: $name, your password is: $password";
?>
Dealing with Multi-value filed
Form fields can send multiple values, rather than a single value.
The trick is to add square brackets ([]) after the field name in your HTML form. When PHP
engine sees a submitted form field name with square brackets at the end, it creates a nested
array of values within the $_GET or $_POST and $_REQUEST superglobal array, rather than
a single value.
You can then pull the individual values out of that nested array. So you might create a multi-
select list control as follows:
<select name="mySelection[]" id="mySelection" size="3" multiple="multiple"> ... </select>
Example:
<html>
<body>
<form action="demo.php"method="post">
<fieldset style="width:200px">
<legend>Personal Info</legend>
First Name<br>
<input type="text"name="txtfname"><br>
Last name<br>
<input type="text"name="txtlname"><br>
</fieldset>
<fieldset style="width:200px">
<legend>Platform Interested</legend>
<input type="checkbox"name="chkplatform[]"value="PHP">PHP<br>
<input type="checkbox"name="chkplatform[]"value="JAVA">JAVA<br>
<input type="checkbox"name="chkplatform[]"value="C">C<br>
</fieldset>
<input type="submit" name="btnsave"value="save">
<input type="reset" name="btnreset"value="Reset">
</form>
</body>
</html>
demo.php:
<?php
if(isset($_POST["btnsave"]))
{
$firstname=$_POST["txtfname"];
$lastname=$_POST["txtlname"];
$platform=$_POST["chkplatform"];
echo"<h1>First Name=$firstname</h1>";
echo"<h1>Last Name=$lastname</h1>";
foreach($platform as $platforms=>$p)
{ echo"<b>platform interested:$p</b><br>";}
}
else
{
echo"Form data is not submitted";
}
?>
Generating File uploaded form:
A PHP script can be used with a HTML form to allow users to upload files to the server.
Initially files are uploaded into a temporary directory and then relocated to a target
destination by a PHP script.
Information in the phpinfo.php page describes the temporary directory that is used for file
uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is
stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini.
The process of uploading a file follows these steps –
The user opens the page containing a HTML form featuring a text files, a browse
button and a submit button.
The user clicks the browse button and selects a file to upload from the local PC.
The full path to the selected file appears in the text filed then the user clicks the
submit button.
The selected file is sent to the temporary directory on the server.
The PHP script that was specified as the form handler in the form’s action attribute
checks that the file has arrived and then copies the file into an intended directory.
The PHP script confirms the success to the user.
As usual when writing files it is necessary for both temporary and final locations to
have permissions set that enable file writing. If either is set to be read-only then
process will fail.
An uploaded file could be a text file or image file or any document.
Working with file and Directories:
Understanding file & directory:
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.
Opening and closing a file:
PHP fopen():
This 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:
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.
x+ It is same as x but it creates and opens file in read-write mode.
c Opens file in write-only mode. If the file does not exist, it is created. If it exists, it is
neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case
with 'x'). The file pointer is positioned on the beginning of the file
c+ It is same as c but it opens file in read-write mode.
Example:
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
?>
PHP Close File :
The PHP fclose() function is used to close an open file pointer.
Syntax:
fclose ( open function variable name)
Example:
<?php
fclose($handle);
?>
PHP Read File:
PHP provides various functions to read data from file. There are different functions that allow
you to read all file data, read data line by line and read data character by character.
The available PHP file read functions are given below.
fread()
fgets()
fgetc()
fread(): The PHP fread() function is used to read data of the file. It requires two arguments:
file resource and file size.
Syntax:
string fread (resource filename , filesize or int $length )
where $length represents length of byte to be read.
Example:
<?php
$filename = "c:\\file1.txt";
$fp = fopen($filename, "r");//open file in read mode
$contents = fread($fp, filesize($filename));//read file
echo "<pre>$contents</pre>";//printing data of file
fclose($fp);//close file
?>
Output:
this is first line
this is another line
this is third line
fgets():
The PHP fgets() function is used to read single line from the file.
Syntax:
string fgets ( resource filename [, int $length ] )
Example:
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
echo fgets($fp);
fclose($fp);
?>
Output
this is first line
fgetc():
The PHP fgetc() function is used to read single character from the file. To get all data using
fgetc() function, use !feof() function inside the while loop.
Syntax:
string fgetc ( resource filename)
Example:
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
Output
this is first line this is another line this is third line
feof():
This function checks if the "end-of-file" (EOF) has been reached for an open file. This
function is useful for looping through data of unknown length.
Syntax:
feof(file)
Example:
<?php
$file = fopen("test.txt", "r");
//Output lines until EOF is reached
while(! feof($file)) {
$line = fgets($file);
echo $line. "<br>";
}
fclose($file);
?>
PHP Write File
PHP fwrite() and fputs() functions are used to write data into file. To write data into file, you
need to use w, r+, w+, x, x+, c or c+ mode.
The PHP fwrite() function is used to write content of the string into file.
Syntax:
int fwrite ( resource filename , string $string [, int $length ] )
Example:
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'welcome ');
fwrite($fp, 'to php file write');
fclose($fp);
echo "File written successfully";
?>
Output: data.txt
welcome to php file write
PHP Append to File
You can append data into file by using a or a+ mode in fopen() function. Let's see a simple
example that appends data into data.txt file.
The PHP fwrite() function is used to write and append data into file.
Example:
<?php
$fp = fopen('data.txt', 'a');//opens file in append mode
fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data');
fclose($fp);
echo "File appended successfully";
?>
Output: data.txt
welcome to php file write this is additional text appending data
rename( ) Function:
The rename() function in PHP is an inbuilt function which is used to rename a file or
directory.
It makes an attempt to change an old name of a file or directory with a new name specified by
the user and it may move between directories if necessary.
If the new name specified by the user already exists, the rename() function overwrites it. The
old name of the file and the new name specified by the user are sent as parameters to the
rename() function and it returns True on success and a False on failure.
Syntax:
rename(oldname, newname, context)
Example 1:
<?php
$old_name = "ofile.txt" ;
$new_name = "nfile.txt" ;
rename( $old_name, $new_name) ;
?>
Output:
1
Example 2:
<?php
$old_name = "ofile.txt" ;
$new_name = "nfile.txt" ;
if (!rename($old_name, $new_name))
{
echo "File cannot be renamed. \n";
}
else
{
echo "File has been renamed.";
}
?>
Output:
File has been renamed.
Delete a file:
To delete a file by using PHP is very easy. Deleting a file means completely erase a file from
a directory so that the file is no longer exist. PHP has an unlink() function that allows to
delete a file. The PHP unlink() function takes two parameters $filename and $context.
Syntax:
unlink( $filename, $context );
Example:
<?php
$file="text2.txt";
if(!unlink($file))
{
echo"File cannot be deleted due to error";
}
else
{
echo"File has been deleted";
}
?>
Output:
File has been deleted.
RACHANA BEHERA
Email-id: [email protected]
UNIT 4
Session and Cookie:
Introduction to Session Control:
A session is a global variable stored on the server.
Each session is assigned a unique id which is used to retrieve stored values.
Whenever a session is created, a cookie containing the unique session id is stored on the
user’s computer and returned with every request to the server. If the client browser does not
support cookies, the unique php session id is displayed in the URL.
Sessions have the capacity to store relatively large data compared to cookies.
The session values are automatically deleted when the browser is closed. If you want to store
the values permanently, then you should store them in the database.
Just like the $_COOKIE array variable, session variables are stored in the $_SESSION array
variable. Just like cookies, the session must be started before any HTML tags.
Session Functionality:
You want to store important information such as the user id more securely on the server
where malicious users cannot temper with them.
You want to pass values from one page to another.
You want the alternative to cookies on browsers that do not support cookies.
You want to store global variables in an efficient and more secure way compared to passing
them in the URL.
You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.
What is a Cookie:
A cookie is an item of data that a web server saves to your computer’s hard disk via a web
browser.
It can contain almost any alphanumeric information (as long as it’s under 4 KB) and can be
retrieved from your computer and returned to the server.
Common uses include session tracking, maintaining data across multiple visits, holding
shopping cart contents, storing login details, and more.
Because of their privacy implications, cookies can be read only from the issuing domain.
In other words, if a cookie is issued by, for example, oreilly.com, it can be retrieved only by a
web server using that domain. This prevents other websites from gaining access to details for
which they are not authorized.
Because of the way the Internet works, multiple elements on a web page can be embedded
from multiple domains, each of which can issue its own cookies. When this happens, they are
referred to as third-party cookies. Most commonly, these are created by advertising
companies in order to track users across multiple websites.
Because of this, most browsers allow users to turn cookies off either for the current server’s
domain, third-party servers, or both. Fortunately, most people who disable cookies do so only
for third-party websites.
Cookies are exchanged during the transfer of headers, before the actual HTML of a web page
is sent, and it is impossible to send a cookie once any HTML has been transferred. Therefore,
careful planning of cookie usage is important.
A browser/server request/response dialog with cookies:
RACHANA BEHERA
Email-id: [email protected]
UNIT 5
Database Connectivity with MYSQL:
INTRODUCTION TO RDBMS:
A Relational Database Management System (RDBMS) is a server that manages data for you.
The data is structured into tables, where each table has some number of columns, each of which has a
name and a type.
Tables are grouped together into databases, so a James Bond database might have tables for movies,
actors playing Bond, and villains.
An RDBMS usually has its own user system, which controls access rights for databases (e.g., "user
Fred can update database Bond").
PHP communicates with relational databases such as MySQL and Oracle using the Structured Query
Language (SQL).
INTRODUCTION MySQL:
MySQL is the most popular open-source database system. MySQL is a database.
The data in MySQL is stored in database objects called tables.
A table is a collection of related data entries and it consists of columns and rows.
Databases are useful when storing information categorically. A company may have a database with
the following tables: "Employees", "Products", "Customers" and "Orders".
CONNECTION WITH MySQL DATABASE:
Create a Connection to a MySQL Database:
Before you can access data in a database, you must create a connection to the database.
In PHP, this is done with the mysql_connect() function.
Syntax: mysql_connect(servername, username, password);
Parameter Description
Username Specifies the username to log in with. Default value is the name of the user that owns
(Optional) the server process.
Example: <?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
Closing a Connection:
The connection will be closed automatically when the script ends. To close the connection before,
use the mysql_close() function:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
PHP mysql_pconnect () :
The mysql_pconnect () function opens a persistent MySQL connection.
This function returns the connection on success, or FALSE and an error on failure. You can hide the
error output by adding a '@' in front of the function name.
mysql_pconnect() is much like mysql_connect(), but with two major differences:
This function will try to find a connection that's already open, with the same host, username
and password. If one is found, this will be returned instead of opening a new connection.
The connection will not be closed when the execution of the script ends (mysql_close() will
not close connection opened by mysql_pconnect()). It will stay open for future use.
Syntax:
mysql_pconnect(server, user, pwd, clientflag)
Parameter Description
Server Specifies the server to connect to (can also include a port number. e.g. "hostname:port"
(optional) or a path to a local socket for the localhost). Default value is "localhost:3306".
User Specifies the username to log in with. Default value is the name of the user that owns
(optional) the server process.
Example:
<?php
$con = mysql_pconnect("localhost","mysql_user","mysql_pwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
?>
The reason for using PHP as an interface to MySQL is to format the results of SQL queries in a form
visible in a web page. As long as you can log into your MySQL installation using your username and
password, you can also do so from PHP.
However, instead of using MySQL’s command line to enter instructions and view output,you will
create query strings that are passed to MySQL. When MySQL returns its response, it will come as a
data structure that PHP can recognize instead of the formatted output you see when you work on the
command line. Further PHP commands can retrieve the data and format it for the web page.
The process of using MySQL with PHP is as follows:
1. Connect to MySQL and select the database to use.
2. Build a query string.
3. Perform the query.
4. Retrieve the results and output them to a web page.
5. Repeat steps 2 to 4 until all desired data has been retrieved.
6. Disconnect from MySQL.
7. Most websites developed with PHP contain multiple program files that will require access to
MySQL and will thus need the login and password details. Therefore, it’s sensible to create a
single file to store these and then include that file wherever it’s needed.
Database Tables:
A database most often contains one or more tables. Each table is identified by a name (e.g.
"Customers" or "Orders"). Tables contain records (rows) with data.
Below is an example of a table called "Persons":
FirstName LastName Age
Peter Gen 45
Glenn John 50
The table above contains three records (one for each person) and three columns (FirstName,
LastName, Age).
Queries:
A query is a question or a request. With MySQL, we can query a database for specific information
and have a recordset returned.
Look at query: SELECT LastName FROM Persons
The query above selects all the data in the "LastName" column from the "Persons" table, and will
return a record set like this:
LastName
Gen
John
Firstname Lastname
Peter Gen
Glenn John
Glenn Quagmire
Peter Griffin
Example: Consider two tables "officers" and "students", having the following data.
Execute the following query:
SELECT officers.officer_name, officers.address, students.course_name
FROM officers
INNER JOIN students
ON officers.officer_id = students.student_id;
Output:
The MySQL Inner Join is used to returns only those results from the tables that match the
specified condition and hides other rows and columns. MySQL assumes it as a default Join, so it
is optional to use the Inner Join keyword with the query.
MySQL Inner Join Example:
Let us first create two tables "students" and "technologies" that contains the following data:
Table: student
Table: technologies
Table: contacts
To fetch all records from both tables, execute the following query:
SELECT *
FROM customers
CROSS JOIN contacts;
After successful execution of the query, it will give the following output:
When the CROSS JOIN statement executed, you will observe that it displays 42 rows. It means
seven rows from customers table multiplies by the six rows from the contacts table.
try
{
//check if
if(filter_var($email,FILTER_VALIDATE_EMAIL)=== FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e)
{
//display custom message
echo $e->errorMessage();
}
?>
The new class is a copy of the old exception class with an addition of the errorMessage() function.
Since it is a copy of the old class, and it inherits the properties and methods from the old class, we
can use the exception class methods like getLine() and getFile() and getMessage().
Example explained:
The code above throws an exception and catches it with a custom exception class:
1. The customException() class is created as an extension of the old exception class. This way it inherits
all methods and properties from the old exception class
2. The errorMessage() function is created. This function returns an error message if an e-mail address is
invalid
3. The $email variable is set to a string that is not a valid e-mail address
4. The "try" block is executed and an exception is thrown since the e-mail address is invalid
5. The "catch" block catches the exception and displays the error message