0% found this document useful (0 votes)
74 views96 pages

PHP w24 Merged

The document outlines the model answer scheme for the Winter 2024 examination in Web Based Application Development with PHP, detailing important instructions for examiners on assessing candidates' answers. It includes a series of questions and model answers related to PHP concepts such as advantages of PHP, inheritance, string functions, data types, and programming constructs. The document emphasizes the importance of understanding and conceptual matching over exact wording in candidates' responses.

Uploaded by

Shruti Shevade
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)
74 views96 pages

PHP w24 Merged

The document outlines the model answer scheme for the Winter 2024 examination in Web Based Application Development with PHP, detailing important instructions for examiners on assessing candidates' answers. It includes a series of questions and model answers related to PHP concepts such as advantages of PHP, inheritance, string functions, data types, and programming constructs. The document emphasizes the importance of understanding and conceptual matching over exact wording in candidates' responses.

Uploaded by

Shruti Shevade
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/ 96

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
WINTER – 2024 EXAMINATION
Model Answer – Only for the Use of RAC Assessors

Subject Name: Web Based Application development with PHP (WBP) Subject Code: 22619
Important Instructions to examiners:
222261
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
9
XXXXX
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model
answer.

Q. Sub Answer Marking Scheme


No. Q.
N.

1 Attempt any FIVE of the following: 10 M

a) List advantages of PHP. 2M

Ans 1)Open Source Any 4 advantages, 1 for


½M
2)Platform independent

3)simple and Easy

4)Database support

5)Security

6)Scripting Language

7)Vast Community

b) Define inheritance in PHP. 2M

Ans Inheritance is a mechanism of extending an existing class by inheriting a class. Correct definition 2 M

We create a new sub class with all functionality of that existing class, and we

Page No: 1 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
can add new members to the new sub class.

When we inherit one class from another we say that inherited class is a
subclass and the class who has inherits is called parent class.

In order to declare that one class inherits the code from another class, we use
the extends keyword.

c) List any four string functions with use. 2M

Ans str_word_count( ): Count the number of words in a string List 1 M,

strlen(): Returns the length of a string Use 1 M,

strrev(): Reverses a string 1/2 M for one function

strops(): Returns the position of the first occurrence of a string inside another
string (case-sensitive)

str_replace(): Replaces some characters in a string (case-sensitive)

ucwords(): Convert the first character of each word to uppercase

strtoupper(): Converts a string to uppercase letters

strtolower(): Converts a string to lowercase letters

str_repeat(): Repeating a string with a specific number of times.

strcmp(): 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.

Substr(): substr() function used to display or extract a string from a particular


position.

Str_split(): To convert a string to an array

Trim(): Removes white spaces and predefined characters from a both the sides
of a string.

Rtrim(): Removes the white spaces from end of the string

Ltrim():Removes the white spaces from left side of the string

d) State different data types in PHP. 2M

Ans i) Integer: This data type holds only numeric values. Integers hold only whole Any two data types, 1 M
numbers including positive and negative numbers, i.e., numbers without for each
fractional part or decimal point. The range of integer values are -
Page No: 2 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
2,147,483,648 to +2,147,483,647. Integers can be defined indecimal(base 10),
hexadecimal(base 16), octal(base 8) or binary(base 2) notation.The default
base is decimal (base 10).

(ii) Float: Floating point numbers represents numeric values with decimal
points (real numbers) or a number in exponential form. The range of floating
point values are 1.7E-308 to 1.7E+308. Example: 3.14, 0.25, -5.5, 2E-4, 1.2e2

(iii) String: A string is a sequence of characters. A string are declares using


single quotes or double quotes. Example: “Hello PHP”, ‘Hello PHP’

(iv) Boolean: The Boolean data types represents two values, true(1) or
false(0). Example: $a=True

v)Array: An array stores multiple values in one single variable and each value
is identify by position ( zero is the first 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......)

(vi) Object :

Objects are defined as instances of user defined classes that can hold both
values and functions. First we declare class of object using keyword class. A
class is a structure that contain properties (variables) and methods (functions).

(vii) Resource: The special resource type is not an actual data type. It is the
storing of a reference to functions and resources external to PHP. Consider a
function which connect to the database, a function to send a query to the
database, a function to close the connection of database. Resource variables
hold special handles to opened files, database connections, streams etc.

(viii) Null: Null is a special data type which can have only one value NULL
i.e. a variable that has no value assigned to it. If a variable is created without a
value, it is automatically assigned a value of NULL.

Syntax : $var_name= NULL

e) Explain array-flip( ) and explode( ) function ·with syntax. 2M

Ans array-flip(): array-flip(): 1M and


explode(): 1M
The array_flip() function flips/exchanges all keys with their associated values
in an array.

This built-in function of PHP array_flip() is used to exchange elements within

Page No: 3 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
an array, i.e., exchange all keys with their associated values in an array and
vice-versa.

Syntax: array_flip(array);

explode():

- The explode() function breaks a string into an array.

- The explode() is a built in function in PHP used to split a string in different


strings.

- The explode() function splits a string based on a string delimeter, i.e. it splits
the string wherever the delimeter character occurs. This function returns an
array containing the strings formed by splitting the original string.

Syntax:

array explode(separator, OriginalString, NoOfElements);

f) Define class with syntax and example. 2M

Ans - A class is a unit of code that describes the characteristics and behaviors of Define:1 M, Syntax: ½ M
something, or of a group of things. and any correct Example:
½M
- Class is a collection of objects. Object has properties and behavior.

- Class is a user-defined data type, which includes local functions as well as


local data. You can think of a class as a template for making many instances of
the same kind (or class) of object.

Syntax :

<? Php

classname_of_class

{ // code goes here...

} ?>

Example:

<?php

class Car

Page No: 4 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
{

// Nothing to see here; move along

$Maruti = new Car();

$Honda = new Car();

print_r( $Maruti ); // Displays “Car Object ( )”

print_r( $Honda ); // Displays “Car Object ( )”

?>

g) State advantages of PHP-MySQL. 2M

Ans 1. The most important advantage of PHP is that it’s open-source and free Any two advantages: 1
from cost. It can be downloaded anywhere and is readily available to M, ½ M for each
use for events or web applications.
2. It is platform-independent. PHP-based applications can run on any OS
like UNIX, Linux, Windows, etc.
3. Applications can easily be loaded which are based on PHP and
connected to the database. It’s mainly used due to its faster rate of
loading over slow internet speed than other programming language.
4. It has less learning curve because it is simple and straightforward to
use. Someone familiar with C programming can easily work on PHP.
5. It is more stable for a few years with the assistance of providing
continuous support to various versions.
6. It helps in reusing an equivalent code and not got have to write lengthy
code and sophisticated structure for events of web applications.
7. It helps in managing code easily.
8. It has powerful library support to use various function modules for data
representation.
9. PHP’s built-in database connection modules help in connecting
databases easily reducing trouble and time for the development of web
applications and content-based sites.
10. The popularity of PHP gave rise to various communities of developers,
a fraction of which may be potential candidates for hire.
11. Flexibility makes PHP ready to effectively combine with many other
programming languages in order that the software package could use

Page No: 5 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
foremost effective technology for every particular feature.

2. Attempt any THREE of the following: 12 M

a) Explain use of for and for each with example. 4M

Ans for Statement : for statement: 2 M, for


each statement : 2M
The for statement is used when you know how many times you want to
execute a statement or a block of statements. That is, the number of iterations
is known beforehand. These type of loops are also known as entry-controlled
loops. There are three main parameters to the code, namely the initialization,
the test condition and the counter.

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.

1. Initialization Expression: In this expression we have to initialize the loop


counter to some value. for example: $i=1;

2. 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:
$i<=10;

3.Update Expression: After executing loop body this expression


increments/decrements the loop variable by some value. for example : $i+= 2;

Syntax :

for (initialization expression; test condition; update expression)

// code to be executed

Example:

<?php

//for loop to print even numbers and sum of them

$sum=0;

Page No: 6 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
for($i=0; $i<=10;$i+=2)

echo "$i<br/>";

$sum+=$i;

echo "Sum=$sum";

?>

for-each statement:

foreach loop is used for array and objects. For every counter of loop, an array
element is assigned and the next counter is shifted to the next element.

Syntax:

foreach (array_element as value)

//code to be executed

Example:

<?php

$arr = array (10, 20, 30, 40, 50);

foreach ($arr as $i)

echo "$i<br/>";

?>

b) Demonstrate use of_construct() and_destruct() with example. 4M

Ans __construct(): __construct():2 M,


__destruct(): 2 M
To create a constructor, simply add a method with the special name _
Page No: 7 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
_construct() to your class. (That ’ s two underscores, followed by the word “
construct, ” followed by parentheses.) PHP looks for this special method name
when the object is created; if it finds it, it calls the method.

Example :

class MyClass

function __construct()

echo “Welcome to PHP constructor. <br / > ”;

$obj = new MyClass; // Displays “Welcome to PHP constructor.”

__ destruct(): A destructor is called when the object is destroyed.

- You have to manually dispose of objects you created, but in PHP, it's
handled by the Garbage Collector, which keeps an eye on your objects and
automatically destroys them when they are no longer needed.

- Destructors are useful for tidying up an object before it’s removed from
memory.

- Destructors don’t have any types or return value. It is just called before de-
allocating memory for an object or during the finish of execution of PHP
scripts or as soon as the execution control leaves the block.

- For example, if an object has a few files open or contains data that should be
written to a database, it’s a good idea to close the files or write the data before
the object disappears.

- You can create destructor methods in the same way as constructors, except
that you use __destruct() function

Example:

<?php

class MyDestClass

Page No: 8 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
{

function __construct()

print "In constructor<br>";

function __destruct()

print "Destroying " . __CLASS__ . "<br>";

$obj = new MyDestClass();//object is not created

?>

c) Write PHP program 4M

i) To find largest of two number

ii) for connecting to MySQL server.

Ans <?php Any Correct logic


Program for i) 2 M ii) 2
function findLargest($num1, $num2) { M
if ($num1 > $num2) {
return $num1;
} elseif ($num2 > $num1) {
return $num2;
} else {
return "Both numbers are equal";
}
}

$num1 = 10;
$num2 = 20;

echo "The largest number between $num1 and $num2 is: " .
findLargest($num1, $num2);

Page No: 9 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
?>

ii) <?php

// MySQL server credentials

$servername = "localhost"; // Change this if your MySQL server is on a


different host

$username = "root"; // MySQL username (default: root)

$password = ""; // MySQL password (default: empty string for local


MySQL setup)

$dbname = "your_database"; // Name of the database you want to connect to


(change as necessary)

// Create connection using MySQLi

$conn = new mysqli($servername, $username, $password, $dbname);

// Check the connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

echo "Connected successfully to the MySQL server";

// Close the connection

$conn->close();

?>

d) Write a PHP program to count total number of rows in the 4M


database table.

Ans <?php Any correct logic


program 4 M
// MySQL server credentials

$servername = "localhost"; // Change this if your MySQL server is on a


different host

$username = "root"; // MySQL username (default: root)

Page No: 10 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
$password = ""; // MySQL password (default: empty string for local
MySQL setup)

$dbname = "your_database"; // Name of the database you want to connect to

// Create connection using MySQLi

$conn = new mysqli($servername, $username, $password, $dbname);

// Check the connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Define the table name

$tableName = "your_table_name"; // Replace this with your actual table name

// SQL query to count total number of rows in the table

$sql = "SELECT COUNT(*) AS total_rows FROM $tableName";

// Execute the query

$result = $conn->query($sql);

// Check if the query was successful

if ($result->num_rows > 0) {

// Fetch the result as an associative array

$row = $result->fetch_assoc();

// Display the total number of rows

echo "Total number of rows in the '$tableName' table: " .


$row['total_rows'];

} else {

echo "Error: Could not retrieve row count.";

// Close the connection

$conn->close();

Page No: 11 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
?>

3. Attempt any THREE of the following: 12 M

a) Define cookie. Explain how to create and delete cookies. 4M

Ans − PHP cookie is a small piece of information which is stored at client Definition of cookie-1M
browser. It is used to recognize the user.
Creation of cookie with
− Cookie is created at server side and saved to client browser. Each time syntax and example-
when client sends request to the server, cookie is embedded with request. 1.5M
Such way, cookie can be received at the server side. In short, cookie can be
created, sent and received at server end.
− A cookie is a small file with the maximum size of 4KB that the web server
Deletion of cookie with
stores on the client computer.
syntax and example-
− A cookie can only be read from the domain that it has been issued from. 1.5M
Cookies are usually set in an HTTP header but JavaScript can also set a
cookie directly on a browser.

There are three steps involved in identifying returning users :


1. Server script sends a set of cookies to the browser. For example : name,
age or identification number etc.
2. Browser stores this information on local machine for future use.
3. 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.
− PHP provides a inbuilt function setcookie(), that can send appropriate
HTTP header to create the cookie on the browser.
− While creating the cookie, we have to pass require arguments with it.
− Only name argument is must but it is better to pass value, expires and path
to avoid any ambiguity.
Syntax : setcookie(name, value, expire, path, domain, secure, HttpOnly);
setcookie(“username”, “abc”, time() + 60 * 60 * 24 * 365, “/”, “.abc.com”,
false, true);
− The setcookie() function defines a cookie to be sent along with the rest of
the HTTP headers.
− cookieexample.php
<html>
<body>

Page No: 12 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<?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>
Delete Cookies
− Cookie can be deleted from user browser simply by setting expires
argument to any past date it will automatically delete the cookie from user
browser.
− Deleted cookie can be checked by calling the same cookie with its name
to check if it exists or not.
− There is no special dedicated function provided in PHP to delete a cookie.
All we have to do is to update the expire-time value of the cookie by
setting it to a past time using the setcookie() function. A very simple way
of doing this is to deduct a few seconds from the current time.
− Syntax:
− setcookie(name, time() - 3600);
<html>
<body>
<?php
setcookie("user"," ",time()-3600);
echo "Cookie 'user' is deleted.";
?>
</body>
</html>

b) Explain bitwise operators in PHP. 4M

Page No: 13 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans Bitwise operators allow evaluation and manipulation of specific bits within an List of Bitwise operators
integer. with use-2M

Bitwise Operators And example of any


bitwise operator-2M
Example Name Result

$a & $b AND Bits that are set in both $a and $b are


set.

$a | $b OR (inclusive OR) Bits that are set in either $a or $b are


set.

$a ^ $b Xor (exclusive or) Bits that are set in $a or $b but not both
are set.

~ $a Not Bits that are set in $a are not set, and


vice versa.

$a << $b Shift left Shift the bits of $a $b steps to the left


(each step means "multiply by two")

$a >> $b Shift right Shift the bits of $a $b steps to the right


(each step means "divide by two")

1. & (Bitwise AND) : This binary operator works on two operands. 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.
2. | (Bitwise OR) :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.
3. ^ (Bitwise XOR ) : 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.
4. ~ (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.
5. << (Bitwise Left Shift) :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.
6. >> (Bitwise Right Shift) :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.
Example:
// Bitwise AND
$First = 5;
Page No: 14 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
$second = 3;
$answer = $First & $second;
print_r("Bitwise & of 5 and 3 is $answer");
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;
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");
// Bitwise Left shift
$second = 1;
$answer = $First << $second;
print_r("5 << 1 will be $answer");
print_r("\n");
// Bitwise Right shift
$answer = $First >> $second;
print_r("5 >> 1 will be $answer");
print_r("\n");
?>
Output:
Bitwise & of 5 and 3 is 1
Bitwise | of 5 and 3 is 7
Page No: 15 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Bitwise ^ of 5 and 3 is 6
Bitwise ~ of 5 is -6
5 << 1 will be 10
5 >> 1 will be 2

c) Write a PHP program to draw a rectangle filled with red colour. 4M

Ans <?php Relevant program-4M


// Create an image
$img = imagecreatetruecolor(500, 300);
$color = imagecolorallocate($img, 255, 0, 0);
imagefilledrectangle($img, 30, 30, 470, 270, $color);
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>

d) Explain Following Methods 4M

i) MySQL_select_db()
ii) ImageCopyReszied()

Ans i) MySQL_select _db() MySQL_select_db()-use


and syntax:1M
The mysqli_select_db() function is used to change the default database for the
connection. Example-1M

Syntax: $mysqli -> select_db(name)


Example: ImageCopyResized()-use
and syntax:1M
$con=mysqli_connect("localhost","my_user","my_password","my_db"); Example-1M

if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}

// Return name of current default database


if ($result = mysqli_query($con, "SELECT DATABASE()")) {
$row = mysqli_fetch_row($result);
echo "Default database is " . $row[0];
mysqli_free_result($result);
Page No: 16 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}

// Change db to "test" db
mysqli_select_db($con, "test");

// Return name of current default database


if ($result = mysqli_query($con, "SELECT DATABASE()")) {
$row = mysqli_fetch_row($result);
echo "Default database is " . $row[0];
mysqli_free_result($result);
}

// Close connection
mysqli_close($con);
?>
ii) imageCopyReszied()
The imagecopyresized() function is an inbuilt function in PHP which is used
to copy a rectangular portion of one image to another image. dst_image is the
destination image, src_image is the source image identifier.
Syntax:
bool imagecopyresized( resource $dst_image,
resource $src_image, int $dst_x, int $dst_y,
int $src_x, int $src_y, int $dst_w,
int $dst_h, int $src_w, int $src_h )
Parameters:This function accepts ten parameters as mentioned above and
described below:
• $dst_image: It specifies the destination image resource.
• $src_image: It specifies the source image resource.
• $dst_x: It specifies the x-coordinate of destination point.
• $dst_y: It specifies the y-coordinate of destination point.
• $src_x: It specifies the x-coordinate of source point.
• $src_y: It specifies the y-coordinate of source point.
• $dst_w: It specifies the destination width.
• $dst_h: It specifies the destination height.
• $src_w: It specifies the source width.

Page No: 17 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
• $src_h: It specifies the source height.

Return Value: This function returns TRUE on success or FALSE on failure.

<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new sizes


list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight,
$width, $height);

// Output
imagejpeg($thumb);
?>

4. Attempt any THREE of the following: 12 M

a) Demonstrate the concept of overloading with example. 4M

Ans It is a type of overloading for creating dynamic methods that are not declared concept of overloading-
within the class scope. PHP method overloading also triggers magic methods 2M and example- 2M
dedicated to the appropriate purpose. Unlike property overloading, PHP
method overloading allows function call on both object and static context. The
related magic functions are,
• __call() – triggered while invoking overloaded methods in the object
context.
• __callStatic() – triggered while invoking overloaded methods in static
context.
<?php

Page No: 18 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
class GFG {
public function __call($name, $arguments) {

echo "Calling object method '$name' "


. implode(', ', $arguments). "\n";
}

public static function __callStatic($name, $arguments)


{
echo "Calling static method '$name' "
.implode(', ', $arguments). "\n";
}
}
// Create new object
$obj = new GFG;
$obj->runTest('in object context');
GFG::runTest('in static context');
?>
<?php

class GFG {
function multiply($var1){
return $var1;
}

function multiply($var1,$var2){
return $var1 * $var1 ;
}
}
$ob = new GFG();
$ob->multiply(3,6);
?>
b) Develop PHP program to create database and insert records in 4M
database.

Ans create database -2M


Create table in php:
and insert records in
Step 1) create a database through script database-2M

<?php
if(isset($_POST)) {
$servername = "localhost";
$username = "root";
Page No: 19 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
$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();
}
?>
) Create a table “staff”
<?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 = "CREATE TABLE staff (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50)
)";
if ($conn->query($sql) === TRUE) {
echo "Table staff created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
}
?>

insert values into table “staff”

<?php
{
$servername = "localhost";
Page No: 20 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
$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();
}
?>
c) Explain how to implement multidimensional array in PHP. 4M

Ans These are arrays that contain other nested arrays. Concept and syntax of
An array which contains single or multiple arrays within it and can be multidimensional array-
accessed via multiple indices. 2M
We can create one dimensional and two dimensional array using
multidimensional arrays. The advantage of multidimensional arrays is that Implementation/example-
they allow us to group related data together. 2M
Syntax for creating multidimensional array in php
array (
array (elements...),
array (elements...),
...
)
Example :
<?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",
Page No: 21 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
"email" => "[email protected]",
)
);
// Accessing elements
echo "manisha P's email-id is: " . $person[1]["email"], "<br>";
echo "Vijay Patil's mobile no: " . $person[2]["mob"];
?>
Output :
manisha P's email-id is: [email protected]
Vijay Patil's mobile no: 9875147536
d) Explain print and echo statement in PHP. 4M

Ans PHP echo statement: Use of print and echo


statement-2M
• In PHP, there are two ways to get output or print output: echo and Example of each-2M
print.
• They are both used to output data to the screen.
The PHP echo Statement:

• The echo statement can be used with or without parentheses: echo or


echo().
• The echo statement can display anything that can be displayed to the
browser, such as string, numbers, variables values, the results of
expressions etc.
Example :
<?php
// Displaying strings
echo "Hello, Welcome to PHP Programming";
echo "<br/>";
//Displaying Strings as Multiple arguments
echo "Hello", " Welcome", " PHP";
echo "<br/>";
//Displaying variables
$s="Hello, PHP";
$x=10;
$y=20;
echo "$s <br/>";
echo $x."+".$y."=";

Page No: 22 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
echo $x + $y;
?>
Output :
Hello, Welcome to PHP Programming
Hello Welcome PHP
Hello, PHP
10+20=30
The PHP print Statement :
The PHP print statement is similar to the echo statement and can be used
alternative to echo at many times. It is
also language construct and so we may not use parenthesis : print or print().
print statement can also be used to print
strings and variables.
Web Based Application Development using PHP (MSBTE) 1-6 Expressions
and Control Statements in PHP
Example :
<?php
// Displaying strings
print "Hello, Welcome to PHP Programming";
print "<br/>";
//Displaying variables
$s="Hello, PHP";
$x=10;
$y=20;
print "$s <br/>";
print $x."+".$y."=";
print $x + $y;
?>
Output :

Page No: 23 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Hello, Welcome to PHP Programming
Hello, PHP
10+20=30

e) Create a form given below also write PHP code to find given number is 4M
odd or even.

Ans <?php Relevant code-4M


extract($_REQUEST);
if(isset($check))
{
if($number%2==0)
{
echo "$number is Even Number";
}
else
{
echo "$number is Odd Number";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form method="post">
<table>
<tr>
<td>Enter Your Number</td>
<td><input type="text" name="number" required/></td>
</tr>
<td colspan="2" align="center">
<input type="submit" value="Even or Odd"
name="check"/>
Page No: 24 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
</tr>
</form>
</body>
</html>
</html>

OR

<html>
<body>

<h2>PHP script to find given number is ODD or EVEN </h2>

<form action="" method="post">


<input type="text" name="num" />
<input type="submit" />
</form>

<?php

if($_POST)
{
$num = $_POST['num'];

if(!is_numeric($num))
{
echo "String not allowed.
Input should number";
return;
}
if($num % 2==0)
{
echo "Number is an even number";
}
else
{
echo "Number is an odd number ";
}
}

?>

</body>
</html>

5. Attempt any TWO of the following: 12 M

Page No: 25 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
a) State applications of serialization. Illustrate its use with example. 6M

Ans Serialization in PHP refers to the process of converting a data structure (like Any three correct
an object, array, or variable) into a string format that can be stored, applications-3 M
transmitted, or manipulated. Deserialization is the reverse process, converting
the serialized string back into its original data structure. Any Correct example in
PHP – 3 M
Applications of serialization in PHP:
1. Serialization allows developers to store complex data structures, like
objects and arrays, in databases or files.
2. When data needs to be sent over a network (e.g., via APIs or sockets),
it is serialized to ensure compatibility with the transmission format.
3. PHP sessions often use serialization to store session data as strings.
The session data is serialized before being written to a storage medium
like files or databases.
4. Serialization is used in caching systems like Redis or Memcached to
store PHP objects or arrays for faster retrieval.
5. Serialization can preserve the state of objects by storing their
properties and values. This is useful when saving the state of an object
between requests or sessions.
6. Developers use serialization to log complex data structures in a
readable and storable format for debugging purposes.
7. Serialization is often used in queue systems to serialize tasks or
messages before pushing them into the queue.
8. When applications written in PHP need to communicate with systems
in other programming languages, serialization ensures that the data can
be properly transmitted and interpreted.
Example:
<?php
class User
{
public $name;
public $email;

public function __construct($name, $email)


{

Page No: 26 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
$this->name = $name;
$this->email = $email;
}
}
$user = new User('Rina', '[email protected]');
$serializedUser = serialize($user);
echo $serializedUser;
?>
OUTPUT:
O:4:"User":2:{s:4:"name";s:4:"Rina";s:5:"email";s:15:"[email protected]";}

b) Write a PHP program 6M

(i) for sending mail

(ii) for validating name field.

Ans (i) PHP program to sending mail for sending mail-3M


<html> for validating name field-
<head> 3M
<title>Email using PHP</title>
</head>
<body>
<?php
$to_email = "[email protected]";
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: [email protected]';
$retvalue= mail($to_email,$subject,$message,$headers);
echo $retvalue;
if( $retvalue == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>
</body>
</html>

(ii) For Validating name field


<!DOCTYPE html>
<html>
<head>

Page No: 27 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<style>
.error {color: #FF0001;}
</style>
</head>
<body>
<?php
// define variables to empty values
$nameErr = " ";
//Input fields validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validating Name field
if (emptyempty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = input_data($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only alphabets and white space are allowed";
}
}
?>
<h2>Input Form</h2>
<span class = "error">* required field </span>
<br><br>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr; ?> </span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
</form>
<?php
if(isset($_POST['submit'])) {
if($nameErr == "") {
echo "<h3 color = #FF0001> <b>You have sucessfully
registered.</b> </h3>";
echo "<h2>Your Input:</h2>";
echo "Name: " .$name;
echo "<br>";
} else {
echo "<h3> <b>Please input name in correct fomat.</b> </h3>";
}
}
?>
</body>
</html>
c) Display the given text "this is server side coding using PHP" in 6M

Page No: 28 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
PDF format using PHP.

Ans <?php Correct code-6M


require('fpdf.php');
$pdf=new FPDF();
$pdf->SetFillColor(100,256,256);
$pdf->AddPage();
$pdf->SetFont('Courier','B',16);
$pdf->SetTextColor(0,100,200);
$pdf->Cell(100,10,this is server side coding using PHP',0,1,'C',true);
$pdf->Output();
?>

6. Attempt any TWO of the following: 12 M

a) Create a html form "result.html" to accept Rollno of student using 6M


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 from result_table.

Ans File result.html Correct


Result.html-2 M
<html> Result.php -2 M
Create table /
<head>
Insert two records/
<meta charset="UTF-8"> Delete the record- 2 M

<meta name="viewport" content="width=device-width, initial-scale=1.0">


<title>Check Result</title>
</head>
<body>
<h1>Check Student Result</h1>
<form action="result.php" method="POST">
<label for="rollno">Enter Roll Number:</label>

Page No: 29 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<input type="number" name="rollno" id="rollno" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
PHP Code: result.php
<?php
// Database credentials
$servername = "localhost";
$username = "root";
$password = ""; // Adjust if needed
$dbname = "My_db";
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get the roll number from the form
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$rollno = intval($_POST['rollno']);
// Query to check the result
$sql = "SELECT Status FROM result_table WHERE Rollno = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $rollno);
$stmt->execute();
$result = $stmt->get_result();
// Check if the Rollno exists

Page No: 30 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo "Roll Number: " . $rollno . "<br>";
echo "Result: " . $row['Status'];
} else {
echo "No result found for Roll Number: " . $rollno;
}
$stmt->close();
}
$conn->close();
?>
Create table result_table
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = " My_db";
// Creating connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br>";
// sql to create table
$sql = "CREATE TABLE result_table ( Rollno INT PRIMARY KEY, Status
VARCHAR(10) NOT NULL)";
if ($conn->query($sql) === TRUE) {
echo "Table created successfully";

Page No: 31 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
File - Insert.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "My_db";
// Creating connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br>";
$sql = "INSERT INTO result_table (Rollno, Status)
VALUES (1, 'Pass');";
$sql .= " INSERT INTO result_table (Rollno, Status)
VALUES (2, 'Fail')";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

Page No: 32 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
?>
Code to delete the record:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "My_db";
// Creating connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br>";
$sql = "DELETE from result_table WHERE Rollno=2";
if ($conn->query($sql) === TRUE) {
echo "record deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

b) Explain the following function types with example: 6M

(i) Anonymous function

(ii) Variable function

Ans (i) Anonymous function or lambda function: Anonymous function


with example –
Anonymous function is a function without any user defined name. Such a 3 M,
function is also Variable function with
example –
3M
Page No: 33 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
called closure or lambda function.
Syntax:
$var=function ($arg1, $arg2) { return $val; };
• There is no function name between the function keyword and the opening
parenthesis.
• There is a semicolon after the function definition because anonymous
function
definitions are expressions.
• Function is assigned to a variable, and called later using the variable’s name.
• When passed to another function that can then call it later, it is known as a
callback.
• Closure is also an anonymous function that can access variables outside its
scope
with the help of use keyword
Example-1 :
<?php
$var = function ($name)
{
echo "Hello $name";
};
$var("Sneha");
?>
OUTPUT:
Hello Sneha
Example 2 - Anonymous function as a Closure:
<?php
$maxmarks=300;
$percent=function ($marks) use ($maxmarks)
{

Page No: 34 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
return $marks*100/$maxmarks;
};
echo "marks=285 percentage=". $percent(285);
?>
(ii) Variable function:
If name of a variable has parentheses (with or without parameters in it) in front
of it, PHP
parser tries to find a function whose name corresponds to value of the variable
and executes
it. Such a function is called variable function.
Syntax:
<?php
function valueofvariable (arg list)
{
//block of code;
}
$variable_name= valueofvariable;
$variable_name (arg list);
?>
Example:
<?php
function add($x, $y){
echo $x+$y;
}
function sub($x, $y){
echo $x-$y;
}
$var=readline("enter name of function: ");
$var(10,20);

Page No: 35 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
?>
OUTPUT
add
30

c) Explain: 6M

(i) _clone()

(ii) class_exists()

(iii) get_parent_class()

Ans (i) _clone() Correct explanation


Of _clone()-2 M
By combining the clone keyword and __clone() magic method, we can class_exists()-2 M
perform a deep copy of an object. Deep copy creates a copy of an object and get_parent_class()-2 M
recursively creates a copy of the objects referenced by the properties of the
object.
The following example illustrates how to use the __clone() magic method to
carry a deep copy of the Person object:
Example:
<?php
class Address
{
public $street;
public $city;
}
class Person
{
public $name;
public $address;
public function __construct($name)
{
$this->name = $name;
$this->address = new Address();

Page No: 36 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
public function __clone()
{
$this->address = clone $this->address;
}
}
$bob = new Person('Bob');
$bob->address->street = 'North 1st Street';
$bob->address->city = 'San Jose';
$alex = clone $bob;
$alex->name = 'Alex';
$alex->address->street = '1 Apple Park Way';
$alex->address->city = 'Cupertino';
var_dump($bob);
var_dump($alex);
?>
In above example, using __clone() method in the Person class we can create a
separate
copy of the Address object for both the references which is known as deep
copy of
object,.

(ii) class_exists()
The class_exists() function checks whether a class with a given name has been
defined or not. It is useful for verifying the availability of a class before
instantiating it or calling its methods.
Syntax
bool class_exists(string $className, bool $autoload = true)
Example:
<?php

Page No: 37 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
class MyClass {}
if (class_exists('MyClass')) {
echo "Class 'MyClass' exists.";
} else {
echo "Class 'MyClass' does not exist.";
}
?>
Output:
Class 'MyClass' exists.

(iii) get_parent_class()
The get_parent_class() function retrieves the name of the parent class for a
given class or object. It is used in object-oriented programming to examine
class inheritance.
Syntax
string|false get_parent_class(object|string $objectOrClass = null)
Example:
<?php
class ParentClass {}
class ChildClass extends ParentClass {}
$child = new ChildClass();
echo get_parent_class($child);
?>
Output:
ParentClass

Page No: 38 | 38
lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Important Instructions to examiners:


1) The answers should be examined by key words and not as word-to-word as given
in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner
may try to assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more
Importance (Not applicable for subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components
indicated in the figure. The figures drawn by candidate and model answer may
vary. The examiner may give credit for anyequivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the
assumed constant values may vary and there may be some difference in the
candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner
of relevant answer based on candidate’s understanding.
7) For programming language papers, credit may be given to any other program
based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in
English/Marathi and Bilingual (English + Marathi) medium is introduced at first year
of AICTE diploma Programme from academic year 2021-2022. Hence if the
students in first year (first and second semesters) write answers in Marathi or
bilingual language (English +Marathi), the Examiner shall consider the same and
assess the answer based on matching of concepts with model answer.

Q. Sub Answer Marking


No Q.N. Scheme
1. Attempt any FIVE of the following: 10
a) List any four data types of PHP. 2M
Ans.  boolean Any four
 integer types ½ M
each
 float
 string
 array
 object
 resource
 NULL
b) Define Array. State its example. 2M
Ans. Definition:An array is a special variable, which can hold more than Definition
one value at a time. 1M

Page 1 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Example:
1)Indexed array: Any one
example 1M
$colors = array("Red", "Green", "Blue");

2)Associative array:
$student_one = array("Maths"=>95, "Physics"=>90,
"Chemistry"=>96, "English"=>93,
"Computer"=>98);

3)Multidimensional array
$movies =array(
"comedy" =>array("Pink Panther", "John English", "See no evil hear
no evil"),
"action" =>array("Die Hard", "Expendables","Inception"),
"epic" =>array("The Lord of the rings")
);
c) State the role of constructor. 2M
Ans. The constructor is an essential part of object-oriented programming. Correct
It is a method of a class that is called automatically when an object of answer 2M
that class is declared. The main purpose of this method is to initialize
the object.
d) State the use of cookies. 2M
Ans. Cookie is used to keep track of information such as a username that Correct use
the site can retrieve to personalize the page when the user visits the 2M
website next time.
e) List two database operations. 2M
Ans. 1.mysqli_affected_rows() Any two
operations
2. mysqli_close() 1M each
3. mysqli_connect()
4. mysqli_fetch_array()
5.mysqli_fetch_assoc()
6.mysqli_affected_rows()
7. mysqli_error()
f) Write syntax of for each loop 2M
Ans. foreach ($array as $value) { Correct
code to be executed; syntax 2M
}

Page 2 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

g) State role of GET and POST methods 2M


Ans. i)Get method:
It processes the client request which is sent by the client, using the 1M for each
HTTP get method.Browser uses get method to send request. method

ii)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.
2. Attempt any THREE of the following: 12
a) Explain the use of break and continue statements. 4M
Ans. Break statement:-break keyword is used to terminate and transfer
the control to the next statement when encountered inside a loop or
switch case statement.
Syntax:
if (condition) Use and
{ break; } relevant
Example: example of
each - 2M
<?php

for ($a = 0; $a < 10; $a++)


{
if ($a == 7)
{
break; /* Break the loop when condition is true. */
}
echo "Number: $a <br>";
}
echo " Terminate the loop at $a number";
?>

ii)Continue Statement
It is used to skip the execution of a particular statement inside the
loops.
if (condition)
{ continue; }
Example:
<?php
for ($i = 0; $i< 10; $i++)

Page 3 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

{
if ($i == 5)continue;
{
echo " $i<br>";
}}
echo "end";
?>
b) Explain Indexed array and associative arrays with suitable 4M
examples.
Ans.  In indexed arrays the value is accessed using indexes 0,1,2 etc.
 These types of arrays can be used to store any type of elements,
but an index is always a number. By default, the index starts at Explanation
zero. These arrays can be created in two different ways as shown of each array
in the following with suitable
 Array initialization example -2M
First method
$colors = array("Red", "Green", "Blue");

Second method
$colors[0] = "Red";
$colors[1] = "Green";
$colors[2] = "Blue";

Example:-initialize an array elements and display the same


<?php
$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");
// Accessing the elements directly
echo "Accessing the 1st array elements directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n";
?>

ii)Associative array
Associative arrays are used to store key value pairs.
Associative arrays have strings as keys and behave more liketwo-
column tables. The first column is the key, which is used to access the
value.

Page 4 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Here array() function is used to create associative array.


<?php
/* First method to create an associate array. */
$student_one = array("Maths"=>95, "Physics"=>90,
"Chemistry"=>96, "English"=>93,
"Computer"=>98);
Second method to create an associate array.
$student_two["Maths"] = 95;
$student_two["Physics"] = 90;
$student_two["Chemistry"] = 96;
$student_two["English"] = 93;
$student_two["Computer"] = 98;

Example
<?php
$student_two["Maths"] = 95;
$student_two["Physics"] = 90;
$student_two["Chemistry"] = 96;
$student_two["English"] = 93;
$student_two["Computer"] = 98;
echo "Marks for student one is:\n";
echo "Maths:" . $student_two["Maths"], "\n";
echo "Physics:" . $student_two["Physics"], "\n";
echo "Chemistry:" . $student_two["Chemistry"], "\n";
echo "English:" . $student_two["English"], "\n";
echo "Computer:" . $student_two["Computer"], "\n";
?>
c) Define Introspection. Explain it with suitable example 4M
Ans. Introspection is the ability of a program to examine an object's
characteristics, such as its name, parent class (if any), properties, and Definition
1M
methods. With introspection, we can write code that operates on any
class or object. We don't need to know which methods or properties
are defined when we write code; instead, we can discover that
informationat runtime, which makes it possible for us to write generic
debuggers, serializers, profilers, etc.
Example:-
<?php Any relevant
class parentclass Program /
Example -
{ 3M

Page 5 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

public $roll;
public function par_function()
{}}
class childclass extends parentclass
{public $name;
public function child_fun()
{}}
$obj=new childclass();
//class introspection
print_r("parent class exists:".class_exists('parentclass'));
echo"<br> child class methods: ";
print_r(get_class_methods('childclass'));
echo"<br> child class variables: ";
print_r(get_class_vars('childclass'));
echo"<br> parent class variables: ";
print_r(get_class_vars('parentclass'));
echo"<br> parent class: ";
print_r(get_parent_class('childclass'));
//object introspection;
echo"<br> is object: ";
print_r(is_object($obj));
echo"<br> object of a class: ";
print_r(get_class($obj));
echo"<br> object variables: ";
print_r(get_object_vars($obj));
echo"<br> methods exists: ";
print_r(method_exists($obj,'child_fun'));
?>

d) Describe 4M
i) Start session
ii) Get session variables
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 Description
of Start
new session session 2M
Syntax 1.
boolsession_start( void )

Page 6 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

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". From this page,
we will access the session information we set on the first page Description
("demo_session1.php"). of
Get session
2M
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"];

Page 7 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

?>
</body>
</html>
3. Attempt any THREE of the following: 12
a) Explain two functions to scale the given image. 4M
Ans. imagecopyresized() function : It is an inbuilt function in PHP which
is used to copy a rectangular portion of one image to another image
and resize it. dst_image is the destination image, src_image is the Explanation
source image identifier. of two
functions -
Syntax: 2M each
imagecopyresized(dst_image, src_image, dst_x, dst_y,src_x, src_y,
dst_w,dst_h,src_w, src_h)
dst_image: It specifies the destination image resource.
src_image: It specifies the source image resource.
dst_x: It specifies the x-coordinate of destination point.
dst_y: It specifies the y-coordinate of destination point.
src_x: It specifies the x-coordinate of source point.
src_y: It specifies the y-coordinate of source point.
dst_w: It specifies the destination width.
dst_h: It specifies the destination height.
src_w: It specifies the source width.
src_h: It specifies the source height.
Example:
imagecopyresized($d_image,$s_image,0,0,50,50,200,200,$s_width,
$s_height);

imagecopyresampled() function : It is used to copy a rectangular


portion of one image to another image, smoothly interpolating pixel
values thatresize an image.
Syntax:
imagecopyresampled(dst_image, src_image, dst_x, dst_y,src_x,
src_y, dst_w,dst_h,src_w, src_h)
dst_image: It specifies the destination image resource.
src_image: It specifies the source image resource.
dst_x: It specifies the x-coordinate of destination point.
dst_y: It specifies the y-coordinate of destination point.
ṇsrc_x: It specifies the x-coordinate of source point.
src_y: It specifies the y-coordinate of source point.
dst_w: It specifies the destination width.

Page 8 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

dst_h: It specifies the destination height.


src_w: It specifies the source width.
src_h: It specifies the source height.

Example:
imagecopyresampled($d_image,$s_image,0,0,50,50,200,200,$s_widt
h,$s_height);
b) Write syntax to create class and object in PHP. 4M
Ans. A class is defined by using the class keyword, followed by the name
of the class and a pair of curly braces ({}). All its properties and
Correct
methods go inside the curly brackets. syntax for
Syntax : creating
<?php class-2M,
class classname [extends baseclass][implements
interfacename,[interfacename,…]] Object-2M
{ (Example is
[visibility $property [=value];…] optional)
[functionfunctionname(args) { code }…] // method declaration &
definition
}
?>
In the above syntax, terms in squarebrackets are optional.

Object : An object is an instance of class. The data associated with an


object are called its properties. The functions associated with an
object are called its methods. Object of a class is created by using the
new keyword followed by classname.
Syntax : $object = new Classname( );
Example:
<?php
class student
{
public $name;
public $rollno;

function accept($name,$rollno)
{
$this->name=$name;
$this->rollno=$rollno;

Page 9 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

}
}
?>
$s1=new student( );
c) State any four form controls to get user’s input in PHP. 4M
Ans. 1. Textbox control:It is used to enter data. It is a single line input on a
web page.
Tag :<input type=“text”> Any four
form controls
2. Password control:It is used to enter data that appears in the form of 1M each
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.
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.
d) Write steps to create database using PHP 4M
Ans. Steps using PHP Code:Creating database: With CREATE Correct steps
DATABASE query 4M
Step 1: Set variables with values for servername, username,
password.
Step 2: Set connection object by passing servername, username,
password as parameters.
Step 3: Set query object with the query as "CREATE DATABASE
dept";
Step 4: Execute query with connection object.
Code (Optional)-
<?php

Page 10 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE DATABASE ifdept";
if ($conn->query($sql) === TRUE)
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . $conn->error;
}
$conn->close ();
?>

OR

Steps using phpMyAdmin


Step 1: Click on Start and select XAMPP from the list. Open Xampp
control panel by clicking on the option from the list. The Control
Panel is now visible and can be used to initiate or halt the working of
any module.
Step2: Click on the "Start" button corresponding
to Apache and MySQL modules. Once it starts working, the user can
see the following screen:
Step 3: Now click on the "Admin" button corresponding to
the MySQL module. This automatically redirects the user to a web
browser to the following address - http://localhost/phpmyadmin

Step 4: Screen with multiple tabs such as Database, SQL, User


Accounts, Export, Import, Settings, etc. Will appear. Click on
the "Database" tab. Give an appropriate name for the Database in the
first textbox and click on create option.

Page 11 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Step 5 : In the created Database, click on the 'Structure' tab. Towards


the end of the tables list, the user will see a 'Create Table' option.
Give appropriate "Name" and "Number of Columns" for table and
click on 'Go' button.

Step 6 : Give details of columns based on their type. Enter the names
for each column, select the type, and the maximum length allowed for
the input field. Click on "Save" in the bottom right corner. The table
with the initialized columns will be created.

4. Attempt any THREE of the following: 12


a) Define user defined function with example. 4M
Ans. A function is a named block of code written in a program to perform
some specific tasks. They take information as parameters, execute a
Description
block of statements or perform operations on these parameters and 2M, Example
return the result. A function will be executed by a call to the function. 2M
The function name can be any string that starts with a letter or
underscore followed by zero or more letters, underscores, and digits.

Syntax:
function function_name([parameters if any])
{
Function body / statements to be executed
}

Example:
<?php
function display() // declare and define a function
{
echo "Hello,Welcome to function";
}
display(); // function call
?>

When a function is defined in a script, to execute thefunction,


programmer have to call it with its name and parameters if required.

Page 12 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

b) Write a program for cloning of an object. 4M


Ans. (Any other correct program shall be considered)
Correct
program 4M
<?php
class student
{
function getdata($nm,$rn)
{
$this->name=$nm;
$this->rollno=$rn;
}
function display()
{
echo "<br>name = ".$this->name;
echo "<Br>rollno = ".$this->rollno;
}
}
$s1 = new student();
$s1->getdata("abc",1);
$s1->display();
$s2 = clone $s1;
echo "<br> Cloned object data ";
$s2->display();
?>

c) Write steps to create webpage using GUI components. 4M


Ans. Following are the GUI components to design web page:
 Button - has a textual label and is designed to invoke an action Correct
when pushed. steps-4M
 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>

Page 13 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Step 2) If user required to add CSS in <head> section.


<head> (any other
<style> relevant steps
.error {color: #FF0000;} to design web
page shall be
</style> considered)
</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
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.
d) Explain queries to update and delete data in the database. 4M
Ans. Update data : UPDATE query
Update command is used to change / update new value for field in Explanation
row of table. It updates the value in row that satisfy the criteria given of Update
query 2M
in query.

The UPDATE query syntax:


UPDATE Table_name SET field_name=New_value WHERE
field_name=existing_value
Example :
UPDATE student SET rollno=4 WHERE name='abc'
In the above query, a value from rollno field from student table is
updated with new value as 4 if its name field contains name as ‘abc’.

Delete data: DELETE query Explanation


Delete command is used to delete rows that are no longer required of
from the database tables. It deletes the whole row from the table. Delete query
The DELETE query syntax: 2M
DELETE FROM table_name WHERE some_column =
some_value

Page 14 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

[WHERE condition] is optional. The WHERE clause specifies which


record or records that should be deleted. If the WHERE clause is not
used, all records will be deleted.
Example :-
$sql = "DELETE FROM student WHERE rollno=2";

In the above query, a row from student table is deleted if rollno field
contains 2 in that row.
e) Describe the syntax of if-else control statement with example in 4M
PHP.
Ans. if-else control statement is used to check whether the
Description
condition/expression is true or false. Ifthe expression / condition of if-else
evaluates to true then true block code associated with the if statement control
is executed otherwise if it evaluates to false then false block of code statement
associated with else is executed. 2M,
Syntax:
Syntax1M,
if (expression/condition)
{ Example1M
True code block;
}
else
{
False code block;
}

Example:
<?php
$a=30;
if ($a<20)
echo "variable value a is less than 20";
else
echo "variable value a is greater than 20";
?>
In the above example, variable a holds value as 30. Condition checks
whether the value of a is less than 20. It evaluates to false so the
output displays the text as ‘variable value a is greater than 20’.
5. Attempt any TWO of the following: 12
a) Write a PHP program to display numbers from 1-10 in a 6M
sequence using for loop.

Page 15 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Ans. PHP Code-


<?php For loop
syntax 2M
echo "Output<br>";
for($i=1;$i<=10;$i++) Correct
{ syntax 2M
echo "$i<br/>";
} Correct logic
2M
?>
Output
(Output is
1
optional)
2
3
4
5
6
7
8
9
10
b) Write a program to connect PHP with MYSQL. 6M
Ans. Solution1:
<?php
$servername = "localhost"; Correct
$username = "root"; syntax 2M
$password = "";
// Connection Correct code
$conn = new mysqli($servername,$username, $password); 4M
// For checking if connection issuccessful or not
if ($conn->connect_error)
{
die("Connection failed: ". $conn->connect_error);
}
Writing
echo "Connected successfully"; Output is
?> optional
Output:
Connected successfully
OR

Page 16 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Solution2:
Create login.php
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
?>

Create db2.php file


<?php
require_once 'login.php';
$conn = new mysqli($hostname, $username, $password);
//if ($conn->connect_error) die($conn->connect_error);
if ($conn->connect_error) {
die("Connection failed: "
. $conn->connect_error);
}
echo "Connected successfully";
?>
Output:
Connected successfully

c) Illustrate class inheritance in PHP with example. 6M


Ans.  Inheritance is a mechanism of extending an existing class where
a newly created or derived class have all functionalities of
Definition /
existing class along with its own properties and methods. Explanation
 The parent class is also called a base class or super class. And the and
child class is also known as a derived class or a subclass. Types of
 Inheritance allows a class to reuse the code from another class Inheritance-
2M
without duplicating it.
 Reusing existing codes serves various advantages. It saves time, Any Correct
cost, effort, and increases a program’s reliability. Program /
 To define a class inherits from another class, you use the extends example- 4M
keyword.
 Types of Inheritance:
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance

Page 17 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Example:
(Any type of inheritance example shall be considered)
<?php
class student {
var $var = "This is first var";
protected $fist_name;
protected $last_name;

// simple class method


function returnVar() {
echo $this->fist_name;
}
function set_fist_name($fname,$lname){
$this->fist_name = $fname;
$this->last_name = $lname;
}
}
class result extends student {
public $percentage;

function set_Percentage($p){
$this->percentage = $p;
}
function getVal(){
echo "Name:$this->fist_name $this->last_name";
echo "<br/>";
echo "Result: $this->percentage %";
}
}
$res1 = new result();
$res1->set_fist_name("Rita","Patel");
$res1->set_Percentage(95);
$res1->getVal();
?>
Output:
Name:Rita Patel
Result: 95 %

Page 18 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

6. Attempt any TWO of the following: 12


a) Write a PHP program to set and modify cookies. 6M
Ans. PHP program to set cookies
<html> Correct Code
to set cookie -
<body> 3M
<?php
$cookie_name = "username";
$cookie_value = "abc";
setcookie($cookie_name, $cookie_value, time() +
(86400 * 30), "/"); // 86400 = 1 day
if(!isset($_COOKIE[$cookie_name])) { Correct Code
echo "Cookie name '" . $cookie_name . "' is not to modify
set!"; cookies- 3M
} 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>
<body>
<?php
if(!isset($_COOKIE["user"]))
{
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " .
$_COOKIE["user"];
}

Page 19 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

?>
</body>
</html>

Output:
Cookie Value: xyz
b) Write a PHP program to 6M
i) Calculate length of string Program to
ii) Count number of words in string calculate
length of
Ans.
i) Calculate length of string string 3M

<?php
$str = 'Have a nice day ahead!';
echo "Input String is:".$str;
echo "<br>";
echo "Length of String str:".strlen($str);
// output =12 [including whitespace]
?>

ii) Count number of words in string Program to


count
Solution1- number of
<?php words in
// PHP program to count number of string 3M
// words in a string

$str = " This is a string ";

// Using str_word_count() function to count number of words in a


string
$len = str_word_count($str);

// Printing the result


echo "Number of words in string : $len";
?>
Output:
Number of words in string : 4

OR

Page 20 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Solution 2:
<?php
// PHP program to count number of
// words in a string
$string = " This is a string ";
$str = trim($string);
while (substr_count($str, " ") > 0) {
$str = str_replace(" ", " ", $str);
}
$len = substr_count($str, " ")+1;
// Printing the result
echo "Number of words in string: $len";
?>

Output:
Number of words in string: 4
c) i) State the use of serialization. 6M
ii) State the query to insert data in the database.
Ans. i) Use of serialization. Serialization
Serializing an object means converting it to a bytestream explanation
representation that can be stored in a file. Serialization in PHP is with
mostly automatic, it requires little extra work from you, beyond example- 3M
calling the serialize () and unserialize( ) functions.

Serialize() :
 The serialize() converts a storable representation of a value.
 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 transmittedacross a network
connection link. It is useful for storing or passing PHP values
around without losing their type and structure.

Example:
<?php
$s_data= serialize(array('Welcome', 'to', 'PHP'));
print_r($s_data . "<br>");
$us_data=unserialize($s_data);

Page 21 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


lOMoARcPSD|29458053

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

print_r($us_data);
?>

Output:a:3:{i:0;s:7:"Welcome";i:1;s:2:"to";i:2;s:3:"PHP";} Correct
Array ( [0] => Welcome [1] => to [2] => PHP ) example of
insert query-
3M
ii) Query to insert data in the database
<?php
require_once 'login.php';
$conn = newmysqli($hostname,$username, $password,$dbname);
$query = "INSERT INTO studentinfo(rollno,name,percentage)
VALUES
('CO103','Yogita Khandagale',98.45)";
$result = $conn->query($query);
if (!$result)
die ("Database access failed: " . $conn->error);
else
echo "record inserted successfully";
?>

Output:
record inserted successfully

Page 22 / 22

Downloaded by Shaikh M.Hassaan ([email protected])


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
SUMMER – 2024 EXAMINATION
Model Answer – Only for the Use of RAC Assessors

Subject Name: Web Based Application Development with PHP Subject Code: 22619
Important Instructions to examiners:
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model
answer.

Q. Sub Answer Marking


No. Q. Scheme
N.

1 Attempt any FIVE of the following: 10 M

a) List any four advantages of PHP. 2M

Ans 1. Performance: PHP script is executed much faster than those scripts which are Any 4
written in other languages such as JSP and ASP. PHP uses its own memory, so the correct
server workload and loading time is automatically reduced, which results in faster points-2 M
processing speed and better performance.
2. Open Source: PHP source code and software are freely available on the web. We
can develop all the versions of PHP according to our requirement without paying
any cost. All its components are free to download and use.
3. Embedded: PHP code can be easily embedded within HTML tags and script.
4. Platform Independent: PHP is available for WINDOWS, MAC, and LINUX&
UNIX operating system. A PHP application developed in one OS can be easily
executed in other OS also.
5. Database Support: PHP supports all the leading databases such as MySQL,
SQLite, ODBC, etc.
6. Security: PHP is a secure language to develop the website. It consists of multiple

Page No: 1 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
layers of security to prevent threads and malicious attacks.
7. 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.
8. 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.
9. 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 we can make changes easily whenever we want.
10. Web servers Support: PHP is compatible with almost all local servers used today
like Apache, Netscape, Microsoft IIS, etc.
11. Familiarity with syntax: PHP has easily understandable syntax. Programmers are
comfortable coding with it.
12. 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.

b) State the use of str-word-count along with its syntax. 2M

Ans Use of str_word_count() : Use -1 M


and Correct
The str_word_count() is in-built function of PHP. It is used to return information about Syntax- 1 M
words used in a string or counts the number of words in a string.

Syntax:
str_word_count ( $string , $returnVal, $chars )

Parameters Used:
$string: Input string.
$returnVal: $returnVal parameter. It is an optional parameter and its default value is 0.
$chars: This is an optional parameter which specifies a list of additional characters which
shall be considered as a ‘word’.

c) Define Serialization. 2M

Ans In PHP, serialization is the process of converting a data structure or object into a string Correct
Definition- 2
representation that can be stored or transmitted. This allows you to save the state of an
M
object or data structure to a database, cache, or send it over a network connection, and
then later recreate the object or data structure from the serialized string.

Page No: 2 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
d) Differentiate between Session & Cookies. (Any two points) 2M

Ans Sr. Session Cookies Any 2


No. correct
points – 2 M
1 When it comes to sessions, it When it comes to cookies, they
stores the variable and their are stored as a text file on the
values within a file in a user’s system.
momentary manual on the
server.

2 It ends when the operator The cookie expires relying on the


turns off the system or logs lifetime a user set for it.
off the application.

3 They are server-side files that They are considered client-side


manage user data. files that store user data.

4 It can hold an unlimited It can only hold a specific piece of


amount of data. information.

5 Here, we can hold unlimited Here, the utmost size of the


data; however, there is the cookies is 4 KB.
highest memory limitation,
which a script can utilise a
single time, and it is 128 MB.

6 To begin the session, we are As cookies are stored in the local


required to call the system hence, we don’t require to
session_start() function. call a function to initiate a cookie.

7 Sessions are more secure than Cookies are less secure as


cookies. compared to the sessions.

e) List out the database operations. 2M

Ans 1. Create Any 4


2. Insert correct
3. Update operations-2
4. Delete M
5. Truncate
6. Alter
f) Write a program using Foreach loop. 2M

Ans <?php Correct


//declare array program- 2
$season = array ("Summer", "Winter", "Autumn", "Rainy"); M

//access array elements using foreach loop


foreach ($season as $element) {

Page No: 3 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
echo "$element";
echo "</br>";
}
?>
g) Explain in short how can we destroy cookies. 2M

Ans To delete or destroy the cookie, we can use the setcookie() function with the same cookie Correct
name, an empty value, and a past expiration time (specifically, one hour ago). Setting the explanation-
expiration time to the past causes the cookie to be immediately expired and removed from 2M
the browser.
Example:
<?php
$cookieName = "username";

// Set the cookie expiration time to the past to delete the cookie
setcookie($cookieName, "", time() - 3600);

echo "Cookie named 'username' has been deleted.";


?>

2. Attempt any THREE of the following: 12 M

a) Explain different loops in PHP. 4M

Ans Type of Loops in PHP Types of


Loops-1 M
1. The while Loop
2. The Do …while Loop Any 2
3. The For Loop correct Loop
4. The Foreach Loop with syntax-
2M
The While Loop
Example of
While structure is type of loop statement, where the condition is checked at first, the above loop-1
iteration will not stop even if the value changes while executing Statements. M
Syntax-
while(condition)
{
code to be executed
}
Example:
<?php
$i=0;
while($i<=10)
{ //output value 0 from 10
echo "The Number is ".$i."<br>";

Page No: 4 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$i++;
}
?>

The Do While Loop

Do while statement is same as the while statement, the only difference is that it evaluates
the expression at the end.
Syntax –
do
{
code to be executed
}
while(condition);
Example:
<?php
$i=0;
do
{ //output value 0 from 10
echo "The Number is ".$i."<br>";
$i++;
}
while($i<=10)
?>
The For Loop

The for loop is used when we know in advance how many times the script should run.
Syntax:
for(initialization; condition; increment)
{
code to be executed
}
Example:
<?php
for($i=0;$i<=10;$i++)
{
echo "The Number is ".$i."<br/>";
}
?>
The Foreach Loop

For Each structure is a loop structure used for arrays.


Syntax:
foreach(array as value)
{
code to be executed;
}
foreach(array as key => value)
{
Page No: 5 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
code to be executed;
}
Example:
<?php
$email=array('[email protected]','[email protected]');
foreach($email as $value)
{
echo "Processing ".$value."<br/>";
}
?>
b) Differentiate between implode & explode functions. 4M

Ans Implode function Explode function Any 4


Correct
points- 4 M
The implode function works on an The explode function works on
array. a string.

The explode function returns


The implode function returns string.
array.

The first parameter of the implode The first parameter of the


function is optional. explode function is required.

The explode function is used


The implode function in PHP is used
to "Split a string by a specified
to "join elements of an array with a
string into pieces i.e. it breaks a
string".
string into an array".

Syntax: Syntax:
implode (separator, array) explode (separator,string,limit)
c) Define Introspection and explain it with suitable example. 4M

Ans Definition: Definition-1


M
In PHP, An Introspection is an ability to examine an object's characteristics, such as its
name, parent class (if any) properties, classes, interfaces, and methods. Any 4
correct
In-built functions in PHP Introspection: Introspection
built-in
1. class_exists() Checks whether a class has been defined.
functions – 1
2. get_class() Returns the class name of an object. M

3. get_parent_class() Returns the class name of a Return object's parent class. Any Correct
Example- 2

Page No: 6 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
4. is_subclass_of() Checks whether an object has a given parent class. M
5. get_declared_classes() Returns a list of all declared classes.
6. get_class_methods() Returns the names of the class methods.
7. get_class_vars() Returns the default properties of a class
8. interface_exists() Checks whether the interface is defined.
9. method_exists() Checks whether an object defines a method.

Example:
<?php
class Rectangle
{
var $dim1 = 2;
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");
//get class corresponding to an object
$object_class = get_class($S);
print_r($class_properties);
print_r($object_properties);
print_r($class_methods);
print_r($object_class);
?>
OUTPUT:
Array ( [dim1] => 2 [dim2] => 10 )
Array ( [dim1] => 4 [dim2] => 2 )
Page No: 7 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
Array ( [0] => Rectangle [1] => area [2] => display )
Rectangle
d) Explain mail () function in PHP with example. 4M

Ans PHP mail() function is used to send email in PHP. You can send text message, html Syntax with
message and attachment with message using PHP mail() function. description-2
M
Syntax:
Example-2
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, M
string $additional_parameters ]] )

Description:

$to: specifies receiver or receivers of the mail.

$subject: represents subject of the mail.

$message: represents message of the mail to be sent.

$additional_headers (optional): specifies the additional headers such as From, CC, BCC
etc.

Example:

<html>

<head>

<title>Email Using PHP</title>

</head>

<body>

<?php

$to_email = "[email protected]";

$subject = 'Testing PHP Mail';

$message = 'This mail is sent using the PHP mail function';

$headers = 'From:[email protected]';

$retvalue=mail($to_email,$subject,$message,$headers);

echo $retvalue;

if( $retvalue == true ) {

Page No: 8 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
echo "Message sent successfully...";

}else {

echo "Message could not be sent...";

?>

</body>

</html>

3. Attempt any THREE of the following: 12 M

a) Explain Indexed & Associative arrays with suitable example. 4M

Ans 1. Indexed array - Each type


explanation-
• An array with a numeric index where values are stored linearly. 1M
• Numeric arrays use number as access keys. Example of
each type of
• An access key is a reference to a memory slot in an array variable. array-1 M
• The access key is used whenever we want to read or assign a new value an array
element.

• Syntax - <?php $variable_name[n] = value; -?> OR

<?php -$variable_name = array(n => value, …); -?>

• Example - <?php $course = array(0 => "Computer Engg.",1 => "Information


Tech.",

o 2 => "Electronics and Telecomm."); echo


$course[1]; ?>

2. Associative array -

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

• An array with a string index where instead of linear storage, each value can be
assigned a specific key.

• Associative array differ from numeric array in the sense that associative arrays

Page No: 9 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
use descriptive names for id keys.

• Syntax : <?php $variable_name['key_name'] = value;

$variable_name = array('keyname' => value); ?>

b) Explain Constructor with example. 4M

Ans A constructor is a special built-in method. Explanation


–2M
Constructor is special method of class used to initialize an object automatically when it is
created. Example – 2
M
Constructor do not return any value.
Constructor method takes arguments.
To define constructor, 'construct' method is used with two underscores ( ).
Syntax:
function construct([argument1, argument2, ..., argumentN]) {
/* 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");
?>
c) Define session & cookie. Explain use of session start. 4M

Ans Cookie: Cookie is a small piece of information which is stored at client browser. It is used Definition
to recognize the user. each – 1 M

Page No: 10 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
• Cookie is created at server side and saved to client browser. Each time when client Use – 2 M
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.

Session_start-
• 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
Session variables are set with the PHP global variable: $_SESSION.
Example:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

d) Explain inserting and retrieving the query result operations. 4M

Ans The below given code will demonstrate to insert and retrieve the respective query result Relevant
operations. code – 4 M
<?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);

Page No: 11 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
}
$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();
}
?>

4. Attempt any THREE of the following: 12 M

a) Write a program to create PDF document in PHP. 4M

Ans <?php Relevant


code – 4 M
ob_end_clean();
require('fpdf/fpdf.php');

// Instantiate and use the FPDF class


Page No: 12 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$pdf = new FPDF();

//Add a new page


$pdf->AddPage();

// Set the font for the text


$pdf->SetFont('Arial', 'B', 18);

// Prints a cell with given text


$pdf->Cell(60,20,'Hello Students!');

// return the generated output


$pdf->Output();

?>
b) Write a program to demonstrate concept of inheritance in PHP. 4M

Ans Inheritance: Relevant


code – 4 M
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

Page No: 13 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
Hierarchical Inheritance

Multiple Inheritance

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(“Ramesh”);

$s1->display();

Page No: 14 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________

?>

OUTPUT:

College name=ABC college


College code= 7
Student name=Ramesh
c) Create Employee form like employee_name, Address, Mobile_No, Date of 4M
birth, Post and Salary using different form input element and display user
inserted values in new PHP form.

Ans Html Program Html code –


<!DOCTYPE html> 2M
<html lang="en">
<head> PHP code –
2M
<title>Employee Form</title>
</head>
<body>
<h2>Employee Information</h2>
<form action="process_form.php" method="post">
<label for="employee_name">Employee Name:</label><br>
<input type="text" id="employee_name" name="employee_name"><br><br>

<label for="address">Address:</label><br>
<input type="text" id="address" name="address"><br><br>

<label for="mobile_no">Mobile No:</label><br>


<input type="text" id="mobile_no" name="mobile_no"><br><br>

<label for="dob">Date of Birth:</label><br>


<input type="date" id="dob" name="dob"><br><br>

<label for="post">Post:</label><br>
<input type="text" id="post" name="post"><br><br>

<label for="salary">Salary:</label><br>
<input type="text" id="salary" name="salary"><br><br>

<input type="submit" value="Submit">


</form>
</body>
</html>

Page No: 15 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
PHP Program

<!DOCTYPE html>
<html lang="en">
<head>

<title>Employee Information</title>
</head>
<body>
<h2>Employee Information</h2>
<?php
// Retrieve form data using PHP
$employee_name = $_POST['employee_name'];
$address = $_POST['address'];
$mobile_no = $_POST['mobile_no'];
$dob = $_POST['dob'];
$post = $_POST['post'];
$salary = $_POST['salary'];

// Display the retrieved data


echo "<p><strong>Employee Name:</strong> $employee_name</p>";
echo "<p><strong>Address:</strong> $address</p>";
echo "<p><strong>Mobile No:</strong> $mobile_no</p>";
echo "<p><strong>Date of Birth:</strong> $dob</p>";
echo "<p><strong>Post:</strong> $post</p>";
echo "<p><strong>Salary:</strong> $salary</p>";
?>
</body>
</html>
d) Write PHP program to demonstrate delete operation on table data. 4M

Ans In the below example a student record with a roll no. ‘CO103’ will be deleted by using Relevant
DELETE statement and WHERE clause. code – 4 M

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

Page No: 16 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();

?>
e) Explain web page validation with example. 4M

Ans There are some built-in functions in PHP which will validate the web page. Explanation
• User may by mistakenly submit the data through form with empty fields or in wrong –2M
format.
• PHP script must ensure that required fields are complete and submitted data is in Example – 2
valid format. M
• PHP provides some inbuilt function using these functions that input data can be
validated.
• empty() function will ensure that text field is not blank it is with some data, function
accepts a variable as an argument and returns TRUE when the text field is submitted
with empty string, zero, NULL or FALSE value.
• Is_numeric() function will ensure that data entered in a text field is a numeric value,
the function accepts a variable as an argument and returns TRUE when the text
field is submitted with numeric value.
• preg_match() function is specifically used to performed validation for entering text
in the text field, function accepts a “regular expression” argument and a variable as
an argument which has to be in a specific pattern. Typically it is for validating email,
IP address and pin code in a form.
• For Example a PHP page formvalidation.php is having three text fields name,
mobile number and email from user, on clicking Submit button a data will be
submitted to PHP script validdata.php on the server, which will perform three
different validation on these three text fields, it will check that name should not be
blank, mobile number should be in numeric form and the email is validated with an
email pattern.

<html>
<head>
<title> Validating Form Data</title>
</head>
<body>
<form method="post" action="validdata.php">
Name :<input type="text" name="name" id="name" /><br/>
Mobile Number :<input type="text" name="mobileno" id="mobileno" /><br/>
Email ID :<input type="text" name="email" id="email" /><br/>
<input type="submit" name="submit_btn" value="Submit" />
</form>
</body>
</html>

Page No: 17 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if(empty($_POST['name']))
{
echo "Name can't be blank<br/>";
}
if(!is_numeric($_POST['mobileno']))
{
echo "Enter valid Mobile Number<br/>";
}
$pattern ='/\b[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}\b/';
if(!preg_match($pattern,$_POST['email']))
{
echo "Enter valid Email ID.<br/>";
}
}
?>

5. Attempt any TWO of the following: 12 M

a) Explain decision making statements along with their syntax in PHP. 6M

Ans Program Instructions are executed sequentially. In some cases it is necessary to change Each Syntax
the sequence of executions based on certain conditions. For this purpose decision control Carries – 1
structure is required. M
Decision making statements are
1. if statement
2. if else statement
3. Else if else statement
4. Switch statement
5. Break statement
6. Continue statement
If statement-

The if statement executes some code if one condition is true.

Syntax
if (condition) {
// code to be executed if condition is true;

Page No: 18 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
}
Example-
<?php
$a=10;
if ($a > 0)
{
echo "The number is positive";
}

?>
1. If else statement –

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
echo "Have a nice day!";
?>

2. Nested if else statement-

Nested if statements mean an if block inside another if block. Nested if else


statement used when we have more than two conditions. It is also called if else if
statement

Page No: 19 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
if(condition1)
{

// Code to be executed
if condition1 is true
}

elseif(
condition2)
{
// Code to be executed if the condition1 is false and condition2 is true
}
else
{
// Code to be executed if both condition1 and condition2 are false
}
4. The if...elseif...else statement executes different codes for more than two
conditions.

Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
// code to be executed if first condition is false and this condition is true;
} else {
// code to be executed if all conditions are false;
}
Example
Output "Have a good morning!" if the current time is less than 10, and "Have a
good day!" if the current time is less than 20. Otherwise it will output "Have a

Page No: 20 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
good night!":
<?php
$t = date("H");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";

} else {
echo "Have a good night!";
}
?>
4.swich case –
The PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.

Syntax
switch (expression) {
case label1:
//code block
break;
case label2:
//code block;
break;
case label3:
//code block
break;
default:

Page No: 21 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
//code block
}
This is how it works:

The expression is evaluated once

The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
The break keyword breaks out of the switch block

The default code block is executed if there is no match


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

echo "Your favorite color is green!";


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

4 Break : The keyword break ends execution of the current for, for each, while, do
while or switch structure. When the

keyword break executed inside a loop the control automatically passes to the first
Page No: 22 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
statement outside the loop. A

break is usually associated with the if.

Example :

<?php

for($i=1; $i<=5;$i++)

echo "$i<br/>";

if($i==3)

break;

?>

Output :

2. Continue : It is used to stop processing the current block of code in the loop and
goes to the next iteration. It is used to skip a part of the body of the loop under
certain conditions. It causes the loop to be continued with the next iteration after
skipping any statement in between. The continue statement tells the compiler
”SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH THE
NEXT ITERATION”.

Example :

<?php

for($i=1; $i<=5;$i++)

Page No: 23 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
if($i==3)

continue;

echo "$i<br/>";

?>

Output :

5
b) Write PHP program to demonstrate database operation using PHP and 6M
MySQL.

Ans Note - Assessor may consider any one database operation from this. Any One
Correct
CREATE – Database
Operation
A database consists of one or more tables. You will need special CREATE privileges to Carries 6 M
create or to delete a MySQL database. (Create,
Select,
− A database is a collection of data. MySQL allows us to store and retrieve the data Insert,
from the database in a efficient way. Update,
Delete)

<?php

if(isset($_POST)) {

$servername = "localhost";

$username = "root";

$password = "";

//$dbname = "clg";

Page No: 24 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$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);

Page No: 25 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$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();

?>

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

Page No: 26 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$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

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

Page No: 27 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$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,...
WHERE some_column=some_value

<?php

$servername = "localhost";

$username = "root";

Page No: 28 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$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();
}
?>

c) Explain method overriding with example. 6M

Ans In function overriding, both parent and child classes should have same function name and Explanation-
number of arguments. 2 M,
Script- 4 M
It is used to replace the parent method in child class.

The purpose of overriding is to change the behavior of parent class method.

The two methods with the same name and same parameter is called overriding.

Inherited methods can be overridden by redefining the methods (use the same name) in
the child class.

Example-

<?php

Page No: 29 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
class Shape

public $length;

public $width;

public function construct($length, $width) {

$this->length = $length;

$this->width = $width;

public function intro()

echo "The length is {$this->length} and the width is {$this->width}.";

class square extends Shape

public $height;

public function construct($length, $width, $height)

$this->length = $length;

$this->width = $width;

$this->height = $height;

public function intro()

echo "The length is {$this->length}, the width is {$this->width}, the height is {$this-
>height} ";

Page No: 30 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
}

$s = new square(10,30, 50);

$s->intro();

?>

Output :

The length is 10, the width is 30, the height is 50

6. Attempt any TWO of the following: 12 M

a) Write a PHP program to demonstrate use of cookies. 6M

Ans <html> Correct


<body> logic- 6 M
<?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];
}
if(!isset($_COOKIE["user"]))
{
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
setcookie("user"," ",time()-3600);
echo "Cookie 'user' is deleted.";
?>

Page No: 31 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
</body>
</html>
b) Explain the following string functions with example: 6M

(i) Str-replace

(ii) Vcwords()

(ii) Strlen()

(iv) Strtoupper()

Ans Note: in sub question (ii) instead of Vcwords() read it as ucwords() Each Correct
1. str_replace()-Replaces some characters in a string (case-sensitive) String
Function
Syntax- Str_replace(string tobe replaced, text, string) Carries-
Example- 1.5 M
<?php
echo str_replace("Clock","Click","Click and Clock");
?>
Output:
Click and Click

2. ucwords()-Convert the first character of each word to uppercase.


Syntax- ucwords(String)
Example- <?php
echo ucwords("welcome to php world");
?>
Output:
Welcome To Php World

3.strlen()-Returns the length of a string


Syntax- Strlen(String)
Example- <?php
echo strlen("Welcome to PHP");
?>
Output: 14
4. strtoupper()-Converts a string to uppercase letters
Syntax - strtoupper(String)
Example-
<?php
echo strtoupper("information technology ");

Page No: 32 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________

Output:
INFORMATION TECHNOLOGY

c) Explain interface with example. 6M

Ans An Interface allows the users to create programs, specifying the public methods that a Interface
class must implement, without involving the complexities and details of how the explanation -
particular methods are implemented. 3 M,
example-3 M
− An Interface is defined just like a class but with the class keyword replaced by the
interface keyword and just the function prototypes.
− The interface contains no data variables.
− An interface consists of methods that have no implementations, which means the
interface methods are abstract methods.
− All the methods in interfaces must have public visibility scope.
-Interfaces are different from classes as the class can inherit from one class only whereas
the class can implement one or more interfaces.
− Interface enables you to model multiple inheritance

Syntax-1 :

interface (using class along with interface)

class child_class_name extends parent_class_name

implements interface_name1, ..

Example :

Example :

<?php

// Class A i.e. Parent A

class A

public function disp1()

echo "Parent-A <br>";


}
Page No: 33 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
}

// Interface B i.e Parent B

interface B

public function disp2();

class C extends A implements B

function disp2()

echo " Parent-B <br>";

public function disp3()

echo "\nChild-C";

$obj = new C();

$obj->disp1();

$obj->disp2();

$obj->disp3();

?>

Output :

Parent-A

Parent-B

Child-C

Page No: 34 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
Syntax-2 :

Interface (using multiple interface)

class child_class_name implements interface_name1,

interface_name2, ...

Example :

<?php

// interface A i.e. Parent A

interface A

public function disp1();

// Interface B i.e Parent B

interface B

public function disp2();

class C implements A,B

function disp1()

echo "Parent-A <br>";

function disp2()

echo " Parent-B <br>";

Page No: 35 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
public function disp3()

$obj = new C();

$obj->disp1();

$obj->disp2();

$obj->disp3();

?>

Output :

Parent-A

Parent-B

Child-C

Page No: 36 | 36

You might also like