0% found this document useful (0 votes)
19 views82 pages

Web Applications Development Using PHP & Mysql

The document outlines a course on Web Applications Development using PHP and MySQL, covering fundamental topics such as PHP syntax, data types, functions, arrays, objects, forms, cookies, sessions, and MySQL integration. It emphasizes PHP's characteristics, including its open-source nature, performance, and ease of use, while also providing examples and rules for variable declaration and data handling. The course includes recommended textbooks and references for further reading.

Uploaded by

Pacha Omkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views82 pages

Web Applications Development Using PHP & Mysql

The document outlines a course on Web Applications Development using PHP and MySQL, covering fundamental topics such as PHP syntax, data types, functions, arrays, objects, forms, cookies, sessions, and MySQL integration. It emphasizes PHP's characteristics, including its open-source nature, performance, and ease of use, while also providing examples and rules for variable declaration and data handling. The course includes recommended textbooks and references for further reading.

Uploaded by

Pacha Omkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL

WEB APPLICATIONS DEVELOPMENT USING PHP & MYSQL


Unit-1
The Building blocks of PHP: Variables, Data Types, Operators and Expressions, Constants.
Flow Control Functions in PHP: Switching Flow, Loops, Code Blocks and Browser Output.
Working with Functions: What is function?, Calling functions, Defining Functions, Returning the values
from User- Defined Functions, Variable Scope, Saving state between Function calls with the static
statement, arguments of functions.

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).

2. Steven Holzner , PHP: The Complete Reference, McGraw-Hill

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

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>

Output: My first PHP page


Hello World!
STRUCTURE OF PHP: PHP is an embedded scripting language when used in Web pages. This means that
PHP code is embedded in HTML code. You use HTML tags to enclose the PHP language that you embed in
your HTML file — the same way that you would use other HTML tags. We create and edit Web pages
containing PHP the same way that you create and edit regular HTML pages.

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

Rules for declaring PHP variable:


o As PHP is a loosely typed language, so we do not need to declare the data types of the variables. It
automatically analyzes the values and makes conversions to its correct datatype.
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a number or special symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.
Syntax for creating variable:
$variablename=value;
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
DATA TYPES

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.

Operator Name Example Explanation

+ Addition $a + $b Sum of operands

- Subtraction $a - $b Difference of operands

* Multiplication $a * $b Product of operands

/ Division $a / $b Quotient of operands

% Modulus $a % $b Remainder of operands

** Exponentiation $a ** $b $a raised to the power $b

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 "=".

Operator Name Example Explanation

= Assign $a = $b The value of right operand is assigned to the


left operand.

+= Add then Assign $a += $b Addition same as $a = $a + $b

-= Subtract then $a -= $b Subtraction same as $a = $a - $b


Assign

*= Multiply then $a *= $b Multiplication same as $a = $a * $b


Assign

/= Divide then $a /= $b Find quotient same as $a = $a / $b


Assign
(quotient)

%= Divide then $a %= $b Find remainder same as $a = $a % $b


Assign
(remainder)
Example:
<?php
$x = 10;
echo $x . "<br>"; // Outputs: 10
$x = 20;
$x += 30;
echo $x . "<br>"; // Outputs: 50
$x = 50;
$x -= 20;
echo $x . "<br>"; // Outputs: 30
$x = 5;
$x *= 25;
echo $x . "<br>"; // Outputs: 125
$x = 50;

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.

Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === Returns true if $x is equal to $y, and they are of the same type
$y

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same
type

> Greater than $x > $y Returns true if $x is greater than $y

BSC SEMESTER – V 14 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or $x >= $y Returns true if $x is greater than or equal to $y


equal to

<= Less than or $x <= $y Returns true if $x is less than or equal to $y


equal to

<=> 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.

Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

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.

Operator Name Example Result

And And $x and $y True if both $x and $y are true

BSC SEMESTER – V 15 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL

Or Or $x or $y True if either $x or $y is true

Xor Xor $x xor $y True if either $x or $y is true, but not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

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:

Operator Name Example Explanation

. Concatenation $a . $b Concatenate both $a and $b

.= Concatenation and $a .= $b First concatenate $a and $b, then assign the


Assignment concatenated string to $a, e.g. $a = $a . $b

7. 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 Result

+ Union $x + $y Union of $x and $y

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

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non- $x !== $y Returns true if $x is not identical to $y


identity

8. Conditional assignment operators: The PHP conditional assignment operators are used to set a
value depending on conditions:

Operator Name Example Result

?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.


The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE

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)

 name: Specifies the name of the constant

 value: Specifies the value of the constant

BSC SEMESTER – V 17 |P a g e
ZENEX VISION DEGREE COLLEGE WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL

 Case-insensitive: Specifies whether the constant name should be case-insensitive.

 Constants are case sensitive in PHP

 Constants are Global

 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.

FLOW CONTROL FUNCTIONS IN PHP


Flow Control Functions in PHP: PHP supports a number of traditional programming constructs for
controlling the flow of execution of a program. Control statements are conditional statements that execute
a block of statements if the condition is correct. The statement inside the conditional block will not
execute until the condition is satisfied.
CONDITIONAL STATEMENTS: PHP provides us with five conditional statements:
1. if statement
2. if…else statement
3. if…elseif…else statement

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

if ($age >= 18)


{
echo "Eligible to give vote";
}
else
{
echo "Not eligible to give vote";
}
}
?>
Output:
Eligible to give vote
5. switch statement: The “switch” performs in various cases i.e., it has various cases to which it matches
the condition and appropriately executes a particular case block. It first evaluates an expression and then
compares with the values of each case. If a case matches then the same case is executed. To use switch, we
need to get familiar with two different keywords namely, break and default.
1. The break statement is used to stop the automatic control flow into the next cases and exit from the
switch case.
2. The default statement contains the code that would execute if none of the cases match.
Syntax:
switch(expression)
{
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}

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

echo "Your favorite color is green!";


break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}?>
LOOPING STATEMENTS

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

Code Blocks and Browser Output


Imagine a script that outputs a table of values only when a variable is set to the
Boolean value true. The following code shows a simplified HTML table constructed
with the code block of an if statement.

<?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

WORKING WITH FUNCTIONS

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

echo "Hello PHP Function";


}
sayHello();//calling function
?>
Output:
Hello PHP Function

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

echo "7 + 13 = " . sum(7,13) .


"<br>";echo "2 + 4 = " . sum(2,4);
?>
</body>
</html>

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();

Saving State Between Function Calls with the static Statement:


Local variables within functions have a short but happy life—they come into being when the function is
called and die when execution is finished, as they should. Occasionally, however, you might want to give
a function a rudimentary memory. Assume that you want a function to keep track of the number of times
it has been called so that numbered headings can be created by a script.

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>”;
?>

PHP FUNCTION ARGUMENTS

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

Hello Sonoo, you are 27 years old


Hello Vimal, you are 29 years old
Hello John, you are 23 years old
2. Call By Reference: Value passed to the function doesn't modify the actual value by default (call by
value). But we can do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you need to use
ampersand (&) symbol before the argument name.
Let's see a simple example of call by reference in PHP.
Example:
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello Call By Reference
3. Default Argument Value: We can specify a default argument value in function. While calling PHP
function if you don't specify any argument, it will take the default argument.
Let's see a simple example of using default argument value in PHP function.
Example:
<?php
function sayHello($name="Sonoo")
{
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>

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";

echo "Season are: $season[0], $season[1], $season[2] and $season[3]";


ZENEX VISION DEGREE Page 37
COLLEGE
?>
Output:
Season are: summer, winter, spring and autumn
2. 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");
Example
<?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
2nd way:
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
Example:
<?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/>";
?>

ZENEX VISION DEGREE Page 37


COLLEGE
Output:
Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000
3. Multidimensional Array: PHP multidimensional array is also known as array of arrays. It allows you to
store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is
represented by row * column.
Example:
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
for ($row = 0; $row < 3; $row++)
{
for ($col = 0; $col < 3; $col++)
{
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000

ZENEX VISION DEGREE Page 37


COLLEGE
ARRAY RELATED FUNCTIONS

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);

3.array_push():It adds one or more values at the end of an array


Example: $colors = array("Red", "Blue");
array_push($colors, "Green", "Yellow");
print_r($colors);

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";
}

8.array_merge():It merges two or more arrays into one new array.


Example: $arr1 = array(1, 2);
$arr2 = array(3, 4);
$result = array_merge($arr1, $arr2);
print_r($result);

9.array_keys():This function returns all the keys from an associative array.


Example: $data = array("name" => "John", "age" => 25);
print_r(array_keys($data));

10.array_values():It returns all the values from an array without keys.


Example: $data = array("name" => "John", "age" => 25);
print_r(array_values($data));

11.array_slice():It extracts a portion of an array without changing the original array.


Example: $letters = array("a", "b", "c", "d");
print_r(array_slice($letters, 1, 2));

12.array_splice():This function removes or replaces part of an array.


Example: $letters = array("a", "b", "c", "d");
array_splice($letters, 1, 2, array("x", "y"));
print_r($letters);

ZENEX VISION DEGREE Page 37


COLLEGE
13.array_reverse():It reverses the order of elements in an array.
Example: $numbers = array(1, 2, 3, 4);
print_r(array_reverse($numbers));

14.array_unique():This function removes duplicate values from an array.


Example: $values = array(1, 2, 2, 3, 4, 4);
print_r(array_unique($values));

15.array_sum():It returns the sum of all numeric values in an array.


Example: $numbers = array(10, 20, 30);
echo array_sum($numbers);

ZENEX VISION DEGREE Page 37


COLLEGE
WORKING WITH OBJECTS
PHP WITH OOPS CONCEPT
Object-oriented programming is a programming model organized around Object rather than the
actions and data rather than logic.
Class: A class is an entity that determines how an object will behave and what the object will contain. In
other words, it is a blueprint or a set of instruction to build a specific type of object.

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.

ZENEX VISION DEGREE Page 37


COLLEGE
Creating an object and accessing object Instances: Following is an example of how to create object using new
operator.
Syntax:
<?php
class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>
Example of class and object:
<?php
class SayHello
{
function hello()
{
echo "Hello World";
}
}
$obj=new SayHello;
$obj->hello();
?>
Output: Hello World
ZENEX VISION DEGREE Page 37
COLLEGE
STRING FUNCTIONS OR MANIPULATING STRINGS WITH PHP
PHP provides various string functions to access and manipulate strings. A list of PHP string functions are given
below.
1. strlen() Function: It returns the length of the string i.e. the count of all the characters in the string
including whitespaces characters.
Syntax:
strlen(string or variable name)
Example:
<?php
$str = "Hello World!";
// Prints 12 as output
echo strlen($str);
// Prints 13 in a new line
echo "<br>" . strlen("zenexvision");
?>
Output:
12
11
2. strrev() Function: It returns the reversed string of the given string.
Syntax:
strrev(string or variable name)
Example:

<?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.

ZENEX VISION DEGREE Page 37


COLLEGE
 rtrim() & chop() – Removes characters or whitespaces from right side.
 ltrim() – Removes characters or whitespaces from the left side.
Syntax:
rtrim(string, charList)
ltrim(string, charList)
trim(string, charList)
chop(string, charList)
Example:
<?php
$str = "\nThis is an example for string functions.\n";
// Prints original string
echo $str. "<br>";
// Removes whitespaces from right end
echo chop($str) . "<br>";
// Removes whitespaces from both ends
echo trim($str) . "<br>";
// Removes whitespaces from right end
echo rtrim($str) . "<br>";
// Removes whitespaces from left end
echo ltrim($str);
?>

Output: This is an example for string


functions. This is an example for string
functions. This is an example for string
functions. This is an example for string
functions. This is an example for string
functions.

ZENEX VISION DEGREE Page 37


COLLEGE
4. strtoupper() Function: The strtoupper() function returns string in uppercase letter.
Syntax:
strtoupper (string)
Example:
<?php
$str="Zenex Vision College";
$str=strtoupper($str);
echo $str;
?>
Output:
ZENEX VISION COLLEGE
5. strtolower() function: The strtolower() function returns string in lowercase letter
Syntax:
strtolower(string)
Example:
<?php
$str=" Zenex Vision College ";
$str=strtolower($str);
echo $str;
?>
Output:
Zenex vision college
6. ucfirst() function: The ucfirst() function returns string converting first character into uppercase. It doesn't
change the case of other characters.
Syntax
ucfirst(strin )
Example
<?php
$str="Zenex College";
$str=ucfirst($str); echo
$str;
?>

ZENEX VISION DEGREE Page 37


COLLEGE
Output:
ZENEX College
7. lcfirst() function: The lcfirst() function returns string converting first character into lowercase. It doesn't
change the case of other characters.
Syntax
string lcfirst ( string $str )
Example
<?php
$str="Zenex College";
$str=lcfirst($str);
echo $str;
?>
Output:
zenex College
8. ucwords() function: The ucwords() function returns string converting first character of each word into
uppercase.
Syntax
string ucwords ( string $str )
Example
<?php
$str="zenex college";
$str=ucwords($str);
echo $str;
?>
Output:
Zenex College
9. strcmp() Function: The strcmp() function is used to compare two strings. It returns true if two strings are
equal otherwise returns false.
Syntax:
strcmp(string1,string2)

ZENEX VISION DEGREE Page 37


COLLEGE
Example:
<html>
<body>
<?php
echo strcmp("Hello world!","Hello world!");
?>
<p>If this function returns 0, the two strings are equal.</p>
</body>
</html>
Output:
0
If this function returns 0, the two strings are equal.
DATE AND TIME FUNCTIONS IN PHP

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

ZENEX VISION DEGREE Page 37


COLLEGE
WEB APPLICATIONS DEVELOPMENT USING PHP & MYSQL
UNIT III
WORKING WITH FORMS
HTML FORM: HTML form is a section of a document which contains controls such as text fields,
password fields, checkboxes, radio buttons, submit button, menus etc.
<form> is a HTML element to collect input data with containing interactive controls. It provides
facilities to input text, number, values, email, password, and control fields such as checkboxes, radio
buttons, submit buttons, etc., or in other words, form is a container that contains input elements like text,
email, number, radio buttons, checkboxes, submit buttons, etc.
Syntax:
<form>
<!--form elements-->
</form>
The <form> element is a container for different types of input elements, such as: text fields, checkboxes,
radio buttons, submit buttons, etc.

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.

Accessing / Reading form Data


To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>

ZENEX VISION DEGREE Page 52


COLLEGE
</body>
</html>

Accessing Form Input with User-Defined Arrays


HTML forms are required, when you want to collect some data from the site visitor. For
example, during user registration you would like to collect information such as name, e-mail
address, credit card etc., The following are the form elements.
<form> Defines an HTML form for user input

<input> Defines an input control

<textarea> Defines a multiline input control (text area)

<label> Defines a label for an <input> element

<fieldset> Groups related elements in a form

<legend> Defines a caption for a <fieldset> element

<select> Defines a drop-down list

<optgroup> Defines a group of related options in a drop-down list

<option> Defines an option in a drop-down list

<button> Defines a clickable button

Example:
<!DOCTYPE html>

<html>

<head>

<title>An HTML form with checkboxes</title>

</head>

<body>

<form action=”send_formwithcb.php” method=”POST”>

<p><label>Name:</label><br/>

<input type=”text” name=”user” /></p>

<fieldset>

<legend>Select Some Products:</legend><br/>

<input type=”checkbox” id=”tricorder”name=”products*+” value=”Tricorder”>


ZENEX VISION DEGREE Page 53
COLLEGE
<label for=”tricorder”>Tricorder</label><br/>

<input type=”checkbox” id=”ORAC_AI”name=”products*+” value=”ORAC AI”>


<label for=”ORAC_AI”>ORAC AI</label><br/>

<input type=”checkbox” id=”HAL_2000”name=”products*+” value=”HAL 2000”>


<label for=”HAL_2000”>HAL 2000</label>
</fieldset>

<button type=”submit” name=”submit” value=”submit”>Submit Form</button>

</form>

</body>

</html>

Output:

ZENEX VISION DEGREE Page 54


COLLEGE
COMBINING HTML AND PHP CODE ON A SINGLE PAGE

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>

ZENEX VISION DEGREE Page 55


COLLEGE
Output:

File: Save this file as welcome.php


<?php
$name=$_GET["name"];//receiving name field value in $name variable
echo "Welcome, $name";
?>
Output:

ZENEX VISION DEGREE Page 56


COLLEGE
PHP Post Form: Post request is widely used to submit form that have large amount of data such as file
upload, image upload, login form, registration form etc.
The data passed through post request is not visible on the URL browser so it is secured. You can send large
amount of data through post request.
Let's see a simple example to receive data from post request in PHP.
File: Save this file as form1.html
<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: Save this file as login.php


<?php
$name=$_POST["name"];//receiving name field value in $name variable
$password=$_POST["password"];//receiving password field value in $password variable

echo "Welcome: $name, your password is: $password";


?>

ZENEX VISION DEGREE Page 57


COLLEGE
Using Hidden Fields to Save State
A hidden field behaves the same as a text field, except that the user cannot see it unless he views the HTML
source of the document that contains it. Hidden fields are typically used for three purposes.
<? php
// your php code goes here
Tracking users as they move around within a site.
Hidden fields are used to provide predefined input to a server side program when a variety of static
HTML pages act as front ends to the same program on the server.
Hidden fields are used to store contextual information in pages that are dynamically generated.
<?php
$num_to_guess = 42;
$num_tries = (isset($_POST[num_tries])) ? $num_tries + 1 : 0;
$message = "";
if (!isset($_POST[guess])) {
$message = "Welcome to the guessing machine!";
} elseif ($_POST[guess] > $num_to_guess) {
$message = "$_POST[guess] is too big! Try a smaller number";
} elseif ($_POST[guess] < $num_to_guess) {
$message = "$_POST[guess] is too small! Try a larger number";
} else { // must be equivalent
$message = "Well done!";
}
ZENEX VISION DEGREE Page 58
COLLEGE
$guess = $_POST[guess];
?>
<html>
<head>
<title>Listing 9.8 Saving state with a hidden field</title>
</head>
<body>
<h1><?php print $message ?></h1> Guess number: <?php print $num_tries?>
<form action="<?php print $_SERVER[PHP_SELF] ?>" method="POST">Type your guess here:
<input type="text" name="guess" value="<?php print $guess?>">
<input type="hidden" name="num_tries" value="<?php print $num_tries?>">
</body>
</html>

Redirecting the user


Redirection is an integral part of modern website. If something happens on your website like a user submitted a
comment or logged in, he should be redirected to thank you page or user profile page respectively.

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.

SENDING MAIL ON FORM SUBMISSION


PHP makes use of mail() function to send an email. This function requires three mandatory arguments that
specify the recipient's email address, the subject of the message and the actual message additionally there are
other two optional parameters.
Syntax: mail( to, subject, message, headers, parameters );

Sr.N Parameter & Description


o
1 To
Required. Specifies the receiver / receivers of the email

2 Subject
Required. Specifies the subject of the email. This parameter cannot contain any
newline characters

ZENEX VISION DEGREE Page 60


COLLEGE
3 Message
Required. Defines the message to be sent. Each line should be separated with a
LF (\n). Lines should not exceed 70 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:

ZENEX VISION DEGREE Page 62


COLLEGE
Exception Handling in PHP
An exception is an unexpected program result that can be handled by the program itself. Exception Handling in
PHP is almost similar to exception handling in all programming languages.
PHP provides the following specialized keywords for this purpose.

 try: It represents a block of code in which exceptions can arise.


 catch: It represents a block of code that will be executed when a particular exception has been thrown.
 throw: It is used to throw an exception. It is also used to list the exceptions that a function throws, but doesn’t
handle itself.
 finally: It is used in place of a catch block or after a catch block basically it is put for cleanup activity in PHP
code.
Example:

<?php

// PHP Program to illustrate normal


// try catch block code
function demo($var) {

echo " Before try block";


try {
echo "\n Inside try block";

ZENEX VISION DEGREE Page 63


COLLEGE
// If var is zerothen only if will be executed
if($var == 0) {

// If var is zero then only exception is thrown


throw new Exception('Number is zero.');

// This line will never be executed


echo "\n After throw it will never be executed";
}
}

// Catch block will be executed only


// When Exception has been thrown by try block
catch(Exception $e) {
echo "\n Exception Caught" . $e->getMessage();
}
finally {
echo "\n Here cleanup activity will be done";
}

// This line will be executed whether


// Exception has been thrown or not
echo "\n After catch it will be always executed";
}

// Exception will not be raised


demo(5);

// Exception will be raised here


demo(0);
?>

ZENEX VISION DEGREE Page 64


COLLEGE
UNIT IV

WORKING WITH COOKIES AND USER SESSIONS


INTRODUCING COOKIES: PHP cookie is a small piece of information which is stored at client browser.
It is used to recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends request to the server, cookie
is embedded with request. Such way, cookie can be received at the server side.

There are three steps involved in identifying returning users −


 Server script sends a set of cookies to the browser. For example name, age, or identification number
etc.
 Browser stores this information on local machine for future use.
 When next time browser sends any request to web server then it sends those cookies information to
the server and server uses that information to identify the user.

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.

ZENEX VISION DEGREE Page 65


COLLEGE
 Path − This specifies the directories for which the cookie is valid. A single forward slash character
permits the cookie to be valid for all directories.
 Domain − This can be used to specify the domain name in very large domains and must contain at
least two periods to be valid. All cookies are only valid for the host and domain which created them.
 Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission
using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
PHP Cookie Example
File: cookie1.php
<?php
setcookie("user", "Sreenu");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"]))
{
echo "Sorry, cookie is not found!";
}
else
{
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
Output:
Sorry, cookie is not found!
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
Cookie Value: Sreenu

ZENEX VISION DEGREE Page 66


COLLEGE
SESSION INTRODUCTION: When we work with an application, we open it, do some changes, and then
we close it. This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server does not know who
you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages
(e.g. username, favorite color, etc). By default, session variables last until the user closes the browser. So
Session variables hold information about one single user, and are available to all pages in one application.
PHP SESSION: PHP session is used to store and pass information from one page to another temporarily
(until user close the website). Session identifiers or SID is a unique number which is used to identify every
user in a session based environment. The SID is used to link the user with his information on the server
like posts, emails etc. PHP session technique is widely used in shopping websites where we need to store and
pass cart information e.g. username, product code, product name, product price etc from one page to another.

PHP session_start() function


PHP session_start() function is used to start the session. It starts a new or resumes existing session. It returns
existing session if session is created already. If session is not available, it creates and returns new session.
Syntax
bool session_start (void)
Example
session_start();
PHP $_SESSION: PHP $_SESSION is an associative array that contains all session variables. It is used to
set and get session variable values.
Example: Store information
$_SESSION["user"] = "Sachin";
Example: Get information
echo $_SESSION["user"];

ZENEX VISION DEGREE Page 67


COLLEGE
PHP Session Example
//Save file as session1.php
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["user"] = "zenex";
echo "Session information are set successfully.<br/>";
?>
<a href="session2.php">Visit next page</a>
</body>
</html>
//Save file as session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body>
</html>

ZENEX VISION DEGREE Page 68


COLLEGE
OUTPUT:

ZENEX VISION DEGREE Page 69


COLLEGE
Working with session variables PHP
You can access a session variable’s value by using the global variable $_SESSION. In the example stated below,
you will create another session with a variable that stores your name.
Example:
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["name"] = "Simplilearn";
echo "Information set in a variable.<br/>";
?>
</body>
</html>
Output:
SessioninPHP_1
Now that the variable is set, you will access it from another file. Create another file and write the following
code to access the name variable you have just set.
Note: Load both the pages without closing the browser, as it will end the session.
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["name"];
?>
</body>
</html>
Output:
SessioninPHP_2

ZENEX VISION DEGREE Page 70


COLLEGE
Passing session IDs in the Query String
Passing session IDs via query strings in PHP can be done, but it is generally discouraged due to security concerns,
such as exposing session IDs in URLs, which can be logged or shared unintentionally. However, if you still need to
do this, here's how it can be achieved:
1. Enable Transparent Session ID Handling

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();

// Example of appending session ID to a URL


$url = "example.php?" . SID; // SID includes "PHPSESSID=session_id"
echo '<a href="' . $url . '">Click Here</a>';

// Alternatively, use session_id()


$url = "example.php?PHPSESSID=" . session_id();
echo '<a href="' . $url . '">Click Here</a>';

Destroy a Session and Unsetting Variables in PHP


Although the web server will terminate the session by default upon closing the browser, you can also destroy
it manually. Two functions can help you achieve this.
session_destroy(): Calling this function will eliminate all the session variables
unset(): Calling this function will kill only the specified session variable
You can also use the session_unset() function to remove all the variables of a session. Let’s look at how to
destroy the counter variable that you have created in one of the sessions above.
Example: Using unset() to Destroy a Session Variable
<?php
ZENEX VISION DEGREE Page 71
COLLEGE
unset($_SESSION[‘counter’]);
?>
This will end only the counter variable, but not the others if there are any.
Example: Using session_destroy() to Destroy a Complete Session in PHP
<?php
session_destroy();
?>
The PHP session_destroy() function does not accept any parameter. Simply calling this function will destroy
the entire session in PHP.

ZENEX VISION DEGREE Page 72


COLLEGE
WEB APPLICATIONS DEVELOPMENT USING PHP & MYSQL
UNIT V
INTERACTING WITH MYSQL USING PHP
INTRODUCTION
MySQL: MySQL is the very popular open-source relational database management system which is used by
popular high-volume websites such as Wikipedia, Google, Facebook, YouTube and Twitter as well as many
others across the globe. This original version of MySQL is low-cost, easy to use, install and integrate, is
flexible across many different platforms and is very reliable and scalable and performs well. As a result, over
100 millions copies of the software have been downloaded or distributed throughout its existence.
DIFFERNCES BETWEEN MySQL AND MySQLi
MySQL MySQLi
MySQL extension added in PHP version 2.0. and MySQLi extension added in PHP 5.5 and will work
deprecated as of PHP 5.5.0. on MySQL 4.1.3 or above.
Does not support prepared statements. MySQLi supports prepared statements.
MySQL provides the procedural interface. MySQLi provides both procedural and object-
oriented interfaces.
MySQL extension does not support stored MySQLi supports store procedures.
procedures.
MySQL extension lags in security and other special MySQLi extension with enhanced security and
features, comparatively. improved debugging.
Transactions are handled by SQL queries only. MySQLi supports transactions through API.
Extension directory: ext/mysql. Extension directory: ext/mysqli.
CONNECTING TO MYSQL WITH PHP: PHP is the most popular scripting language for web
development. It is free, open source and server side(the code is executed on the server). MySQL is a
Relational Database Management System(RDBMS) that uses Structured Query Language(SQL). It is also free
and open source. The combination of PHP and MySQL is used to create any kind of website.
Making a Connection: The basic syntax for a connection to MySQL is as follows:
$mysqli=mysqli_connect(“hostname”,”username”,”password”,”database”);
The value of $mysqli is the result of the function and is used in later functions for communicating with
MySQL. With sample values inserted, the connection code looks like as follows:
$mysqli=mysqli_connect(“hostname”,”zenex”,”manager”,”testDB”);

Example program: <?php


ZENEX VISION DEGREE Page 73
COLLEGE
$servername=”localhost”;
$username=”zenex”;
$password=”manager”
$database=”testDB”;
// Create connection
$con=mysqli_connect($servername,$username,$password,$database);
// Check connection
if(!$con)
{
die(“Error detected”.mysqli_error($con));
}
else
{
echo “Connection established successfully”
}
mysqli_close($conn);
?>
OUTPUT:
Connection established successfully
Explanation:
1. The first part of the script is four variables (server name, database, username, and password) and their
respective values. These values should correspond to your connection details.
$servername=”localhost”;
$username=”zenex”;
$password=”manager”
$database=”testDB”;
2. Next is the main PHP function mysqli_connect(). It establishes a connection with the specified database.
// Create connection
$con=mysqli_connect($servername,$username,$password,$database);
3. Following is an “if statement.” It is the part of the code that shows whether the connection was established.
When the connection fails, it gives the message Connection failed. The die function prints the message and
then exits out of the script.
if(!$con)

ZENEX VISION DEGREE Page 74


COLLEGE
{
die(“Error detected”.mysqli_error($con));
}

4. If the connection is successful, it displays “Connected successfully.”


echo “Connection established successfully”
5. When the script ends, the connection with the database also closes. If you want to end the code manually,
use the mysqli_close function.

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),

ZENEX VISION DEGREE Page 75


COLLEGE
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if (mysqli_query($conn, $sql))
{
echo "Table MyGuests created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
OUTPUT:
Table MyGuests created successfully
CREATING MENU

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:

Creating the Record Addition Mechanism

To create a record addition mechanism in PHP, you'll typically be working with:


An HTML form to gather input.
A PHP script that processes the form submission and inserts the data into a database (usually MySQL).
1. Create the Database Table
Assuming you have a MySQL database with a table named users:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE
);

2.HTML Form (form.html)


<!DOCTYPE html>
<html>
<head>
ZENEX VISION DEGREE Page 77
COLLEGE
<title>Add User</title>
</head>
<body>
<h2>Add a New User</h2>
<form action="add_user.php" method="POST">
<label>Name:</label><br>
<input type="text" name="name" required><br><br>

<label>Email:</label><br>
<input type="email" name="email" required><br><br>

<input type="submit" value="Add User">


</form>
</body>
</html>
3.PHP Script to Add Record (add_user.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 {
// Create PDO instance
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

// Check if form was submitted


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get and sanitize user input
$name = trim($_POST['name']);
$email = trim($_POST['email']);

// Prepare SQL and bind parameters


$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");

ZENEX VISION DEGREE Page 78


COLLEGE
$stmt->execute(['name' => $name, 'email' => $email]);

echo "User added successfully!";


}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();}
?>

Viewing RECORDS in PHP

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
]);

// Fetch all records


$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {


ZENEX VISION DEGREE Page 79
COLLEGE
die("Error: " . $e->getMessage());
}
?>

<!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>

<?php if ($users): ?>


<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td><?= htmlspecialchars($user['id']) ?></td>
<td><?= htmlspecialchars($user['name']) ?></td>
<td><?= htmlspecialchars($user['email']) ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php else: ?>
<p>No users found.</p>
<?php endif; ?>

ZENEX VISION DEGREE Page 80


COLLEGE
</body>
</html>

Creating The Record Deletion Mechanism

create a record deletion mechanism in PHP, you need:


A way to identify the record (usually by id).
A PHP script that deletes the record from the database.
Assume you already have a MySQL table like:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
HTML Page to View & Delete (e.g., list_users.php)
This displays users with a Delete link next to each one.
<?php
// Database connection
$pdo = new PDO("mysql:host=localhost;dbname=your_database", "your_username", "your_password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// 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>

<table border="1" cellpadding="5" cellspacing="0">


<tr><th>ID</th><th>Name</th><th>Email</th><th>Action</th></tr>
<?php foreach ($users as $user): ?>
<tr>
<td><?= htmlspecialchars($user['id']) ?></td>
<td><?= htmlspecialchars($user['name']) ?></td>
ZENEX VISION DEGREE Page 81
COLLEGE
<td><?= htmlspecialchars($user['email']) ?></td>
<td>
<a href="delete_user.php?id=<?= $user['id'] ?>" onclick="return confirm('Are you sure you want to delete this
user?');">Delete</a>
</td>
</tr>
<?php endforeach; ?>
</table>

</body>
</html>

Step 2: Deletion Script (e.g., delete_user.php)


<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];

try {
$pdo = new PDO("mysql:host=localhost;dbname=your_database", "your_username", "your_password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Use prepared statement to prevent SQL injection


$stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
$stmt->execute(['id' => $id]);
// Redirect back to user list
header("Location: list_users.php");
exit;
} catch (PDOException $e) {
echo "Error deleting record: " . $e->getMessage();
}
} else { echo "Invalid request.";}

ZENEX VISION DEGREE Page 82


COLLEGE

You might also like