Epa WBP 08 04
Epa WBP 08 04
Web Based Application Development using PHP (22619) T.Y. Diploma: Sem 6
PHP 4.(e) Describe the syntax of if-else control statement with example in 4
PHP.
5.(a) Write a PHP program to display numbers from 1-10 in a 6
sequence using for loop.
Summer- Unit –1 1.(a) State the advantages of PHP (any four). 2
2023 Expressions and 1.(g) State the use of $ sign in PHP. 2
Control statements 2.(a) Write a program using do-while loop. 4
in PHP
5.(a) Implement any three datatypes used in PHP with illustration. 6
Winter- Unit –1 1.(d) State any 2 differences between for and for each. 2
2023 Expressions and 2.(b) Develop a simple program for sending and receiving plain text 4
Control message.
statements in 3.(b) List loop control structures. Explain any one loop control 4
PHP structure.
4.(e) Explain the following terms: i) Variables ii) Datatypes 4
iii) Constant iv) Operators
Summer- Unit –1 1.(a) List the any four advantages of PHP. 2
2024 Expressions and 1.(f) Write a program using Foreach loop. 2
Control 2.(a) Explain use of for and for each loops in PHP.. 4
statements in 5.(a) Explain decision making statements along with their syntax in 6
PHP PHP.
Winter- Unit –1 1.(a) List the any four advantages of PHP. 2
2024 Expressions and 1.(d).State different data types in php 2
Control 2.(a) Explain use of for and for each loops in PHP.. 4
statements in 2.(c) Write PHP Program(i) To find largest of two numbers 2
PHP 3.(b) Explain bitwise operators in php 4
4.(e) Explain print and echo statement in php. 4
Summer- Unit –2 1.(b) What is array? How to store data in array? 2
2022 Arrays, 2.(b) Write a program to create associative array in PHP. 4
functions and 3.(a) Define function. How to define user defined function in PHP? 4
Graphics Give example.
4.(a) Write PHP script to sort any five numbers using array function. 4
6.(b) Explain any four string functions in PHP with example. 6
Winter- Unit –2 2.(b) Explain Indexed array and associative arrays with suitable 4
2022 Arrays, example.
Examination Paper Analysis and Solution
Winter- Unit –2 1.(c) List any four strings functions with use.. 2
2024 Arrays, 1.(e) Explain array-flip and explode function with syntax 2
functions and 3.(d) Explain following methods imagecopyresized 2
Graphics 4.(c) Explain how to implement multidimensional array in php 4
5.(c) Display the given test ‘this is server side coding using php’ in 6
PDF using PHP.
6.(b) Explain following functions types with example 6
i) Anonymos function ii )variable function
2022 OOP Concept in 2.(c) Define Introspection and explain it with suitable example. 4
PHP 3.(b) Explain method overloading with example. 4
4.(b) Write PHP program for cloning of an object. 4
5.(b) Create a class as “Percentage” with two properties length & 4
width. Calculate area of rectangle for two objects. 4
6.(c) (i) What is inheritance? 6
(ii) Write update operation on table data.
Winter- Unit 3 1.(c) State the role of constructor. 2
2022 OOP Concept in 2.(c) Define Introspection and explain it with suitable example. 4
PHP 3.(b) Write syntax to create class and object in PHP. 4
4.(b) Write PHP program for cloning of an object. 4
5.(c) Illustrate class inheritance in PHP with example. 4
6.(c) (i) State the use of serialization. 3
(ii) State the query to insert data in the database. 3
Summer- Unit 3 1.(c) Define introspection. 2
2023 OOP Concept in 2.(c) Define serialization and explain it with suitable example. 4
PHP 3.(b) Explain the concept of cloning of an object 4
4.(b) Describe inheritance, overloading, overriding and cloning 4
object.
5.(c) Explain the concept of constructor and destructor in detail. 6
Winter- Unit 3 1.(c) Explain Cloning object. 2
2023 OOP Concept in 1.(e) Explain classes and object creation. 2
PHP 2.(c) Explain constructor and destructor in PHP 4
3.(b) Develop a PHP program for overloading. 4
5.(a) Write a PHP program on Introspection. 6
6.(b) Develop a PHP program to create constructor to initialize 6
object of class.
Summer- Unit 3 1.(c) Define serialization. 2
2024 OOP Concept in 2.(c) Define introspection and explain it with suitable example. 4
PHP 3.(c) Explain constructor and destructor in PHP 4
4.(b) Write a program to demonstrate concept of inheritance in php. 4
5.(c) Explain method overriding with example . 6
6.(c) Explain interface with example 6
Winter- Unit 3 1.(c) Define inheritance in PHP. 2
Examination Paper Analysis and Solution
2024 OOP Concept in 1.(f) Define class with syntax and example. 2
PHP 2.(a) Demonstrate __--construct() and __destruct() in PHP 4
4.(a) Demonstrate the concept of overlading with example. 4
5.(a) state application of serialization.Illustate with example. 6
6.(c) Explain clone ,class exists get parent class 6
Summer- Unit 4 1.(d) How can we destroy cookies. 2
2022 Creating and 1.(g) How to create session variable in PHP ? 2
Validating 2.(d) Write difference between get( ) & post( ) method of form (Any 4
Forms four points).
3.(c) Define session & cookie. Explain use of session start. 4
4.(c) Create customer form like customer name, address, mobile no, 4
date of birth using different form of input elements & display user
inserted values in new PHP form.
4.(e) How do you validate user inputs in PHP ? 4
6.(a) Write a PHP program to demonstrate use of cookies. 6
Winter- Unit 4 1.(d) State the use of Cookies. 2
2022 Creating and 1.(g) State role of GET and POST methods. 2
Validating 2.(d) Describe : (i) Start session (ii) Get session variable 4
Forms 3.(c) State any four form controls to get user’s input in PHP. 4
4.(c) Write steps to create webpage using GUI components. 4
6.(a) Write a PHP program to set and modify cookies. 6
Summer- Unit 4 1.(d) Enlist the attributes of cookies. 2
2023 Creating and 1.(f) Define GET & POST methods. 2
Validating 2.(d) Describe the procedure of sending email. 4
Forms 3.(c) Describe the procedure of validation of web page. 4
4.(c) explain web server role in web development. 4
4.(e) Create a web page using GUI component. 4
6.(a) Design form controls –text box, text area, radio button, check 6
box, list and buttons
Winter- Unit 4 1.(a) List attributes of cookie. 2
2023 Creating and 2.(a)Develop a simple program for sending and receiving plain text 4
Validating messages.
Forms 3.(a)Differentiate between session and cookie. 4
4.(d)Design web page using following form controls: 4
Examination Paper Analysis and Solution
(ii) mysqli_connect()
Winter- Unit 5 1.(g) Define MySQL. 2
2023 Database 3.(b)Explain following Terms 4
Operations (i) POD::_construct()
(ii) mysqli_connect()
4.(a)Develop a program to connect PHP with MySQL. 4
6.(a) Develop a PHP program to 6
(i)Enter a data into database
(ii) Retrieve and present data from database
Summer- Unit 5 1.(e) List out database operations. 2
2024 Database 3.(d) Explain inserting and retriving the query result operations. 4
Operations 4.(e) Write PHP program to demonstrate delete operations on table 6
data. 6
5.(b) Write PHP program to demonstrate database operations using
PHP and MySQL.
Winter- Unit 5 1.(g) State advantages of PHP-MySQL. 2
2024 Database 2.(c) write php program ii for connecting MySQL server 2
Operations 2.(d) write php program to count total number of rows in the 4
database table.
3.(d) Explain following methods i)MySQL_select_db( ) 4
4.(b) Develop PHP program to create database and insert records in 4
database.
6.(a) Create a html form ‘result.html’ to accept rollno of student 6
using submit button. Write ‘result.php’ code to check the result of
student ‘pass’ or ‘fail’. Create a table result_table in MySQL
database ‘my-db’ with two columns rollno and status also write php
code to delete a record result_table.
Examination Paper Analysis and Solution
UNIT 1 Expressions and Control statements in PHP
?>
Example: Each code line in PHP must end with a semicolon.
The semicolon is a separator and is used to distinguish one set of instructions from another.
There are two basic statements to output text with PHP: echo and print.
In the example above we have used the echo statement to output the text "Hello World".
Q.3 Write down rules for declaring PHP variables. (S-22) 4 Marks
Ans : Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable.
A variable name must start with a letter or the underscore character.
A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($first_name), or with
capitalisation ($firstName).
Variables used before they are assigned have default values.
A variable name cannot start with a number.
A variable name can only contain alpha-numeric characters (A-Z, a-z) and underscores.
Variable names are case-sensitive ($name and $NAME are two different variables)
You able to use variable over and over again in your PHP script after declaring it.
Variables can, but do not need, to be declared before assignment. PHP automatically converts the variable to the correct data type, depending on its
value.
Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of character.
The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.
The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10.
Example :
<html>
<body>
<?php
$i = 0;
$num = 0;
do {
$i++;
}
while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce the following result −
Loop stopped at i = 10
While Loop-The while loop - Loops through a block of code as long as the specified condition is true.
$i = 1;
while ($i < 6) {
echo $i;
$i++;
}
The while loop does not run a specific number of times, but checks after each iteration if the condition is still true.
The condition does not have to be a counter, it could be the status of an operation or any condition that evaluates to either true or false.
For loop- The for loop - Loops through a block of code a specified number of times.
The for loop is used when you know how many times the script should run.
Examination Paper Analysis and Solution
Syntax-
for (expression1, expression2, expression3) {
// code block
}
This is how it works:
expression1 is evaluated once
expression2 is evaluated before each iteration
expression3 is evaluated after each iteration
example-
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
For each loop- The foreach loop - Loops through a block of code for each element in an array or each property in an object.The most common use of
the foreach loop, is to loop through the items of an array.
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x)
{
echo "$x <br>";
}
$members = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach ($members as $x => $y)
{
echo "$x : $y <br>";
}
Q.8 Explain the use of break and continue statements. (W-22) 4 Marks
Ans: The PHP break keyword is used to terminate the execution of a loop prematurely. The break statement is situated inside the statement block. It gives you
full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.
<?php
$i = 0;
while( $i < 10)
Examination Paper Analysis and Solution
{
$i++;
if( $i == 3 )
break;
}
echo ("Loop stopped at i = $i" );
?>
The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.
Just like the break statement the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional
test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )
continue;
echo "Value is $value <br />";
}
?>
Q.9 Describe the syntax of if-else control statement with example in PHP. (W-22) 4 Marks
Ans The If...Else Statement
If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
<?php
$d = date("D");
if ($d == "Fri")
echo "Have a nice weekend!";
else
Examination Paper Analysis and Solution
echo "Have a nice day!";
?>
Q.10 Write a PHP program to display numbers from 1-10 in a sequence using for loop.
(W-22) 4 Marks
Ans :
<?php
$a = 1;
for( $a = ; $a<=10; $a++ )
{
echo $a;
}
?>
</body>
</html>
This will produce the following result −
Loop stopped at i = 10
Q.14 Implement any three datatypes used in PHP with illustration. (S-23) 6 Marks
Ans:Datatyapes are Array,integer
Array: An array stores multiple values in one single variable and each value is identify by position ( zero is the first p position). The array is a collection of
heterogeneous (dissimilar) data types. PHP is a loosely typed language that’s why we can store any type of values in arrays.
Syntax : Variable_name = array (element1, element2, element3, element4......)
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x) {
echo "$x <br>";
}
Integer:
integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
Examination Paper Analysis and Solution
An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation
In the following example $x is an integer. The PHP var_dump() function returns the data type and value:
Example :
$x = 5985;
var_dump($x);
int(5985)
Boolean :
A Boolean represents two possible states: TRUE or FALSE.
Example :$x = true;
var_dump($x);
Output is bool(true)
Float :
A float (floating point number) is a number with a decimal point or a number in exponential form.
In the following example $x is a float. The PHP var_dump() function returns the data type and value:
Example :
$x = 10.365;
var_dump($x)
float(10.365)
Q.15 State any 2 differences between for and for each. (W-23) 2 Marks
Ans: Difference is as follows
for loop foreach loop
The iteration is clearly visible. The block of code is The iteration is hidden. The block of code is
repeated if the condition is met, or the counter repeated until iterating over the array is completed.
meets a specific value.
Good performance. Better performance.
The stop condition is specified easily. The stop condition must be specified.
Upon working with collections, it needs the usage It can simply work without the usage of the count()
of the count() function. method.
Examination Paper Analysis and Solution
Q.16 List loop control structures. Explain any one loop control structure. (W-23) 4 Marks
Ans : Loop control structures are while,do...while ,for loop and for each loop
Do...while loop :
The do... while statement will execute a code block at least once, it will repeat the loop if a condition is true.
The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than
10.
Example :
<html>
<body>
<?php
$i = 0;
$num = 0;
do {
$i++;
}
while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce the following result −
Loop stopped at i = 10
Q.17 Explain the following terms: i) Variables ii) Datatypes iii) Constant iv) Operators
(W-23) 4 Marks
Ans:
i) Variables:
Variables are "containers" for storing information.
A variable can have a short name (like $x and $y) or a more descriptive name ($age, $carname, $total_volume).
Rules for PHP variables:
o A variable starts with the $ sign, followed by the name of the variable
Examination Paper Analysis and Solution
o A variable name must start with a letter or the underscore character
o A variable name cannot start with a number
o A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
o Variable names are case-sensitive ($age and $AGE are two different variables)
iii) Constant
Constants are like variables, except that once they are defined they cannot be changed or undefined.
A constant is an identifier (name) for a simple value. The value cannot be changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
To create a constant, use the define() function.
Parameters:
o name: Specifies the name of the constant
o value: Specifies the value of the constant
o case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false. Note: Defining case-insensitive constants was deprecated in PHP
7.3. PHP 8.0 accepts only false, the value true will produce a warning.
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
Welcome to W3Schools.com!
ii) Datatypes-
o Variables can store data of different types, and different data types can do different things.
o PHP supports the following data types:
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
iv)operators-
Operators are used to perform operations on variables and values.
Examination Paper Analysis and Solution
PHP divides the operators in the following groups:
o Arithmetic operators
o Assignment operators
o Comparison operators
o Increment/Decrement operators
o Logical operators
o String operators
o Array operators
o Conditional assignment operators
Ans- The Bitwise operators is used to perform bit-level operations on the operands. The operators are first converted to bit-level and then calculation is
performed on the operands. The mathematical operations such as addition , subtraction , multiplication etc. can be performed at bit-level for faster processing.
In PHP, the operators that works at bit level are:
Examination Paper Analysis and Solution
& (Bitwise AND) : This is a binary operator i.e. it works on two operand. Bitwise AND operator in PHP takes two numbers as operands and does AND on
every bit of two numbers. The result of AND is 1 only if both bits are 1.
Syntax:
$First & $Second This will return another number whose bits are
set if both the bit of first and second are set.
Example:
Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise & will be 0001 (i.e. set
if both first and second have their bit set.)
| (Bitwise OR) : This is also binary operator i.e. works on two operand. Bitwise OR operator takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 any of the two bits is 1.
Syntax:
$First | $Second
Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise | will be 0111 (i.e. set
if either first or second have their bit set.)
Examination Paper Analysis and Solution
^ (Bitwise XOR ) : This is also binary operator i.e. works on two operand. This is also known as Exclusive OR operator. Bitwise XOR takes two numbers as
operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
Syntax:
$First ^ $Second
Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise ^ will be 0110 (i.e. set
if either first or second have their bit set but
not both.)
~ (Bitwise NOT) : This is a unary operator i.e. works on only one operand. Bitwise NOT operator takes one number and inverts all bits of it.
Syntax:
~$number
Input: number = 5
Explanation:
Binary representation of 5 is 0101. Therefore the
Examination Paper Analysis and Solution
bitwise ~ of this will be 1010 (inverts all the
bits of the input number)
<< (Bitwise Left Shift) : This is a binary operator i.e. works on two operand. Bitwise Left Shift operator takes two numbers, left shifts the bits of the first
operand, the second operand decides the number of places to shift.
Syntax:
Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise << will shift the bits of 5 one times
towards the left (i.e. 01010 )
Note: Bitwise left shift with one bit is equivalent to multiplication with 2.
>> (Bitwise Right Shift) : This is also binary operator i.e. works on two operand. Bitwise Right Shift operator takes two numbers, right shifts the bits of the first
operand, the second operand decides the number of places to shift.
Syntax:
Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise >> will shift the bits of 5 one times
towards the right(i.e. 010)
Note: Bitwise right shift with one bit is equivalent to division with 2.
<?php
// PHP code to demonstrate Bitwise Operator.
// Bitwise AND
$First = 5;
$second = 3;
$answer = $First & $second;
print_r("\n");
// Bitwise OR
$answer = $First | $second;
print_r("Bitwise | of 5 and 3 is $answer");
print_r("\n");
// Bitwise XOR
$answer = $First ^ $second;
Examination Paper Analysis and Solution
print_r("Bitwise ^ of 5 and 3 is $answer");
print_r("\n");
// Bitwise NOT
$answer = ~$First;
print_r("Bitwise ~ of 5 is $answer");
print_r("\n");
print_r("\n");
print_r("\n");
?>
Output:
$num1 = 10;
$num2 = 20;
?>
Output
Largest Number: 20
Suppose we want to assign ages to a group of high school students with their names.
We can use the Associative array method to get it done. For example:
<?php
$course = array("CO"=>549, "IF"=>450,"EJ"=>100);
echo "course['CO']=", $course["CO"],"<br>";
echo "course['IF']=", $course["IF"],"<br>";
echo "course['EJ']=", $course["EJ"],"<br>";
?>
Q.3 Define function. How to define user defined function in PHP? Give example. (S-22) 4 Marks
Ans
PHP functions are like other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some
processing and returns a value.
They are built-in functions, but PHP gives you option to create your own functions as well. A function will be executed by a call to the function. You
may call a function from anywhere within a page.
Syntax and example :
Examination Paper Analysis and Solution
Example 1
function functionName()
{
code to be executed;
}
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "Welcome to PHP world!";
}
/* Calling a PHP Function */
writeMessage();
?>
Example 2
<?php
function addfunc($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addfunc(50, 20);
?>
Q.4 Write PHP script to sort any five numbers using array function. (S-22) 4 Marks
Ans :
<?php
$num = array(40, 61, 2, 22, 13);
echo "Before Sorting:<br>";
$arrlen= count($num);
for($x = 0; $x < $arrlen; $x++)
Examination Paper Analysis and Solution
{
echo $num[$x];
echo "<br>";
}
sort($num);
echo "After Sorting in Ascending order:<br>";
$arrlen= count($num);
for($x = 0; $x < $arrlen; $x++)
{
echo $num[$x];
echo "<br>";
}
echo "After Sorting in Descending order:<br>";
rsort($num);
$arrlen= count($num);
for($x = 0; $x < $arrlen; $x++)
{
echo $num[$x];
echo "<br>";
}
?>
Q.6 Explain any four string functions in PHP with example. (S-22) 6 Marks
Ans : following are strings functions below:
Word Count -
o The PHP str_word_count() function counts the number of words in a string.
o Example - Count the number of word in the string "Hello world!":
echo str_word_count("Hello world!"); output is 2
Strpos ( ) -
o The PHP strpos() function searches for a specific text within a string.
o If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.
Examination Paper Analysis and Solution
o Example - Search for the text "world" in the string "Hello world!":
strcmp( )-
o Compare two strings (case-sensitive). If this function returns 0, the two strings are equal.If this function returns any negative or positive numbers, the
two strings are not equal.
o Strcmp(String1, String2)
<?php echo strcmp(" world!","Hello PHP!"); ?> output is 40
Q.7 Explain Indexed array and associative arrays with suitable example. (W-22) 6 Marks
Ans :
Indexed array -
o An array with a numeric index where values are stored linearly.
o Numeric arrays use number as access keys.
o An access key is a reference to a memory slot in an array variable.
o The access key is used whenever we want to read or assign a new value an array element.
o Syntax - <?php $variable_name[n] = value; -?> OR
<?php -$variable_name = array(n => value, …); -?>
o Example - <?php $course = array(0 => "Computer Engg.",1 => "Information Tech.",
2 => "Electronics and Telecomm."); echo $course[1]; ?>
Examination Paper Analysis and Solution
Associative array -
o This type of arrays is like the indexed arrays but instead of linear storage, every value can be assigned with a user-defined key of string type.
o An array with a string index where instead of linear storage, each value can be assigned a specific key.
o Associative array differ from numeric array in the sense that associative arrays use descriptive names for id keys.
o Syntax : <?php $variable_name['key_name'] = value;
$variable_name = array('keyname' => value); ?>
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "Welcome to PHP world!";
}
/* Calling a PHP Function */
writeMessage();
?>
Examination Paper Analysis and Solution
Example 2
<?php
function addfunc($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addfunc(50, 20);
?>
Q.9 Write a PHP program to (i) Calculate length of string (ii) Count number of words in the string(W-22) 6 Marks
Ans : (i) Calculate length of string - Returns the length of a string
<?php echo strlen("Welcome to PHP"); ?> output is 14
(ii) Count number of words in the string - Count the number of words in a string
<?php echo str_word_count("Welcome to PHP world!"); ?> output is 4
Q.10 State the use of strlen() &strrev(). (S-23) 6 Marks
Ans :
strlen( ) -
o Returns the length of a string.
o Synatx - strlen(String)
o Example - <?php echo strlen("Welcome to PHP"); ?
strrev():
o Reverses a string
o Synatx - strrev(String)
o Example- <?php echo strrev("Information Technology"); ?>
Syntax :
<?php $variable_name['key_name'] = value; $variable_name = array('keyname' => value); ?>
<?php
$capital = array("Mumbai" => "Maharashtra","Goa" => "Panaji", "Bihar" => "Patna");
print_r($capital);
echo"<br>";
echo "Mumbai is a capital of " .$capital ["Mumbai"];
?>
By default, array starts with index 0. What if you wanted to start with index 1 instead? You could use the
PHP =>operator like this:
$course = array ( 1 => "Computer Engg.", 2 => "Information Tech.", 3 => "Electronics and Telecomm.");
The => operator create key/value pairs in arrays-the item on the left of the operator => is the key and the item on the right is the value.
Multidimesional arrays -
These are arrays that contain other nested arrays.
An array which contains single or multiple arrays within it and can be accessed via multiple indices.
We can create one dimensional and two-dimensional array using multidimensional arrays.
The advantage of multidimensional arrays is that they allow us to group related data together.
Syntax:
array ( array (elements...), array (elements...),...)
<?php
// Defining a multidimensional array
$person = array(array("name" => "Yogita K", "mob" => "5689741523","email" => "[email protected]", ), array( ‘name" => "Manisha P.", "mob" =>
"2584369721", "email" => "[email protected]", ),
array( "name" => "Vijay Patil", "mob" => "9875147536", "email" => "[email protected]", ) );
// Accessing elements
Examination Paper Analysis and Solution
echo "manisha P's email-id is: " . $person[1]["email"], "<br>";
echo "Vijay Patil's mobile no: " . $person[2]["mob"];
?>
<?php
$mobile = array
(
array("LG",20,18), array("sony",30,13), array("Redme",10,2), array("Samsung",40,15) );
echo $mobile[0][0].": In stock: ".$mobile[0][1].", sold: ".$mobile[0][2].".<br>";
echo $mobile[1][0].": In stock: ".$mobile[1][1].", sold: ".$mobile[1][2].".<br>";
echo $mobile[2][0].": In stock: ".$mobile[2][1].", sold: ".$mobile[2][2].".<br>";
echo $mobile[3][0].": In stock: ".$mobile[3][1].", sold: ".$mobile[3][2].".<br>";
?>
It joins an array of elements into strings. It splits the array based on the separator.
It uses the delimiter for string concatenation. It uses the delimiter for splitting the string.
The output example is ‘“ Car”,” Truck”,” Bus”’. The output example is ‘Array ( [0] => Car [1] =>
Truck [2] => Bus )
1 Q.13 State user defined function and explain with example. (S-23) 4 Marks
Ans : PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and
does some processing and returns a value.
Examination Paper Analysis and Solution
They are built-in functions, but PHP gives you option to create your own functions as well. A function will be executed by a call to the function. You
may call a function from anywhere within a page.
function functionName()
{
code to be executed;
}
Example -
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "Welcome to PHP world!";
}
/* Calling a PHP Function */
writeMessage();
?>
<?php
function addfunc($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addfunc(50, 20);
?>
<?php
// PHP program to count number
// of words in a string
// Function to count the words
function get_num_of_words($string)
{
$string = preg_replace('/\s+/', ' ', trim($string));
$words = explode(" ", $string);
return count($words);
}
$str = " Geeks for Geeks ";
// Function call
$len = get_num_of_words($str);
// Printing the result
echo $len;
Examination Paper Analysis and Solution
?>
Q.2. Define Introspection and explain it with suitable example. (S-22, W-22, S-23,S-24) 4 Marks
Ans. Introspection:
Introspection in PHP offers the useful ability to examine an object's characteristics, such as its name, parent class (if any) properties, classes, interfaces, and
methods.
In-built functions in PHP Introspection:
Function Description
class_exists() Checks whether a class has been defined.
et_class() Returns the class name of an object.
get parent_class() Returns the class name of a Return object's parent class.
is_subclass_of() Checks whether an object has a given parent class.
get_declared_classes() Returns a list of all declared classes.
get_class_methods() Returns the names of the class methods.
get_class_vars() Returns the default properties of a class
interface_exists() Checks whether the interface is defined.
method_exists() Checks whether an object defines a method.
Example:
<?php
class Rectangle
{
var $dim1 = 2;
Examination Paper Analysis and Solution
var $dim2 = 10;
function Rectangle($dim1,$dim2)
{
$this->dim1 = $dim1;
$this->dim2 = $dim2;
}
function area()
{
return $this->dim1*$this->dim2;
}
function display()
{
// any code to display info
}
}
$S = new Rectangle(4,2);
//get the class varibale i.e properties
$class_properties = get_class_vars("Rectangle");
//get object properties
$object_properties = get_object_vars($S);
//get class methods
$class_methods = get_class_methods("Rectangle");
OUTPUT:
9.426
48
Examination Paper Analysis and Solution
In the above example, area () method is created dynamically and executed with the help of magic method __ call() and its behavior changes according to the
passed number of parameters as object.
Q.4.Write PHP program for cloning of an object. (S-22, W-22, S-23) 4 Marks
Ans-
<?php
class student{
public $name;
public $course;
public function __construct($n){
$this->name= $n;
}
public function setCourse(course $c){
$this->course =$c;
}
}
class course{
public $cname;
public function __construct($cn){
$this->cname = $cn;
}
}
$student1 = new student('sneha');
$course1 = new course ('php');
$student1->setCourse($course1);
$student2 = clone $student1;
$student2->name = "Sheetal";
$student2->course->cname ="python";
echo "<pre>";
print_r($student1);
echo "<pre>";
echo "<pre>";
print_r($student2);
Examination Paper Analysis and Solution
echo "<pre>";
?>
OUTPUT:
Q.6. Create a class as “Percentage” with two properties length & width. Calculate area of rectangle for two objects. (S-22) 4 Marks
Ans-
<?php
class Rectangle
{
// Declare properties
public $length ;
public $width ;
// define parameterised constructor
function __construct($l,$w){
$this->length = $l;
$this->width =$w;
}
// Method to get the area
public function getArea()
{
return ($this->length * $this->width);
}
}
Examination Paper Analysis and Solution
// Create multiple objects from the Rectangle class
$rect1 = new Rectangle(2,5);
$rect2 = new Rectangle(3,8);
// Call the methods of both the objects
echo "Area of Rectangle_1 :" . $rect1->getArea() . "<br>";
echo "Area of Rectangle_2:" .$rect2->getArea(). "<br>";
?>
OUTPUT:
Area of Rectangle_1 :10
Area of Rectangle_2:24
Q.7 (i) What is inheritance ? (ii) Write update operation on table data. (S-22,S-24) 6 Marks
Ans:
(I) Inheritance:
It is the process of inheriting (sharing) properties and methods of base class in its child class. Inheritance provides reusability of code in a program. PHP uses
extends keyword to establish relationship between two classes.
Syntax:
class derived_class_name extends base_class_name
{
// body of derived Class
}
derived_class_name is the name of new class which is also known as child class and base_class_name is the name of existing class which is also known as
parent class.
A derived class can access properties of base class and also can have its own properties. Properties defined as public in base class can be accessed inside as well
as outside of the class but properties defined as protected in base class can be accessed only inside its derived class. Private members of class cannot be
inherited.
Types of Inheritance are:
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Examination Paper Analysis and Solution
Example:
<?php
class college
{
public $name="ABC College";
protected $code=7;
}
class student extends college
{
public $sname;
public function setName($n){
$this->sname=$n;
}
public function display()
{
echo "College name=" .$this->name;
echo "<br>College code=" .$this->code;
echo "<br>Student name=" .$this->sname;
}
}
$s1=new student();
$s1->setName(“Sneha”);
$s1->display();
?>
OUTPUT:
College name=Vidyalankar Polytechnic
College code=568
Student name=Sneha
Q.9. Write syntax to create class and object in PHP. (W-22) 4 Marks
Ans.
Examination Paper Analysis and Solution
Syntax to create class:
class ClassName{
// data member1;
---------------
// data memberN;
//member function1 ();
----------------
//member functionN ()
}
Syntax to create object:
$objName= new ClassName;
OR
$objName= new ClassName(arg list);
Ans.
Inheritance is a mechanism of extending an existing class to define new derived class.
Where a newly created or derived class has all functionalities of existing class along with its own properties and methods.
The parent class is also called a base class or super class. And the child class is also known as a derived class or a subclass.
Inheritance allows a class to reuse the code from another class without duplicating it.
Reusing existing codes serves various advantages. It saves time, cost, effort, and increases a program’s reliability.
To define a class inherits from another class, use the extends keyword.
Types of Inheritance: Single Inheritance Multilevel Inheritance Multiple Inheritance Hierarchical Inheritance
Example:
<?php
class User
{
public $name;
public $gender;
function __construct($n,$g)
Examination Paper Analysis and Solution
{
$this->name= $n;
$this->gender= $g;
}
}
class Employee extends User
{
public $id;
public $salary;
public $designation;
function __construct($n,$g,$i,$s,$dg)
{
$this->name= $n;
$this->gender= $g;
$this->id= $i;
$this->salary= $s;
$this->designation= $dg;
}
function getEmployeeDetails()
{
Echo "Name: $this->name<br>Gender:
$this->gender<br>Employee Id:
$this->id<br>Salary:$this->salary<br>
designation=$this->designation";
}
}
$e1 = new Employee("Sneha","F",114,34555,"Manager");
$e1->getEmployeeDetails();
?>
Q.11 State the use of serialization. (W-22, S-23) 3 Marks, (S-24) 2 Marks
Ans.
Serializing an object means converting it to a byte stream representation that can be stored in a file.
Serialize() :
The serialize() converts a storable representation of a value.
Examination Paper Analysis and Solution
The serialize() function accepts a single parameter which is the data we want to serialize and returns a serialized string.
A serialize data means a sequence of bits so that it can be stored in a file, a memory buffer or transmitted across a network connection link.
It is useful for storing or passing PHP values around without losing their type and structure.
Syntax : serialize(value1);
Example:
<?php
$s_data= serialize (array ('Welcome', 'to', 'PHP'));
Q.12. State the query to insert data in the database. (W-22) 3 Marks
Ans.
<?php
require_once ‘login.php’;
$conn= newmysqli ($hostname,$username,$password, $dbname);
$querry = INSERT INTO studentinfo (rollno,name,percentage) VALUES(114,“Sneha Patange”, 95.6)”;
$result= $conn->query($query);
if (!$result)
die ("Database access failed: ". $conn->error);
else
echo "record inserted successfully";
?> Output: record inserted successfully
Q.13. Describe inheritance, overloading, overriding and cloning object. (S-23) 4 Marks
Examination Paper Analysis and Solution
Ans.
Inheritance allows classes to inherit properties and methods from a parent class, overloading provides dynamic property and method handling, overriding
enables customization of inherited methods, and cloning creates copies of objects.
1. Inheritance: Inheritance is a fundamental concept in object-oriented programming that allows classes to inherit properties and methods from another class.
In PHP, we can define a new class by extending an existing class using the extends keyword. The new class is called the child or derived class, and the existing
class is called the parent or base class. The child class inherits all the public and protected properties and methods of the parent class. It can also add its own
properties and methods or override the parent class's methods.
2. Overloading: In PHP, overloading refers to the ability to dynamically create properties and methods in a class at runtime.
There are two types of overloading:
a. Property Overloading: PHP provides the __set() and __get() magic methods to handle property overloading. When a property is accessed or modified that
doesn't exist or is inaccessible within the class, these methods are called, allowing us to define custom logic for handling the property.
b. Method Overloading: PHP doesn't support method overloading in the traditional sense (having multiple methods with the same name but different
parameters). However,we can use the __call() magic method to handle method overloading. It gets called when a non-existent or inaccessible method is
invoked, giving the flexibility to handle the method dynamically.
3. Overriding: Overriding occurs when a child class implements a method already defined in the parent class. The method signature (name and parameters) in
the child class must match that of the parent class. By overriding a method, we can customize the behaviors of the method in the child class while retaining the
same method name. To override a method in PHP, simply declare the method in the child class with the same name as the parent class's method.
4. Cloning Objects: Cloning an object in PHP allows us to create a duplicate of an existing object. The clone is a separate instance of the class, but its
properties will initially have the same values as the original object. In PHP, we can clone an object using the clone keyword followed by the object you want to
clone. The cloning process involves calling the __clone() magic method if it's defined in the class. This method allows us to customize the cloning process by
modifying the properties of the cloned object if necessary.
Q.14 Explain the concept of constructor and destructor in detail. (S-23) 6 Marks
Demonstrate __--construct() and __destruct() in PHP (S-24,W-24) 4 Marks
Ans.
Constructor:
A constructor is a special built-in method.
Constructor is special method of class used to initialize an object automatically when it is created.
Constructor do not return any value.
Constructor method takes arhument
To define constructor, 'construct' method is used with two underscores (__).
Syntax:
function __construct([argument1, argument2, ..., argumentN]) {
Examination Paper Analysis and Solution
/* Class initialization code */
}
Destructor:
A destructor function in class is used to destroy an object created by an constructor.
A destructor function is commonly called in two ways: When a script ends or manually delete an object with the unset() function.The 'destruct' method starts
with two underscores (__).
Syntax :
function __destruct() {
/* Class initialization code */
}
Example:
<?php
class student{
public $name;
function __construct()
{
echo "Constructor is executed for " .$this->name;
}
function __destruct()
{
echo "Destructor is executing for " .$this->name;
}
}
$s1=new student("Sneha");
?>
OUTOUT:
Constructor is executed for Sneha
Destructor is executing for Sneha
Examination Paper Analysis and Solution
Explain interface with example W-24
In PHP, interfaces are used to define a contract for classes. An interface specifies a set of methods that a class must implement, but it does not provide any implementation
for those methods. This allows you to define a common set of methods that multiple classes can implement, ensuring consistency across different implementations.
```php
interface InterfaceName {
public function method1();
public function method2($param);
// More methods...
}
```
A class can implement an interface using the `implements` keyword. The class must provide concrete implementations for all the methods defined in the interface.
```php
class ClassName implements InterfaceName {
public function method1() {
// Implementation of method1
}
### Example
Let's create an interface `Shape` with a method `calculateArea()`. Then, we'll create two classes `Circle` and `Rectangle` that implement this interface.
```php
<?php
?>
```
Output
Examination Paper Analysis and Solution
```
Area of Circle: 78.539816339745
Area of Rectangle: 24
```
Q.3 Write difference between get( ) & post( ) method of form (Any four points). (S-22) 4 Marks
Examination Paper Analysis and Solution
Ans:
Q.4 Define session & cookie. Explain use of session start. (S-22) 4 Marks
Ans :
Examination Paper Analysis and Solution
Cookie: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. In short, cookie can be created, sent and received at server end.
Session: Session data is stored on the server side and each Session is assigned with a unique Session ID (SID) for that session data.As session data is stored on
the server there is no need to send any data along with the URL for each request to server.
Q.5 Create customer form like customer name, address, mobile no, date of birth using different form of input elements & display user inserted values
in new PHP form. (S-22) 4 Marks
Ans:
<head>
<title>Registration form</title>
<link rel="stylesheet" href="styel.css" type="text/css">
</head>
<body>
<div class="main">
<div class="register">
<h2>Register Here</h2>
<form id="register" action="registrationform.php" method="post">
<label>First name:</label>
<br>
<input type="text" id="fname" name="fname" placeholder="Enter your first name">
<br>
<br>
<label>Last name:</label>
<br>
<input type="text" id="lname" name="lname" placeholder="Enter your last name">
<br>
<br>
<label>First name:</label>
<br>
<input type="text" id="fname" name="fname" placeholder="Enter your first name">
<br>
<br>
<label>Last name:</label>
<br>
<input type="text" id="lname" name="lname" placeholder="Enter your last name">
<br>
<br>
<label for="email">Enter your email:</label>
<br>
<input type="email" id="email" name="email" placeholder="Enter valid email">
<br>
<br>
<label>Date of Birth:</label>
<br>
<input type="date" id="dob" name="dob" placeholder="Enter your Birthday">
<br>
<br>
<label>Enter mobile number:</label><br><br>
<input type="tel" id="mobno" name="mobno" placeholder="Enter your mobile number" pattern="[7-9]{1}[0-9]{9}" required>
<br>
<input type="submit" id="submit" name="submit" value="Submit">
Examination Paper Analysis and Solution
</form>
</div><!-----end of register--->
</div><!-----end of main---->
</body>
</html>
Q.10 Describe : (i) Start session (ii) Get session variable. (W-22) 4 Marks
Ans :
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 1-
Bool session_start( void)
Example 1.session_start();
PHP $_SESSION is an associative array that contains all session
variables. It is used to set and get session variable values.
Example: Store information
2. $_SESSION["CLASS"] = "TYIF STUDENTS“
Example: Program to set the session variable (demo_session1.php)
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["CLASS"] = "TYIF STUDDENTS";
echo "Session information are set successfully.<br/>";
?>
</body>
</html>
ii)Get Session variables-
We create another page called "demo_session2.php".
Examination Paper Analysis and Solution
we will access the session information we set on the first page ("demo_session1.php").
notice that session variables are not passed individually to each new
page, instead they are retrieved from the session we open at the
beginning of each page (session_start()).
Also notice that all session variable values are stored in the global
$_SESSION variable:
Example:- program to get the session variable
values(demo_session2.php)
<?php
session_start();
?>
<html>
<body>
<?php
echo "CLASS is: ".$_SESSION["CLASS"];
?>
</body> </html>
Q.11 State any four form controls to get user’s input in PHP. (W-22) 4 Marks
Ans :following are from controls to take input from user -
1. Textbox control:It is used to enter data. It is a single line input on a
web page.
Tag :<input type=“text”>
2. Password control:It is used to enter data that appears in the form of
special characters on a web page inside box. Password box looks
like a text box on a wab page.
Tag:<input type=“password”>
3. Textarea : It is used to display a textbox that allow user to enter
multiple lines of text.
Tag :<textarea> … </textarea>
4. Checkbox:It is used to display multiple options from which user
can select one or more options.
Examination Paper Analysis and Solution
Tag: <input type=“checkbox”>
5. Radio / option button :These are used to display multiple options
from which user can select only one option.
Tag :<input type=“radio”>
6. Select element (list) / Combo box / list box:
<select> … </select> : This tag is used to create a drop-down list
box or scrolling list box from which user can select one or more
Options.
<option> … </option> tag is used to insert item in a list.
Q.12 Write steps to create webpage using GUI components. (W-22) 4 Marks
Ans : Following are the GUI components to design web page:
Button - has a textual label and is designed to invoke an action
when pushed.
Checkbox - has textual label that can be toggled on and off.
Option - is a component that provides a pop-up menu of choices.
Label - is a component that displays a single line of read-only,
non-selectable text.
Scrollbar - is a slider to denote a position or a value.
TextField - is a component that implements a single line of text.
TextArea - is a component that implements multiple lines of text.
To design web pages in PHP:
Step 1) start with <html>
Step 2) If user required to add CSS in <head> section.
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
Step 3) In <body> section design form with all mentioned
components.
Step 4) using <?php
Write script for validation for all required input field.
Save the file with php extension to htdocs (C:/Program
Examination Paper Analysis and Solution
Files/XAMPP/htdocs)
Note: You can also create any folders inside ‘htdocs’ folder and
save our codes over there.
Step 5) Using XAMPP server, start the service ‘Apache’.
Step 6)Now to run your code, open localhost/abc.php on any web
browser then it gets executed.
Q.13 Write a PHP program to set and modify cookies. (W-22) 6 Marks
Ans - PHP program to set cookies
<html>
<body>
<?php
$cookie_name = "username";
$cookie_value = "abc";
setcookie($cookie_name, $cookie_value, time() +
(86400 * 30), "/"); // 86400 = 1 day
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie name '" . $cookie_name . "' is not
set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Output:
Cookie 'username' is set!
Value is: abc
PHP program to modify cookies
<?php
setcookie("user", "xyz");
?>
<html>
Examination Paper Analysis and Solution
<body>
<?php
if(!isset($_COOKIE["user"]))
{
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " .
$_COOKIE["user"];
}
?>
</body>
</html>
Output:
Cookie Value: xyz
1. name
2. value
3. expire
4. path
5. Domain
6. Secure
- POST method- It Handles request in servlet which is sent by the client. If a client is entering registration data in an html form, the data can be sent using
post method.
Parameter Descriptions
s
to Required. Specifies the receiver or receivers email ids.
Required. Specifies the subject of the email.
subject
This parameter cannot contain any newline characters.
Required. Defines the message to be sent. Each line should be separated with a (\
message n).
Lines should not exceed 70 characters.
headers Optional. Specifies additional headers, like From, Cc, and Bcc.
Examination Paper Analysis and Solution
parameters Optional. Additional parameter to the send mail can be mentioned in this section.
PHP Mail
<html>
<head>
<title>Email using PHP</title>
</head>
<body>
<?php
$to = "[email protected]";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$header = "From:[email protected] \r\n";
$header .= "Cc:[email protected] \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retvalue = mail ($to,$subject,$message,$header);
if( $retvalue == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>
</body>
</html>
- We always start with a browser making a request for a web page. This request is going to hit the web server. The web server will then analyze it and
determine what to do with it.
- If the web server determines that the request is for a PHP file (often index.php), it will pass that file to the PHP interpreter. The PHP interpreter will read
the PHP file, parse it (and other included files) and then execute it. Once the PHP interpreter finishes executing the PHP file, it will return an output. The web
server will take that output and send it back as a response to the browser.
Examination Paper Analysis and Solution
Q.21 Design form controls –text box, text area, radio button, check box, list and buttons
(S-23) 6 Marks
Ans :
Form Controls :
1. Textbox : A text box is used to enter data. It is a single line input on a web
page.
Tag :<input type=“text”> : It is used to display a text box on a web page.
Attributes of <input> tag used with text box:
name=“ text” : Specify name of text box for unique identification.
maxlength=number : Specify maximum number of characters that can be
accepted in a textbox.
size=number : Specify the width of text box in number of characters.
value=“text” : Specify default text value that appears in the text box when
loaded on a web page.
Example:<input type=“text” name=“n1” maxlength=20 size=15
value=“Enter your name” >
2. Textarea : It is used to display a textbox that allow user to enter multiple
lines of text. Scrollbar is used to move up and down as well as left and right if
the contents are more than size of box.
Tag :<textarea> … </textarea> : It is used to display a multiline text box on
Examination Paper Analysis and Solution
a web page.
Attributes:
name=“ text” : Specify name of the element for unique identification.
cols=number : Specify width of the text area.
rows=number : Specify height of the text area.
readonly : Specify a text area as read only element.
Example:<textarea name=“t1” cols=10 rows=10>Enter your
suggestions</textarea>
3. Radio / option button : Radio buttons are used to display multiple options
from which user can select only one option. When a radio button is selected
by user, a dot symbol appears inside button. Multiple option buttons are
group together to allow user to select only one option from the group. A
group can be created by giving same name to all option buttons in that group.
Tag :<input type=“radio”> : It is used to display a radio button on a web
page.
Attributes of <input> tag used with radio button:
name=“ text” : Specify name of radio button for unique identification.
value=“text” : Specify value to be returned to the destination if that radio
button is selected.
checked: Specify default selection
Example:<input type=“radio” name=“r1” value=“male”>male
<input type=“radio” name=“r1” value=“female” checked>female
name
value
expire
path
domain
Parameters Descriptions
to Required. Specifies the receiver or receivers email ids.
Required. Specifies the subject of the email.
subject
This parameter cannot contain any newline characters.
Required. Defines the message to be sent. Each line should be separated with a (\
message n).
Lines should not exceed 70 characters.
headers Optional. Specifies additional headers, like From, Cc, and Bcc.
parameters Optional. Additional parameter to the send mail can be mentioned in this section.
PHP Mail
<html>
<head>
<title>Email using PHP</title>
</head>
<body>
<?php
$to = "[email protected]";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
Examination Paper Analysis and Solution
$header = "From:[email protected] \r\n";
$header .= "Cc:[email protected] \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retvalue = mail ($to,$subject,$message,$header);
if( $retvalue == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>
</body>
</html>
Cookie Session
Cookies are stored in browser as text file format. Sessions are stored in server side.
The cookie is a client-side resource. The session is a server-side resource.
It is stored limit amount of data. It is stored unlimited amount of data
It is only allowing 4kb[4096bytes]. It is holding the multiple variable in sessions.
It is not holding the multiple variable in cookies. It is holding the multiple variable in sessions.
We can accessing the cookies values in easily. So it is We cannot accessing the session values in easily. So
less secure. it is more secure.
Remember info until deleted by user or expiry. Remembers info until web site time-out.
Setting the cookie time to expire the cookie. using session_destory(), we will destroyed the
sessions.
Examination Paper Analysis and Solution
The setcookie() function must appear BEFORE the The session_start() function must be the very first
<html> tag. thing in your document. Before any HTML tags.
Usually contains an id string. Usually contains more complex information.
Specific identifier links to server. Specific identifier links to user.
Q.25 Design web page using following form controls: (i) Radio Button (ii) Check Box (S-23) 4 Marks
Ans:
radiobtndemo.html
<html>
<head>
<title>Radio Button Demo</title>
</head>
<body>
<form method="get" action="phpradiobtndemo.php">
<label>Select your Gender:</label><br/>
<input type="radio" name="gender" value="male" checked> Male<br/>
<input type="radio" name="gender" value="female"> Female<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
phpradiobtndemo.php
<?php
if(isset($_GET["gender"])){
echo "<p>Gender : " . $_GET["gender"] . "</p>";
}
?>
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM staff WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
Q.3. Inserting and retrieving the query result operations. (S – 22) 4 Marks
Ans:
<?php
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
Examination Paper Analysis and Solution
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM staff";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
}
?>
<?php
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO staff (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Examination Paper Analysis and Solution
}
?>
Q.4 How do you connect MySQL database with PHP. (S – 22) 6 Marks
Ans:
Connecting MySQL Database Server from PHP
- The Process : The process of using MySQL with PHP is as follows :
1. Connect to MySQL and select the database to use.
2. Build a query string.
3. Perform the query.
4. Retrieve the results and output them to a web page.
5. Repeat steps 2 to 4 until all desired data has been retrieved.
6. Disconnect from MySQL.
A database consists of one or more tables.You will need special CREATE privileges to create or to delete a MySQL database.
<?php
Examination Paper Analysis and Solution
if(isset($_POST)) {
$servername = "localhost";
$username = "root";
$password = "";
//$dbname = "clg";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE DATABASE clg";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
}
?>
Q.8 Explain queries to update and delete data in the database. (W -22) 4 Marks
Ans:
<?php
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create connection
$conn = new mysqli($servername, $username, $password);
Examination Paper Analysis and Solution
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Q.10. State the query to insert data in the database. (W -22) 3 Marks
Ans:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO staff (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
Q.11. Write syntax of constructing PHP webpage with MySqL. (S -23) 2 Marks
Ans- Using MySQLi object-oriented procedure:
Syntax:
<?php
$servername = "localhost";
$username = "username";
Examination Paper Analysis and Solution
$password = "password";
// Creating connection
$conn = new mysqli($servername, $username, $password);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
OR
Using MySQLi procedural procedure :
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Note: Any one relevant syntax shall be considered
$conn->close();
}
?>
Q.13. Write a program to connect PHP with MySQL. (S -23) (W -23) 4 Marks
Ans:
In this, and in the following chapters we demonstrate three ways of working with PHP and MySQL:
MySQLi (object-oriented)
MySQLi (procedural)
PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
(i) POD::_construct()
Ans:
Creates a PDO instance to represent a connection to the requested database.
Description
public PDO::__construct(
string $dsn,
string $username = null,
string $password = null,
array $options = null
)
dsn-
The Data Source Name, or DSN, contains the information required to connect to the database.
Username-
The user name for the DSN string. This parameter is optional for some PDO drivers.
Password-
The password for the DSN string. This parameter is optional for some PDO drivers.
Examination Paper Analysis and Solution
Options-
A key=>value array of driver-specific connection options.
(ii) mysqli_connect()
Ans:
Open a new connection to the MySQL server:
Syntax: mysqli_connect(host, username, password, dbname, port, socket)
Parameter Values-
Q.19 Write PHP program to demonstrate database operations using PHP and MySQL. (S-24 6 Marks )
CREATE –
A database consists of one or more tables.You will need special CREATE privileges to create or to delete a MySQL database.
A database is a collection of data. MySQL allows us to store and retrieve the data from the database in a efficient way.
<?php
if(isset($_POST)) {
$servername = "localhost";
$username = "root";
$password = "";
//$dbname = "clg";
Examination Paper Analysis and Solution
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE DATABASE clg";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
}
?>
INSERT –
<?php
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM staff";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
Examination Paper Analysis and Solution
} else {
echo "0 results";
}
$conn->close();
}
?>
DELETE-
Record scan be deleted from a table using the SQL DELETE statement.
DELETE statement is typically used in conjugation with the WHERE clause to delete only those records that matches specific criteria or condition.
SQL query is formed using the DELETE statement and WHERE clause, after that will be executed by passing this query to the PHP query() function to
delete the tables records.
For example a student record with a roll no. ‘CO103’ will be deleted by using DELETE statement and WHERE clause.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM staff WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
INSERT-
After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
The SQL query must be quoted in PHP
Examination Paper Analysis and Solution
String values inside the SQL query must be quoted
Numeric values must not be quoted
The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
<?php
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO staff (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
UPDATE-
Update Data In a MySQL Table Using MySQLi and PDO
The UPDATE statement is used to update existing records in a table:
UPDATE table_name
SET column1=value, column2=value2,B
WHERE some_column=some_value
<?php
Examination Paper Analysis and Solution
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE staff SET lastname='technology' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
}
else
{
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
?>
Q.20. State the query to insert data in the database. (W-22) 3 Marks
Ans.
<?php
require_once ‘login.php’;
$conn= newmysqli ($hostname,$username,$password, $dbname);
$querry = INSERT INTO studentinfo (rollno,name,percentage) VALUES(114,“Sneha Patange”, 95.6)”;
$result= $conn->query($query);
if (!$result)
die ("Database access failed: ". $conn->error);
else
echo "record inserted successfully";
?> Output: record inserted successfully
Examination Paper Analysis and Solution
Q.21. Create a html form ‘result.html’ to accept rollno of student using submit button. Write ‘result.php’ code to check the result of student ‘pass’ or ‘fail’.
Create a table result_table in MySQL database ‘my-db’ with two columns rollno and status also write php code to delete a record result_table.
<!DOCTYPE html>
<html>
<head>
<title>Student Result</title>
</head>
<body>
<h2>Enter Roll Number</h2>
<form action="result.php" method="post">
<label for="rollno">Roll Number:</label>
<input type="text" id="rollno" name="rollno" required>
<br><br>
<button type="submit">Check Result</button>
</form>
<br>
<a href="delete.php">Delete a Record</a>
</body>
</html>
2. result.php (PHP Code)
Code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$rollno = $_POST["rollno"];
// Create connection
Examination Paper Analysis and Solution
$conn = new mysqli($host, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$status = $row["status"];
echo "<h2>Result for Roll Number: " . $rollno . "</h2>";
echo "<p>Status: " . $status . "</p>";
} else {
echo "<h2>Result for Roll Number: " . $rollno . "</h2>";
echo "<p>No result found for this roll number.</p>";
}
$stmt->close();
$conn->close();
}
?>
3. delete.php (PHP Code for Deleting Record)
Code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$rollno = $_POST["rollno_delete"];
Examination Paper Analysis and Solution
// Create connection
$conn = new mysqli($host, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($stmt->affected_rows > 0) {
echo "Record deleted successfully!";
} else {
echo "No record found for deletion.";
}
$stmt->close();
$conn->close();
}
?>
<!DOCTYPE html>
<html>
Examination Paper Analysis and Solution
<head>
<title>Delete Result</title>
</head>
<body>
<h2>Delete Result</h2>
<form action="delete.php" method="post">
<label for="rollno_delete">Roll Number to Delete:</label>
<input type="text" id="rollno_delete" name="rollno_delete" required>
<br><br>
<button type="submit">Delete</button>
</form>
<br>
<a href="result.html">Go Back</a>
</body>
</html>