Web Applications Development Using PHP & Mysql
Web Applications Development Using PHP & Mysql
Unit-2
Working with Arrays: Creating Arrays, Some Array-Related Functions.
Working with Objects: Creating Objects, Accessing Object Instances.
Working with Strings, Dates and Time: Formatting strings with PHP, Manipulating Strings with PHP,
Using Date and Time Functions in PHP.
Unit-3
Working with Forms: Creating Forms, Accessing Form Input with User defined Arrays, Combining
HTML and PHP code on a single Page, Using Hidden Fields to save state, Redirecting the user, Sending
Mail on Form Submission, and Working with File Uploads, Exception handling.
Unit-4
Working with Cookies and User Sessions: Introducing Cookies, Setting a Cookie with PHP, Session
Function Overview, Starting a Session, Working with session variables, passing session IDs in the Query
String, Destroying Sessions and Unsetting Variables.
Unit-5
Interacting with MySQL using PHP: MySQL Versus MySQLi Functions, Connecting to MySQL with
PHP, Working with MySQL Data. Planning and Creating Database Tables, Creating Menu, Creating Record
Addition Mechanism, Viewing Records, Creating the Record Deletion Mechanism.
Text Book(s):
l. Julie c. Meloni, SAMS Teach yourself PHP MySQL and Apache, Pearson Education (2007).
Reference Books
l. Robin Nixon, Leaming PHP, MySQL, JavaScript' CSS & HTMLs, Third Edition o,reilly, 2014
2. Xue Bai Michael Ekedahl, The web warrior guide to web Programming, Thomson (2006)
BSC SEMESTER – V 1 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
BSC SEMESTER – V 2 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
UNIT I
INTRODUCTION: 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.0 is
the latest version of PHP, which was released on 28 November. Some important points need to be
noticed about PHP are as followed:
Some facts about PHP:
PHP has many syntaxes similar to C, Java, and Perl, and has many unique features and specific
functions.
PHP page is a file with a .php extension can contain a combination of HTML Tags and PHP scripts.
PHP is Server-side scripting language: Server-side scripting means that the PHP code is processed
on the web server rather than the client machine.
PHP supports many databases (MySQL and PHP combination is widely used).
PHP is an open-source scripting language.
PHP is an object-oriented language.
PHP is free to download and use.
PHP is simple and easy to learn language.
CHARACTERISTICS OF PHP(OR)FEATURES OF PHP: PHP is very popular language because of
its simplicity and open source. There are some important features of PHP given below:
1. 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.
2. 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.
3. Familiarity with syntax: PHP has easily understandable syntax. Programmers are comfortable coding
with it.
4. Embedded: PHP code can be easily embedded within HTML tags and script.
5. 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.
BSC SEMESTER – V 3 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
6. Database Support: PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
7. 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.
8. Loosely Typed Language: PHP allows us to use a variable without declaring its datatype. It will be
taken automatically at the time of execution based on the type of data it contains on its value.
9. Web servers Support: PHP is compatible with almost all local servers used today like Apache,
Netscape, Microsoft IIS, etc.
10. Security: PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.
11. 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.
12. A Helpful PHP Community: It has a large community of developers who regularly updates
documentation, tutorials, online help, and FAQs. Learning PHP from the communities is one of the
significant benefits.
APPLICATIONS OF PHP: PHP is one of the most widely used language over the web. The following
are the major applications of PHP:
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and
close them.
PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send
data, return data to the user.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
PHP SYNTAX
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
Basic PHP Syntax
A PHP script can be placed anywhere in the document. A PHP script starts with <?php and ends with ?>
<?php
// PHP code goes here
?>
BSC SEMESTER – V 4 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
The default file extension for PHP files is ".php". A PHP file normally contains HTML tags, and
some PHP scripting code. PHP statements end with a semicolon (;). Below, we have an example of a simple
PHP file, with a PHP script that uses a built-in PHP function "echo" to output the text "Hello World!" on a
web page:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
BSC SEMESTER – V 5 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Examples:-
<!DOCTYPE html>
<html>
<body>
<h1>ScmGalaxy</h1>
<?php
echo ‘Hello\n’;
print “World”;
?>
</body>
</html>
2. Commenting
# and // are used to comment out a single line of code, while /* and */ indicate the start and end of a
commented block of code.
1. HTML tags
There are HTML tags for PHP code to indicate the start and end of PHP code in an HTML file. Any one of
the following 4 tags can be used:
1. <?php php-code-here ?>
2. <SCRIPT LANGUAGE="php"> php-code-here </SCRIPT>
3. <? php-code-here ?>
4. <% php-code-here %>
The first and second tags are the ones most recommended and most widely used. Using a tag which is rarely
used may result in a web-server being unable to detect the start and end of the PHP code.
VARIABLES
Variables in a program are used to store some values or data that can be used later in a program.
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important points to know
about variables
BSC SEMESTER – V 6 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that
can be categorized further in 3 types:
1. Scalar Types (Predefined)
2. Compound Types (User-defined)
3. Special Types
1. Scalar Types (Predefined): It holds only single value. There are 4 scalar data types in PHP.
a. boolean
b. integer
c. float
d. string
BSC SEMESTER – V 7 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
a. boolean: Booleans are the simplest data type works like switch. It holds only two values: TRUE
(1) or FALSE (0). It is often used with conditional statements. If the condition is correct, it returns TRUE
otherwise FALSE.
Example:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Output:
This condition is TRUE.
b. integer: Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e.,
numbers without fractional part or decimal points.
Rules for integer:
o An integer can be either positive or negative.
o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31.
Example:
<?php
$n1 = 10;
$n2 = 10;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
Addition of floating numbers: 20
c. 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:
<?php
$n1 = 19.34;
BSC SEMESTER – V 8 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
Addition of floating numbers: 73.812
d. 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:
<?php
$college = "ZENEX";
//both single and double quote statements will treat different
echo "Hello $college";
?>
Output:
Hello ZENEX
2. Compound Types (User-defined): It can hold multiple values. There are 2 compound data types in
PHP.
a) array
b) object
a) array: An array is a compound data type. It can store multiple values of same data type in a single
variable.
Example:
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
BSC SEMESTER – V 9 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Output:
Season are: summer, winter, spring and autumn
b) object: An object is an instance of a class. It’s a central concept in object-oriented programming.
An object has properties. For example, a person object may have the first name, last name, and age
properties.
An object also has behaviours, which are known as methods. For example, a person object can have a method
called getFullName() that returns the full name.
Example:
<?php
class bike
{
function model()
{
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
Output:
Bike Model: Royal Enfield
3. Special Types: There are 2 special data types in PHP.
a) resource
b) NULL
a) resource: resources: Resources in PHP are not an exact data type. These are basically used to store
references to some function call or to external PHP resources. For example, consider a database call. This
is an external resource. Resource variables hold special handles for files and database connections.
b) NULL: Null is a special data type which can have only one value: NULL. If a variable is created without
a value, it is automatically assigned a value of NULL. Variables can also be emptied by setting the value to
NULL:
Example:
BSC SEMESTER – V 10 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
<?php
$nm = NULL;
echo $nm; // this will return no output
// return data type
var_dump($nm);
?>
Output
NULL
PHP OPERATORS AND EXPRESSIONS
Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to
perform operations on variables or values.
For example:
$num=10+20;//+ is the operator and 10,20 are operands
PHP divides the operators in the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Increment/Decrement operators
5. Logical operators
6. String operators
7. Array operators
8. Conditional assignment operators
BSC SEMESTER – V 11 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
1. Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical operations like addition, subtraction,
multiplication, etc. Below is the list of arithmetic operators along with their syntax and operations in PHP.
Example:
<?php
$x = 4; // Variable 1
$y = 2; // Variable 2
// Some arithmetic operations on
// these two variables
echo ($x + $y), "\n";
echo($x - $y), "\n";
echo($x * $y), "\n";
echo($x / $y), "\n";
echo($x % $y), "\n";
echo( $x ** $y);
?>
Output:
6
2
8
BSC SEMESTER – V 12 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
2
0
16
2. Assignment operators: The assignment operators are used to assign value to different variables. The basic
assignment operator is "=".
BSC SEMESTER – V 13 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
$x /= 10;
echo $x . "<br>"; // Outputs: 5
$x = 100;
$x %= 15;
echo $x . "<br>"; // Outputs: 10
OUTPUT:
10
50
30
125
5
10
3. Comparison operators: These operators are used to compare two elements and output the result in
boolean form.
=== Identical $x === Returns true if $x is equal to $y, and they are of the same type
$y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same
type
BSC SEMESTER – V 14 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
<=> Spaceship $x <=> Returns an integer less than, equal to, or greater than zero,
$y depending on if $x is less than, equal to, or greater than $y.
Introduced in PHP 7.
4. Increment/Decrement operators: The increment and decrement operators are used to increase and
decrease the value of a variable.
5. 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.
BSC SEMESTER – V 15 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
6. String operators: The string operators are used to perform the operation on strings. There are two string
operators in PHP, which are given below:
7. Array operators: The array operators are used in case of array. Basically, these operators are used to
compare the values of arrays.
BSC SEMESTER – V 16 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
== Equality $x == $y Returns true if $x and $y have the same key/value pairs
=== Identity $x === Returns true if $x and $y have the same key/value pairs in the
$y same order and of the same types
8. Conditional assignment operators: The PHP conditional assignment operators are used to set a
value depending on conditions:
PHP Constants
1. Constants are like variables except that once they are defined they cannot be changed or
undefined.
2. A constant is an identifier (name) for a simple value. The value cannot be changed during
the script. A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
3. Note: Unlike variables, constants are automatically global across the entire script.
4. Create a PHP Constant
5. To create a constant, use the define () function.
Syntax:
define(name, value, case-insensitive)
BSC SEMESTER – V 17 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Constants are automatically global and can be used across the entire script.
The example below uses a constant inside a function, even if it is defined outside the function:
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest()
{
echo
GREETING;
}
myTest();
?>
Predefined Constants:
PHP automatically provides some built-in constants for you. For example, the constant FILE returns the
name of the file that the PHP engine is currently reading. The constant LINE returns the current line
number of the file. These are but two examples of what are called “magic constants,” because they are
not statically predefined and instead change depending on the context in which they are used.
BSC SEMESTER – V 18 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
4. nested if
5. switch statement
1. if statement: If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.
Syntax:
if(condition)
{
//code to be executed
}
Flowchart:
Example
<?php
$num=12;
if($num<100)
{
echo "$num is less than 100";
}
?>
Output: 12 is less than 100
BSC SEMESTER – V 19 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
2. if…else statement: PHP if-else statement is executed whether condition is true or false.
If-else statement is slightly different from if statement. It executes one block of code if the specified
condition is true and another block of code if the condition is false. Syntax:
if(condition)
{
//code to be executed if true
}
else
{
//code to be executed if false
}
Flowchart
Example: <?php
$num=12;
if($num%2==0)
{
echo "$num is even number";
}
else
{
echo "$num is odd number";
}?>
BSC SEMESTER – V 20 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Output:
12 is even number
3. If…else if…else 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:
if (condition1)
{
//code to be executed if condition1 is true
}
elseif (condition2)
{
//code to be executed if condition2 is true
}
elseif (condition3)
{
//code to be executed if condition3 is true
....
}
else
{
//code to be executed if all given conditions are false
}
Flowchart:
BSC SEMESTER – V 21 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Example
<?php
$marks=69;
if ($marks<33)
{
echo "fail";
}
else if ($marks>=34 && $marks<50)
{
echo "D grade";
}
else if ($marks>=50 && $marks<65)
{
echo "C grade";
}
else if ($marks>=65 && $marks<80)
{
echo "B grade";
}
else if ($marks>=80 && $marks<90)
{
echo "A grade";
}
else if ($marks>=90 && $marks<100)
{
echo "A+ grade";
}
else
{
echo "Invalid input";
}
?>
BSC SEMESTER – V 22 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Output:
B Grade
4. Nested if: 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
if (condition)
{
//code to be executed if condition is true
if (condition)
{
//code to be executed if condition is true
}
}
Flowchart
Example
<?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
BSC SEMESTER – V 23 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
BSC SEMESTER – V 24 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Flowchart:
Example:
<?php
$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
BSC SEMESTER – V 25 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Like any other language, loop in PHP is used to execute a statement or a block of statements, multiple times
until and unless a specific condition is met. This helps the user to save both time and effort of writing the same
code multiple times.
PHP supports four types of looping techniques;
1. for loop
2. while loop
3. do-while loop
4. foreach loop
1. for loop: PHP for loop can be used to execute same block of statements 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.
Syntax:
for (initialization expression; test condition; update expression)
{
// code to be executed
}
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then
check whether this variable is less than or greater than counter value. If statement is true, then loop body is
executed and loop variable gets updated . Steps are repeated till exit condition comes.
Initialization Expression: In this expression we have to initialize the loop counter to some value. for
example: $num = 1;
Test Expression: In this expression we have to test the condition. If the condition evaluates to true then
we will execute the body of loop and go to update expression otherwise we will exit from the for loop.
For example: $num <= 10;
Update Expression: After executing loop body this expression increments/decrements the loop variable
by some value. for example: $num += 2;
BSC SEMESTER – V 26 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Flowchat
Example:
<?php
// code to illustrate for loop
for ($num = 1; $num <= 5; $num += 1)
{
echo "$num \n";
}?>
Output: 1
2
3
4
5
2. while loop: The while loop is also an entry control loop like for loops i.e., it first checks the condition at
the start of the loop and if it is true then it enters the loop and executes the block of statements until
particular condition is false.
BSC SEMESTER – V 27 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Syntax:
while (if the condition is true)
{
// code is executed
Inc/dec;
}
Flowchart:
Example:
<?php
$n=1;
while($n<=5)
{
echo "$n<br/>";
$n++;
?>
Output:
1
2
3
4
5
BSC SEMESTER – V 28 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
3. do-while loop: This is an exit control loop which means that it first enters the loop, executes the
statements, and then checks the condition. Therefore, a statement is executed at least once on using the
do…while loop. After executing once, the program is executed as long as the condition holds true.
Syntax:
do
{
//code to be executed
}while(condition);
Flowchart:
Example
<?php
$n=1;
do
{
echo "$n<br/>";
$n++;
}while($n<=5);
BSC SEMESTER – V 29 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
?>
Output:
1
2
3
4
5
<?php
$display_prices = true; if
($display_prices) {
echo“<table border=\”1\”>\n”;
echo “<tr><td colspan=\”3\”>”;
echo “today’s prices in dollars”;
echo “</td></tr>”;
echo“<tr><td>\$14.00</td><td>\$32.00</td><td>\$71.00</td></tr>\n”; echo “</table>”;
}
?>
If the value of $display_prices is set to true in line 2, the table is printed. Put these lines into a text file
called testmultiecho.php and place this file in your web server document root.
BSC SEMESTER – V 30 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Function: A function is a block of code written in a program to perform some specific task.. It can take
input as argument list and return value. There are thousands of built-in functions in PHP.
PHP provides us with two major types of functions:
Built-in functions : PHP provides us with huge collection of built-in library functions. These functions
are already coded and stored in form of functions. To use those we just need to call them as per our
requirement like, var_dump, fopen(), print_r(), gettype() and so on.
User Defined Functions : Apart from the built-in functions, PHP allows us to create our own
customized functions called the user-defined functions. Using this we can create our own packages of
code and use it wherever necessary by simply calling it.
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.
Creating a Function
While creating a user defined function we need to keep few things in mind:
1. Any name ending with an open and closed parenthesis is a function.
2. A function name always begins with the keyword function.
3. To call a function we just need to write its name followed by the parenthesis
4. A function name cannot start with a number. It can start with an alphabet or underscore.
5. A function name is not case-sensitive.
Syntax:
function function_name()
{
executable code;
}
PHP Functions Example:
<?php
function sayHello(){
BSC SEMESTER – V 31 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Calling functions
Functions come in two flavors: those built in to the language and those you define yourself. PHP has
hundreds of built-in functions. Look at the following snippet for an example of a function in use:
strtoupper(“Hello Web!”);
A function call consists of the function name (strtoupper in this case) followed by
parentheses. If you want to pass information to the function, you place it between these
parentheses. A piece of information passed to a function in this way is called an argument.
Some functions require that more than one argument be passed to them, separated by
commas:
some_function($an_argument, $another_argument);
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
Returning Values from User-Defined Functions
A function can return a value using the return statement in conjunction with a value.
The return statement stops the execution of the function and sends the value back to
the callingcode.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
function sum($x, $y) {
$z = $x +
$y;return
$z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
BSC SEMESTER – V 32 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
VARIABLE SCOPE
In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where
the variable can be referenced/used.
PHP has three types of variable scopes:
1. Local variable
2. Global variable
3. Static variable
1. Local variable: The variables that are declared within a function are called local variables for that
function. These local variables have their scope only in that particular function in which they are declared.
This means that these variables cannot be accessed outside the function, as they have local scope.
Example:
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Output:
Local variable declared inside the function is: 45
2. Global variable: The global variables are the variables that are declared outside the function. These
variables can be accessed anywhere in the program. To access the global variable within a function, use the
GLOBAL keyword before the variable. However, these variables can be directly accessed or used outside the
function without any keyword. Therefore there is no need to use any keyword to access a global variable
outside the function.
Let's understand the global variables with the help of an example:
BSC SEMESTER – V 33 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Example:
<?php
$name = "ABC"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Output:
Variable inside the function: ABC
Variable outside the function: ABC
3. Static variable: Normally, when a function is completed/executed, all of its variables are deleted.
However, sometimes we want a local variable NOT to be deleted. We need it for a further job. To do this, use
the static keyword when you first declare the variable:
Example
<?php
function myTest()
{
static $x = 0;
echo $x;
$x++;
}
myTest();
BSC SEMESTER – V 34 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
If you declare a variable within a function in conjunction with the static statement, the variable remains
local to the function, and the function “remembers” the value of the variable from execution to
execution.
<?php
function numberedHeading($txt)
{
static $num_of_calls = 0;
$num_of_calls++;
echo “<h1>”.$num_of_calls.” “. $txt.”</h1>”;
}
numberedHeading(“Widgets”);
echo “<p>We build a fine range of
widgets.</p>”;numberedHeading(“Doodads”);
echo “<p>Finest in the world.</p>”;
?>
We can pass the information in PHP function through arguments which is separated by comma. PHP
supports 4 types of function arguments
1. Call by Value (default),
2. Call by Reference
3. Default argument values
4. Variable-length argument list.
1. Call by Value: Call by value means passing the value directly to a function. The called function uses the
value in a local variable; any changes to it do not affect the source variable. Let's see the 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:
BSC SEMESTER – V 35 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
BSC SEMESTER – V 36 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL
Output:
Hello Rajesh
Hello Sonoo
Hello John
4. Returning Value
Let's see an example of PHP function that returns value.
Example:
<?php
function cube($n)
{
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27
BSC SEMESTER – V 37 |P a g e
WEB APPLICATIONS DEVELOPMENT USING PHP & MYSQL
UNIT II
ARRAYS
Arrays: An array is a collection of similar types of data. It is used to hold multiple values of similar type in a
single variable.
Advantage of PHP Array:
1. Less Code: We don't need to define multiple variables.
2. Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
3. Sorting: We can sort the elements of array.
TYPES OF ARRAYS IN PHP: There are 3 types of array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
1. 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:
Example:
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
2nd way:
Example:
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
A function in arrays in PHP is a built-in or user-defined function that helps perform various operations on
arrays. These functions allow us to add, remove, search, filter, and modify elements in an array easily. PHP
provides many array functions like count(), array_push(), array_merge(), etc., to handle arrays efficiently.
Using these functions makes code shorter and easier to manage.
1.array():This function is used to create an array. It allows you to store multiple values in one variable.
Example: $fruits = array("Apple", "Banana", "Mango");
print_r($fruits);
2.count():This function counts the number of elements in an array. It is useful to check how many values are stored.
Example: $numbers = array(10, 20, 30, 40);
echo count($numbers);
4.array_pop():It removes the last element from an array and returns it.
Example: $items = array("Pen", "Pencil", "Eraser");
array_pop($items);
print_r($items);
5.array_unshift():This function adds one or more elements to the beginning of an array.
Example: $numbers = array(2, 3, 4);
array_unshift($numbers, 1);
print_r($numbers);
6.array_shift():It removes the first element from an array and returns it.
Example: $cars = array("BMW", "Audi", "Toyota");
array_shift($cars);
print_r($cars);
7.in_array():This function checks if a value exists in an array. It returns true if found, otherwise false.
ZENEX VISION DEGREE Page 37
COLLEGE
Example: $fruits = array("Apple", "Banana", "Mango");
if (in_array("Banana", $fruits))
{
echo "Found";
}
else
{
echo "Not Found";
}
This is the blueprint of the Vehicle that is class, and the Box truck,Sports cae, Sedan car and Pickup truck
are the objects of Vehicle.
In PHP, declare a class using the class keyword, followed by the name of the class and a set of curly braces
({}).
Syntax to Create Class in PHP
<?php
class MyClass
{
// Class properties and methods go here
}
?>
In PHP, to see the contents of the class, use var_dump(). The var_dump() function is used to display the
structured information (type and value) about one or more variables.
Syntax:
var_dump($obj);
Object: Objects are real time entities. Objects are determined from classes in Object-Oriented Programming
like PHP. When a class is specified, we can create any number of objects out of the class.
<?php
$str = "Hello World!"; echo
strrev($str);
?>
Output:
!dlroW olleH
3. trim(), ltrim(), rtrim(), and chop() Functions: It remove white spaces or other characters from the
string. They have two parameters: one string and another charList, which is a list of characters that need to
be omitted.
trim() – Removes characters or whitespaces from both sides.
The date/time functions allow you to get the date and time from the server where your PHP script runs. You
can then use the date/time functions to format the date and time in several ways. Some of the predefined
functions in PHP for date and time are discussed below.
PHP date() Function: The PHP date() function converts timestamp to a more readable date and time
format.
Syntax:
date(format, timestamp)
Explanation:
The format parameter in the date() function specifies the format of returned date and time.
The timestamp is an optional parameter, if it is not included then the current date and time will be used.
Example:
<?php
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
?>
Output:
Today's date is :05/12/2017
Example 2:
ZENEX VISION DEGREE Page 37
COLLEGE
<?php
echo "Today's date in various formats:" . "\n";
echo date("d/m/Y") . "\n";
echo date("d-m-Y") . "\n";
echo date("d.m.Y") . "\n";
echo date("d.M.Y/D");
?>
Output:
Today's date in various formats:
05/12/2017
05-12-2017
05.12.2017
05.Dec.2017/Tue
PHP time() Function: The time() function is used to get the current time as a Unix timestamp (the number
of seconds since the beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT).
Example: The below example explains the usage of the time() function in PHP.
<?php
$timestamp = time();
echo($timestamp);
echo "\n";
echo(date("F d, Y h:i:s A", $timestamp));
?>
Output:
1512486297
December 05, 2017 03:04:57 PM
Creating a form
The example below displays a simple HTML form with two input fields and a submit button:
<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>
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST
method.
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p><label>Name:</label><br/>
<fieldset>
</form>
</body>
</html>
Output:
PHP code is normally mixed with HTML tags. PHP is an embedded language, meaning that you can jump between
raw HTML code and PHP without sacrificing readability.
In order to embed PHP code with HTML, the PHP must be set apart using PHP start and end tags. The PHP
tags tell the web server where the PHP code starts and ends.
Creating Forms: To create a form, you use the <form> element as follows:
<form action="form.php" method="post">
</form>
The <form> element has two important attributes:
action: specifies the URL that processes the form submission. In this example, the form.php will
process the form.
method: specifies the HTTP method for submitting the form. The most commonly used form methods
are POST and GET. In this example, the form method is post.
The form method is case-insensitive. It means that you can use either post or POST. If you don’t specify the
method attribute, the form element will use the get method by default. To retrieve data from get request, we
need to use $_GET, for post request $_POST.
Typically, a form has one or more input elements including text, password, checkbox, radio
button, select, file upload, etc. The input elements are often called form fields.
PHP Get Form: Get request is the default form request. The data passed through get request is visible on the
URL browser so it is not secured. You can send limited amount of data through get request.
File: Save this file as form1.html
<html>
<body>
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>
</body>
</html>
PHP provides a simple and clean way to redirect your visitors to another page that can be either relative or can be
cross domain.
Here is a simple redirection script that will redirect to thank you page if the comment is submitted successfully.
We will use the header('location: thankyou.html')function to redirect to thethank you page. The location is the
parameter along with the path to file in the header() function.
PHP code with HTML to redirect to another page:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$comment = $_POST['comment'];
$name = $_POST['name']; if($comment && $name) { header('location: thankyou.html');
}}
?>
<form action="comment.php" method="POST">
<input type="text" name="Name">
ZENEX VISION DEGREE Page 59
COLLEGE
<textarea name="comment"></textarea>
<input type="submit" value="submit">
</form>
</body>
</html>
This is a simple PHP script, so we put a form that inputs a name and comment. In the PHP script we check if the
server request method is post because we don’t want this code to execute if user hasn’t submitted the form through
POST method, which is only possible if he submit the form
Next, we store the values received in $comment and $name variables. Then we check if they are not empty, that is
they have some value, then we redirect the visitor to thankyou.html page.
thankyou.html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p>Thank you!</p>
</body>
</html>
So this is how you redirect to another page using header() function in PHP.
The thank you page contains a simple thank you message in html file, since it is just for display.
2 Subject
Required. Specifies the subject of the email. This parameter cannot contain any
newline characters
4 Headers
Optional. Specifies additional headers, like From, Cc, and Bcc. The additional
headers should be separated with a CRLF (\r\n)
5 Parameters
Optional. Specifies an additional parameter to the send mail program
As soon as the mail function is called PHP will attempt to send the email then it will return true if
successful or false if it is failed. Multiple recipients can be specified as the first argument to the mail()
function in a comma separated list.
WORKING WITH FILE UPLOADS
PHP allows you to upload single and multiple files through few lines of code only. PHP file upload
features allow you to upload binary and text files both.
PHP $_FILES: The PHP global $_FILES contains all the information of file. By the help of $_FILES
global, we can get file name, file type, file size, temp file name and errors associated with file.
PHP would create following five variables −
$_FILES['file']['tmp_name'] − the uploaded file in the temporary directory on the web server.
$_FILES['file']['name'] − the actual name of the uploaded file.
$_FILES['file']['size'] − the size in bytes of the uploaded file.
$_FILES['file']['type'] − the MIME type of the uploaded file.
$_FILES['file']['error'] − the error code associated with this file upload.
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.
ZENEX VISION DEGREE Page 61
COLLEGE
The PHP script confirms the success to the user.
PHP File Upload Example
File: uploadform.html
<form action="uploader.php" method="post" enctype="multipart/form-data">
Select File:
<input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
File: uploader.php
<?php
$target_path = "e:/";
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>
Output:
<?php
SETTING A COOKIE WITH PHP: PHP provided setcookie() function to set a cookie. This function
requires upto six arguments and should be called before <html> tag. For each cookie this function has to be
called separately.
Syntax: setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments –
Name − This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value − This sets the value of the named variable and is the content that you actually want to store.
Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time
cookie will become inaccessible. If this parameter is not set then cookie will automatically expire
when the Web Browser is closed.
PHP can automatically append the session ID to URLs if cookies are disabled. To enable ensure
this, session.use_trans_sid is set to 1 in your php.ini file or at runtime:
ini_set('session.use_trans_sid', 1);
session_start();
When this is enabled, PHP will automatically append the session ID to URLs when cookies are not available.
2. Manually Append Session ID
You can manually append the session ID to the query string using SID (a predefined constant in PHP)
or session_id():
session_start();
mysqli_close($conn); ?>
PLANNING AND CREATING A DATABASE TABLES
The CREATE TABLE statement is used to create a table in MySQL. We will create a table named
"MyGuests", with five columns: "id", "firstname", "lastname", "email" and "reg_date": Each table should have
a primary key column (in this case: the "id" column). Its value must be unique for each record in the table.
The following examples shows how to create the table in PHP:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
Online address book will contain several actions, so it makes sense to create a menu for your links. The
below program creates a menu for all the scripts you will create in this section, called mymenu.php
Example
<html>
<head>
<title>My Address Book</title>
</head>
<body>
<h1>My Address Book</h1>
<p><strong>Management</strong>
<ul>
<li><a href="addentry.php">Add an Entry</a>
<li><a href="delentry.php">Delete an Entry</a>
</ul>
<p><strong>Viewing</strong>
<ul>
<li><a href="selentry.php">Select a Record</a>
</ul>
ZENEX VISION DEGREE Page 76
COLLEGE
</body>
</html>
OUTPUT:
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
// Create PDO instance
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
To view records in PHP, you'll query your database and then display the results, typically in an HTML table.
Below is a complete example that fetches and shows all users from a MySQL table.
Database Table (MySQL)
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);
PHP Script to View Records (view_users.php)
<?php
// Database configuration
$host = 'localhost';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
// Connect to database
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
<!DOCTYPE html>
<html>
<head>
<title>View Users</title>
<style>
table { border-collapse: collapse; width: 50%; }
th, td { border: 1px solid #ccc; padding: 8px; }
th { background-color: #f4f4f4; }
</style>
</head>
<body>
<h2>Registered Users</h2>
// Fetch records
$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>User List</title>
</head>
<body>
<h2>User List</h2>
</body>
</html>
try {
$pdo = new PDO("mysql:host=localhost;dbname=your_database", "your_username", "your_password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);