Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP Merged

Download as pdf or txt
Download as pdf or txt
You are on page 1of 77

lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


lOMoARcPSD|23918329

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 Sam Borse (borsesam20@gmail.com)


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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 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.No Sub Answer Marking
Q.N. Scheme
1. Attempt any FIVE of the following: 10M
a) State the advantages of PHP(any four) 2M
Ans. The advantages of PHP are as follows: State any four
1. Open Source and Free of Cost: advantages
1/2M each
People can download it from an open-source and get it for free.
2. Platform Independence:
PHP-based applications can run on any OS such as UNIX, Windows, Linux,
etc.
3. Database connection:
It has a built-in database connection that helps to connect databases and
reduce the trouble and the time to develop web applications or content-based
sites altogether.
4. Library support:
PHP has strong library support using which one can utilize the various
function modules for data representation.

Page 1 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

5. User-friendly:
It has a less learning curve, and one can learn it quickly.
6. Flexible:
It is highly flexible, and people can readily use it to combine its function
with various other programming languages.
7. PHP uses its own memory space, so the workload of the server and
loading time reduces automatically, which results into the faster processing
speed.
8.PHP has multiple layers of security to prevent threats and malicious
attacks.
b) State the use of strlen() and strrev() 2M
Ans. Strlen(): Use of each
The strlen() function is used to count number of characters in a string. It method- 1M
returns the length of a string.

Strrev():
The strrev() function is used to reverse a string.
c) Define introspection 2M
Ans. Introspection is the ability of a program to examine object characteristics Correct
definition 2M
such as its name, parent class, properties and method.
d) Enlist the attributes of cookies. 2M
Ans. Attributes of Cookies are as follows: List any four
1. name attributes 1/2M
each
2. value
3. expire
4. path
5. domain
6. secure
e) Write syntax of constructing PHP webpage with MySQL 2M
Ans. Using MySQLi object-oriented procedure: Correct syntax
Syntax: 2M
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = new mysqli($servername, $username, $password);
// Checking connection

Page 2 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

OR

Using MySQLi procedural procedure :


Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Note: Any one relevant syntax shall be considered
f) Define GET & POST methods 2M
Ans. GET method:
GET method is a way to pass data entered in a form, to the server or Each definition
1M
destination by adding it into URL.
OR
It processes the client request which is sent by the client, using the HTTP get
method. Browser uses get method to send request.

POST method:
POST method is a way to pass data entered in form to the server securely
without adding it to URL.
OR
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.

Page 3 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

g) State the use of “$” sign in PHP 2M


Ans. $ sign in PHP is used to indicate a variable. Correct use 2M
A variable starts with the $ sign, followed by the name of the variable.
Example:
$a=10

2. Attempt any THREE of the following: 12M


a) Write a program using do-while loop. 4M
Ans. <?php Correct
$n=1; program 4M
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>

Note: Any other relevant program shall be considered


b) Explain associative and multi dimensional arrays 4M
Ans. Associative Arrays
Explanation of
The associative arrays are very similar to numeric arrays in term of each 2M
functionality but they are different in terms of their index. Associative array
will have their index as string so that you can establish a strong association
between key and values.
Example
<?php
$salaries = array(
"mohammad" => 2000, "Dinesh" => 1000, "Surabhi" => 500
);
echo "Salary of Arjun is ". $salaries['Arjun'] . "<br />";
echo "Salary of Dinesh is ". $salaries['Dinesh']. "<br />";
echo "Salary of Surabhi is ". $salaries['Surabhi']. "<br />";
echo "<pre>";
print_r($salaries);
echo "</pre>";
?>

Page 4 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

Multidimensional Arrays
In multi-dimensional array, each element in the main array can also be an
array. A multidimensional array is an array containing one or more arrays. It
has more than one dimension in the form of rows and columns. Values in the
multi-dimensional array are accessed using multiple indexes.
Example:
In this example we create a two dimensional array to store marks of three
students in three subjects:
<?php
$marks = array(
"Arjun" => array
("physics" => 35, "maths" => 30, "chemistry" => 39),
"Dinesh" => array
("physics" => 30, "maths" => 32, "chemistry" => 29),
"Surabhi" => array
("physics" => 31, "maths" => 22, "chemistry" => 39)
);
/* Accessing multi-dimensional array values */
echo "Marks for Arjun in physics : " ;
echo $marks['Arjun']['physics'] . "<br />";
echo "Marks for Dinesh in maths : ";
echo $marks['Dinesh']['maths'] . "<br />";
echo "Marks for Surabhi in chemistry : " ;
echo $marks['Surabhi']['chemistry'] . "<br />";
echo "<pre>";
print_r($marks);
echo "</pre>";
?>
OR
$cars = array (array("Volvo",22,18), array("BMW",15,13),
array("Ciaaz",10,15));
OR
$row0 = array("Volvo",22,18);
$row1 = array("BMW",15,13);
$row2 = array("Ciaaz",10,15);

Page 5 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

$cars = array($row0, $row1, $row2);


Note: Any other relevant example shall be considered

c) Define serialization and explain it with example 4M


Ans. Definition:
The serialize() function converts a storable representation of a value. Correct
definition 2M
To serialize data means to convert a value to a sequence of bits, so that it can And any
be stored in a file, a memory buffer, or transmitted across a network. suitable
Syntax example 2M
serialize(value);
Example:
<?php
$data = serialize(array("Red", "Green", 4044));
echo $data;
?>
Output:
a:3:{i:0;s:3:"Red";i:1;s:5:"Green";i:2;i:4044;}
d) Describe the procedure of sending email. 4M
Ans. 1. PHP mail is the built-in PHP function that is used to send emails from PHP Correct
scripts. procedure 4M
2. The mail function accepts the following parameters;
a) Email address
b) Subject
c) Message
d) CC or BCC email addresses
3. The PHP mail function has the following basic syntax
<?php
mail($to_email_address,$subject,$message,[$headers],[$parameters]);
?>
HERE,
a) “$to_email_address” is the email address of the mail recipient
b) “$subject” is the email subject
c) “$message” is the message to be sent.
d) “[$headers]” is optional, it can be used to include information such as
CC, BCC
 CC is the acronym for carbon copy. It‟s used when you want to send a
copy to an interested person i.e. a complaint email sent to a company can
also be sent as CC to the complaints board.

Page 6 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

 BCC is the acronym for blind carbon copy. It is similar to CC. The email
addresses included in the BCC section will not be shown to the other
recipients.
4. PHP mailer uses Simple Mail Transmission Protocol (SMTP) to send mail.
On a hosted server, the SMTP settings would have already been set. The
SMTP mail settings can be configured from “php.ini” & “sendemail.ini”
file in the PHP installation folder.

Php Mail Example


<?php
$to_email = 'name @ company . com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply @ company . com';
mail($to_email,$subject,$message,$headers);
?>
3. Attempt any THREE of the following: 12M
a) Differentiate between implode and explode functions. 4M
Ans.
Implode function Explode function Any 4 correct
points-1M each
The implode function works on an The explode function works on a
array. string.

The implode function returns string. The explode function returns array.

The first parameter of the implode The first parameter of the explode
function is optional. function is required.
Syntax: Syntax:
string implode(string $seperator, array explode(string
array $array) separator,string string)

Example: Example:
<?php <?php
$arr = array('CO','IF','EJ'); $str = "CO-IF-EJ";
$str = implode(" ",$arr); $arr = implode("-",$str);
echo $str; print_r($arr);
?> ?>

Page 7 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

b) Explain the concept of cloning of an object 4M


Ans.  The clone keyword is used in PHP‟s to copy object.
 does a shallow copy and so, any changes made in the cloned object will Explanation
not affect the original object. 2M
 __clone is a magic method in PHP. Magic methods are predefined in PHP Example 2M
and start with “__” (double underscore). They are executed in response to
some events in PHP.

Example:
<?php
// Creating instance of Animals class
$objAnimals = new Animals();
// Assigning values
$objAnimals->name = "Lion";
$objAnimals->category = "Wild Animal";
// Cloning the original object
$objCloned = clone $objAnimals;
$objCloned->name = "Elephant";
$objCloned->category = "Wild Animal";
print_r($objAnimals);
print_r($objCloned);
?>
c) Describe the procedure of validation of web page 4M
Ans. Validating a web page in PHP involves checking the input data provided by
Explanation
users to ensure that it meets the required criteria and is safe for further 3M
processing. Here's a general procedure for validating a web page in PHP:
The procedure of validation of web page.
Define the Validation Rules: Determine the validation rules for each input Example 1M
field on the web page. This includes constraints such as required fields, data
formats (e.g., email, date), length limits, and any specific patterns or
restrictions.
Create the HTML Form: Design and create the HTML form that collects
user input. Specify the appropriate input types, such as text, email, number,
etc., and include any necessary attributes like required or pattern.

Page 8 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

Submitting the Form: Set up the PHP script that processes the form
submission. This script will be responsible for handling the validation and
processing the data. Ensure that the form's method attribute is set to "POST"
so that the data is sent securely.

Retrieve and Sanitize Input: In the PHP script, retrieve the submitted data
using the $_POST superglobal array. Sanitize the input to remove any
unwanted characters or tags that could potentially pose security risks. You
can use functions like htmlspecialchars or filter_input to sanitize specific
inputs.

Perform Validation: Apply the validation rules defined in Step 1 to each


input field. Use PHP's conditional statements, loops, and regular expressions
to check if the input data meets the required criteria. For example, you can
use if statements and regular expressions to validate email addresses, check
for empty fields, or validate numeric values.

Display Validation Errors: If any input fails validation, store the error
messages in an array or variable. Display these error messages next to the
corresponding input fields on the web page, informing the user about the
specific validation issues they need to address.

Process Valid Data: If all the input data passes validation, proceed with
further processing, such as storing the data in a database, sending emails, or
performing other necessary operations.

Redisplay Form with Pre-filled Data: If there are validation errors,


redisplay the form with the user's previously submitted data already filled in.
This provides a better user experience and allows users to correct the invalid
fields without re-entering all the data.
Example:
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
if(empty(trim($_POST["name"]))){

Page 9 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

$name_err = "Please enter your name.";


} else{
$name = trim($_POST["name"]);
}
}
d) Write update and delete operations on table data 4M
Ans. Update operations:
 The UPDATE statement is used to change or modify the existing records Correct
in a database table. operation
 SQL query will be formed using the UPDATE statement and WHERE statement 2M
each
clause, after that a query will be executed by passing it to the PHPquery()
function to update the tables records.
Example:
The percentage of roll no. C101 will be updated to ‟98.99‟ from student
table by using UPDATE statement.
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "UPDATE student SET percent=98.99
WHERE rollno='CO101'";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
?>
Delete operation:
 Records can be deleted from a table using the SQL DELETE statement.
 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
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);

Page 10 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

if ($conn->connect_error) die($conn->connect_error);
$query = "DELETE from student WHERE rollno='CO103'";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
?>
4. Attempt any THREE of the following: 12M
a) State user defined functions and explain it with example. 4M
Ans. A function is a named block of code that performs a specific task.PHP
supports user defined functions, where user can define his own functions. Correct
explanation -
A function doesn't execute when its defined, it executes when it is called.
2M
The syntax to create a PHP user defined function –
A PHP user-defined function declaration starts with the keyword function as
shown below – Any correct
function funName($arg1, $arg2, ... $argn) Example-2M

{
// code to be executed inside a function
//return $val
}
The syntax to call a PHP user-defined function –
$ret=funName($arg1, $arg2, ... $argn);
Example:
<?php
// user-defined function definition
function printMessage(){
echo "Hello, How are you?";
}
//user-defined function call
printMessage();
?>
As in the above program, the printMessage() function is created using the
keyword function. The function prints the message “Hello, How are you?”.
So, farther in the program when it is calling the function as
“printMessage();”. It prints a message, as we can see in the above output.

Page 11 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

b) Describe inheritance, overloading, overriding and cloning object. 4M


Ans. Inheritance allows classes to inherit properties and methods from a parent
Each term
class, overloading provides dynamic property and method handling, description 1M
overriding enables customization of inherited methods, and cloning creates
copies of objects.

1. Inheritance: Inheritance is a fundamental concept in object-oriented


programming that allows classes to inherit properties and methods from
another class. In PHP, we can define a new class by extending an existing
class using the extends keyword. The new class is called the child or derived
class, and the existing class is called the parent or base class. The child class
inherits all the public and protected properties and methods of the parent
class. It can also add its own properties and methods or override the parent
class's methods.
2. Overloading: In PHP, overloading refers to the ability to dynamically
create properties and methods in a class at runtime. There are two types of
overloading:
a. Property Overloading: PHP provides the __set() and __get() magic
methods to handle property overloading. When a property is accessed or
modified that doesn't exist or is inaccessible within the class, these methods
are called, allowing us to define custom logic for handling the property.
b. Method Overloading: PHP doesn't support method overloading in the
traditional sense (having multiple methods with the same name but different
parameters). However,we can use the __call() magic method to handle
method overloading. It gets called when a non-existent or inaccessible
method is invoked, giving the flexibility to handle the method dynamically.
3. Overriding: Overriding occurs when a child class provides its own
implementation of a method that is already defined in the parent class. The
method signature (name and parameters) in the child class must match that of
the parent class. By overriding a method, we can customize the behaviour of
the method in the child class while retaining the same method name. To
override a method in PHP, simply declare the method in the child class with
the same name as the parent class's method.

Page 12 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

4. Cloning Objects: Cloning an object in PHP allows us to create a duplicate


of an existing object. The clone is a separate instance of the class, but its
properties will initially have the same values as the original object. In PHP,
we can clone an object using the clone keyword followed by the object you
want to clone. The cloning process involves calling the __clone() magic
method if it's defined in the class. This method allows us to customize the
cloning process by modifying the properties of the cloned object if necessary.

c) Explain web server role in web development 4M


Ans. The web server's role in PHP web development as shown below:
Any relevant
Diagram 1M

Explanation
3M

1. HTTP Request Handling: When a user accesses a PHP-based web


application, their browser sends an HTTP request to the web server. The web
server receives this request and determines how to handle it based on the
requested URL and the HTTP method used (e.g., GET, POST). The server is
responsible for routing the request to the appropriate PHP script or file for
processing.
2. PHP Script Execution: Once the web server receives an HTTP request
that requires PHP processing, it passes the request to the PHP interpreter or
engine. The PHP interpreter executes the PHP code contained within the
requested file or script. It processes the logic, interacts with databases,
performs computations, and generates dynamic HTML or other types of
content.
3. Server-Side Processing: PHP is a server-side scripting language, meaning
the PHP code is executed on the server before the resulting HTML or other
output is sent back to the client's browser. The web server runs the PHP script
in its environment and provides necessary resources like database
connections, file access, and session management.
4. Integration with Other Technologies: In addition to executing PHP code,
the web server may also be responsible for integrating with other
technologies commonly used in web development. For example, the web

Page 13 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

server can handle requests for static files like CSS, JavaScript, and images,
delivering them directly to the client without involving PHP processing. It
can also handle URL rewriting or redirection for search engine optimization
(SEO) purposes or to create user-friendly URLs.
5. Content Delivery: Once the PHP script execution is complete, the web
server sends the generated content (usually HTML) back to the client's
browser as an HTTP response. The server sets the appropriate headers, such
as Content-Type, Content-Length, and caching directives, to ensure the
correct interpretation and rendering of the response by the client.
6. Error Handling and Logging: The web server is responsible for handling
errors and logging relevant information. If an error occurs during PHP script
execution, the web server can be configured to display an error message or
redirect to a custom error page. It also logs information about requests, errors,
and server events, which can be helpful for debugging, monitoring, and
performance analysis.

d) Explain inserting & Retrieving the query result operations. 4M


Ans. Insert operation:
Data can be inserted into an existing database table with an INSERT INTO Insertion with
example- 2M
query.SQL query using the INSERT INTO statement with appropriate values,
after that we will execute this insert query through passing it to the PHP
query() function to insert data in table.
Retrieving with
For example a student data is inserted into a table example-2M
using INSERT INTO statement.

<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "INSERT INTO student(rollno,name,percent) VALUES
('CO103','Reena Patel',98.45)";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
?>

Page 14 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

Retrieving operation:
The data can be retrieved from the table using SQL SELECT statement which
is used to select the records from database tables.
SQL query using the SELECT statement will be executed by passing this
SQL query to the PHP query() function to retrieve the table data.

For example data from the student table can be executed by using the
SELECT statement.
select_sample.php
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "SELECT * FROM student";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " .
$conn->error);
$rows = $result->num_rows;
echo "<table
border='1'><tr><th>RollNo.</th><th>Name</th><th>Percentage</th></tr>";
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo "<tr>";
for ($k = 0 ; $k < 3 ; ++$k) echo
"<td>$row[$k]</td>";
echo "</tr>";
}
echo "</table>";
?>
e) Create a web page using GUI components 4M
Ans. <!DOCTYPE html>
<html> Correct syntax
of any four
<head> GUI
<title>Registration form</title> components
<link rel="stylesheet" href="styel.css" type="text/css">
</head> 1M for each
component

Page 15 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

<body>
<div class="main">
<div class="register">
<h2>Register Here</h2>
<form id="register" action="registrationform.php" method="post">

<label>First name:</label>
<br>
<input type="text" id="fname" name="fname" placeholder="Enter your first
name">
<br>
<br>

<label>Last name:</label>
<br>
<input type="text" id="lname" name="lname" placeholder="Enter your last
name">
<br>
<br>

<label for="email">Enter your email:</label>


<br>
<input type="email" id="email" name="email" placeholder="Enter valid
email">
<br>
<br>

<label>Date of Birth:</label>
<br>
<input type="date" id="dob" name="dob" placeholder="Enter your
Birthday">
<br>
<br>

<label>Gender:</label>
<br>
&nbsp;&nbsp;&nbsp;
<input type="radio" id="male" name="gender" value="male">
&nbsp;

Page 16 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

<span id="male">Male</span>
&nbsp;&nbsp;&nbsp;&nbsp;
<input type="radio" id="female" name="gender" value="female">
&nbsp;
<span id="female">Female</span>

<br>
<br>

<label>Enter mobile number:</label><br><br>


<input type="tel" id="mobno" name="mobno" placeholder="Enter your
mobile number" pattern="[7-9]{1}[0-9]{9}" required>
<br>
<br>

<label>Select Usertype</label>
<br>
<select name="usertype" id="usertype">
<option value="Student">Student</option>
<option value="Staff">Staff</option>
<option value="Alumni">Alumni</option>
</select>
<br>
<br>

<label>Password:</label>
<br>
<input type="password" id="pwd" name="password" placeholder="Enter
your password" pattern ="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must
contain at least one number and one uppercase and lowercase letter, and at
least 8 or more characters" required>

<br>
<br>

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

</form>
</div><!-----end of register--->

Page 17 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

</div><!-----end of main---->
</body>
</html>
5. Attempt any TWO of the following 12M
a) Implement any three data types used in PHP with illustration 6M
Ans. Data Types :
PHP provides eight types of values, or data types: Implementation
Four are scalar (single-value) types: integers, floating-point numbers, strings, / example of
and Booleans. any three data
types -2Meach
Two are compound (collection) types: arrays and objects.
Two are special types: resource andNULL.

Integers: Integers are whole numbers, such as 1, 12, and 256. Integer literals
can be written in decimal, octal, or hexadecimal.
Example :
Decimal1998 ,−641 , +33
Octal0755 // decimal 493 , 010 // decimal 8
Hexadecimal0xFF // decimal 255 ,0x10 // decimal 16 , -0xDAD1 // decimal
−56017
Binary numbers begin with 0b, followed by a sequence of digits (0 and 1).
Like other values, you can include a sign in binary numbers: 0b01100000 //
decimal 1 ,0b00000010 // decimal 2

Floating-Point Numbers: Floating-point numbers (often referred to as real


numbers) represent numeric values with decimal digits. This allows numbers
between 1.7E−308 and 1.7E+308 with 15 digits of accuracy.
PHP recognizes floating-point numbers written in two different formats.
General format :3.14 , 0.017 , -7.1
Scientific format: 0.314E1 // 0.314*10^1, or 3.14 , 17.0E-3 // 17.0*10^(-3),
or 0.017
Floating-point values are only approximate representations of numbers. For
example, on many systems 3.5 is actually represented as 3.4999999999.
Strings: As strings are very common in web applications, PHP includes core-
level support for creating and manipulating strings. A string is a sequence of
characters of arbitrary length. String literals are delimited by either single or
double quotes: 'big dog' or "fat hog" .
Example: $no=10;
$str1=” My roll number is $no”
echo $str1;

Page 18 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

Booleans :A Boolean value represents either true(1) or false(0). Boolean


values are often used in conditional testing.
Example: $var=TRUE;

Arrays :An array holds a group of values, which you can identify by position
(a number, with zero being the first position) or some identifying name (a
string), called an associative index.
Example: The array() construct creates an array.
$person = array("Edison", "Wankel", "Crapper");
$creator = array('Light bulb' =>"Edison", 'Rotary Engine' =>"Wankel",
'Toilet' =>"Crapper");

Objects :Classes are the building blocks of object-oriented design. A class is


a definition of a structure that contains properties (variables) and methods
(functions). Once a class is defined, any number of objects can be made from
it with the new keyword, and the object‟s properties and methods can be
accessed with the -> construct:
$ed = new Person;
$ed->name('Edison');

Resource :Many modules provide several functions for dealing with the
outside world. For example, every database extension has at least a function
to connect to the database, a function to send a query to the database, and a
function to close the connection to the database.
Example :$res = database_connect();
database_query($res);

NULL :The NULL value represents a variable that has no value.


Example:
$aleph = NULL;
b) Write a program to connect PHP with MySQL 6M
Ans. Solution1:
Correct logic
<?php 3M
$servername = "localhost";
$username = "root";
$password = ""; Correct syntax
// Connection 3M
$conn = new mysqli($servername,$username, $password);

Page 19 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

// For checking if connection issuccessful or not


if ($conn->connect_error)
{
die("Connection failed: ". $conn->connect_error);
}
echo "Connected successfully";
?>

OR
Solution2:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

OR
Solution 3:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>

Page 20 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

c) Explain the concept of constructor and destructor in detail. 6M


Ans. Constructor: A constructor is a special built-in method. Constructors allow
initializing object properties when an object is created. A constructor method Explanation of
execute automatically when an object is created. The 'construct' method starts Constructor
3M
with two underscores (__).T
Syntax :function __construct([argument1, argument2, ..., argumentN]) Explanation of
{ destructor
/* Class initialization code */ 3M
}
The type of argument1, argument2,.......,argumentN are mixed.
Example :
<?php
class student
{
var $name;
function __construct($name)
{
$this->name=$name;
}
function display()
{
echo $this->name;
}
}
$s1=new student("xyz");
$s1->display();
?>
Destructor: A destructor is the counterpart of constructor. A destructor
function is called when the object is destroyed. A destructor function cleans
up any resources allocated to an object after the object is destroyed. A
destructor function is commonly called in two ways: When a script ends or
manually delete an object with the unset() function.The 'destruct' method
starts with two underscores (__).

Syntax :function __destruct()


{
/* Class initialization code */
}
The type of argument1, argument2,.......,argumentN are mixed.

Page 21 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

Example :
<?php
class student
{
var $name;
function __construct($name)
{
$this->name=$name;
}
function __destruct()
{
echo "Destructor is executing " .$this->name;
}
}
$s1=new student("xyz");
?>
6. Attempt any TWO of the following 12M
a) Describe form controls – text box, text area, radio button, check box, list 6M
& buttons
Ans. Form Controls : Description of
each control
1. Textbox : A text box is used to enter data. It is a single line input on a web 1M
page.
Tag :<input type=“text”> : It is used to display a text box on a web page.
Attributes of <input> tag used with text box:
name=“ text” : Specify name of text box for unique identification.
maxlength=number : Specify maximum number of characters that can be
accepted in a textbox.
size=number : Specify the width of text box in number of characters.
value=“text” : Specify default text value that appears in the text box when
loaded on a web page.
Example:<input type=“text” name=“n1” maxlength=20 size=15
value=“Enter your name” >

2. Textarea : It is used to display a textbox that allow user to enter multiple


lines of text. Scrollbar is used to move up and down as well as left and right if
the contents are more than size of box.
Tag :<textarea> … </textarea> : It is used to display a multiline text box on
a web page.

Page 22 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

Attributes:
name=“ text” : Specify name of the element for unique identification.
cols=number : Specify width of the text area.
rows=number : Specify height of the text area.
readonly : Specify a text area as read only element.
Example:<textarea name=“t1” cols=10 rows=10>Enter your
suggestions</textarea>

3. Radio / option button : Radio buttons are used to display multiple options
from which user can select only one option. When a radio button is selected
by user, a dot symbol appears inside button. Multiple option buttons are
group together to allow user to select only one option from the group. A
group can be created by giving same name to all option buttons in that group.
Tag :<input type=“radio”> : It is used to display a radio button on a web
page.
Attributes of <input> tag used with radio button:
name=“ text” : Specify name of radio button for unique identification.
value=“text” : Specify value to be returned to the destination if that radio
button is selected.
checked: Specify default selection
Example:<input type=“radio” name=“r1” value=“male”>male
<input type=“radio” name=“r1” value=“female” checked>female

4. Checkbox : Checkbox elements are used to display multiple options from


which user can select one or more options. When a checkbox is selected by
user, a tickmark( √ ) symbol appears inside box.
Tag: <input type=“checkbox”> : It is used to display a checkbox on a web
page.
Attributes of <input> tag used with checkbox:
name=“ text” : Specify name of checkbox for unique identification.
value=“text” : Specify value to be returned to the destination if that
checkbox is checked.
Checked: Specify default selection.
Example: <input type=“checkbox” name=“c1” value=“pen” checked>pen

Page 23 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

5. Select element (list) :<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.
Attributes:
name=“ text” : Specify name of the element for unique identification.
size=number : Specify number of options visible in a list box on a web page.
Multiple : Allow user to select multiple option with control key.
<option> … </option> tag is used to insert item in a list.
Attributes:
value=“text” : Specify value to be sent to the server once selected by user.
selected: Specify default selection.
Example:<select name=“s1” size=2>
<option value=“ Pizza”>Pizza1 </option>
<option value=“ Burger”>Burger</option>
<option value=“ Chocolate”>Chocolate</option>
</select>
6. Note: Explanation of button OR submit button OR reset button shall be
considered
i) Button : Buttons are used to display a command button which user can
click on web page to perform some action.
Tag :<input type=“button”> : It is used to display a button on a web page.
Attributes of <input> tag used with button:
name=“ text” : Specify name of button for unique identification.
value=“text” : Specify value to be displayed on button.
Example:<input type=“button” name=“b1” value=“login”>

ii) Submit button : Submit button is used to display a command button


which user can click on web page to submit information entered in a form.
Tag :<input type=“submit”> : It is used to display a submit button on a web
page.
Attributes of <input> tag used with submit button:
name=“ text” : Specify name of submit button for unique identification.
value=“text” : Specify value to be displayed on submit button.
Example:<input type=“submit” name=“s1” value=“Submit Form”>

iii) Reset button : Reset button is used to clear all elements with their
original state after user clicks on it.

Page 24 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

Tag :<input type=“reset”> : It is used to display a reset button on a web


page.
Attributes of <input> tag used with reset button:
name=“ text” : Specify name of reset button for unique identification
value=“text” : Specify value to be displayed on reset button.
Example: <input type=“reset” name=“r1” value=“Reset Form”>

b) Write a program to create pdf document in PHP 6M


Ans. <?php
require("fpdf/fpdf.php"); // path to fpdf.php Correct logic
$pdf = new FPDF(); 3M
$pdf->addPage();
$pdf->setFont("Arial", 'IBU', 16); Correct syntax
$pdf->settextcolor(150,200,225); 3M
$pdf->cell(40, 10, "Hello Out There!");
$pdf->output();
?>
c) Elaborate the following: 6M
i) _call()
Relevant
ii) Mysqli_connect() explanation of
Ans.
Function overloading : each 3M
When a class has more than one function with same name but different
number of parameters then it is referred as function overloading. A same
name function behaves differently depending on arguments / parameters
passed to it.

__call() :In PHP, for function overloading , __call() method is used. This
function is triggered while invoking overloaded methods in the object
context.The $name argument is the name of the method being called.
The $arguments argument is an enumerated array containing the parameters
passed to the $named method.

Example :
<?php
class Shape1 {
const PI1 = 3.142 ;
function __call($name1,$arg1){
if($name1 == 'area1')
switch(count($arg1)){

Page 25 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2023 EXAMINATION


MODEL ANSWER-Only for the Use of RAC Assessors

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

case 0 : return 0 ;
case 1 : return self::PI1 * $arg1[0] ;
case 2 : return $arg1[0] * $arg1[1];
}
}
}
$circle1 = new Shape1();
echo "Area of Circle= ".$circle1->area1(3);
echo "<br><br>";
$rect1 = new Shape1();
echo "Area of Rectangle= ".$rect1->area1(8,6);
?>

ii) Mysqli_connect()
Mysqli_connect() function opens a new connection to the MySQL server.

Syntax :
mysqli_connect(host, username, password, dbname)

host: Optional parameter. It specifies a host name .


username: It specify MySQL username.
Password: It specify MySQL password.
Dbname: It specify the database name to be used to connect php code.

Example :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Page 26 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using 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 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.No Sub Answer Marking


Q.N. Scheme
1. Attempt any FIVE of the following: 10
a) Describe advantages of PHP. 2M
Ans.  Easy to Learn ½ M each,
 Familiarity with Syntax any four
 PHP is an open-source web development language, it‟s advantages
completely free of cost.
 PHP is one of the best user-friendly programming languages in
the industry.
 PHP supports all of the leading databases, including MySQL,
ODBC, SQLite and more
 effective and efficient programming language
 Platform Independent
 PHP uses its own memory space, so the workload of the server
and loading time will reduce automatically, which results into
the faster processing speed.

Page 1 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

 PHP is one of the most secure ways of developing websites and


dynamic web applications. PHP has multiple layers of security
to prevent threats and malicious attacks.
b) What is array? How to store data in array? 2M
Ans. 1. An array in PHP is an ordered map where a map is a type that
associates values to keys.
1M for
2. Ways to store an array. definition
Using array variable 1M to store
<?php data
$array_fruits= array('Apple', 'Orange', 'Watermelon', 'Mango');
?>
OR
Using array indices
<?php
$array= [];// initializing an array
$array[] = 'Apple';
$array[] = 'Orange';
$array[] = 'Watermelon;
$array[] = „Mango;
print_r($array);
?>

c) List types of inheritance. 2M


Ans. 1. Single Level Inheritance 2M for any
2. Multiple Inheritance four
3. Multiple Inheritance (Interfaces) correct
4. Hierarchical Inheritance names of
inheritance

d) How can we destroy cookies? 2M


Ans. We can destroy the cookie just by updating the expire-time value 1M for
of the cookie by setting it to a past time using the explanatio
setcookie() function. n
1M for
Syntax: setcookie(name, time() - 3600); syntax/
example
e) List any four data types in MYSQL 2M

Page 2 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

Ans. (Any correct data types can also be considered)


Data Type Size Description

CHAR(size) Maximum 255 characters Fixed-length 2M for


Character strings. any four
VARCHAR Maximum 255 characters Variable length correct
(size) string types
TEXT(size) Maximum size of 65,535 Here size is the
characters. number of
characters to
store.
INT(m)/ Signed values range from - Standard integer
INTEGER( 2147483648 to value.
m) 2147483647. Unsigned
values range from 0 to
4294967295. (4 bytes)
DATE() (3 bytes) Displayed as Displayed as
'yyyy-mm-dd'. 'yyyy-mm-dd'
DATETIM Values range from '1000- (8 bytes)
E() 01-01 00:00:00' to '9999- Displayed as
12-31 23:59:59'. 'yyyy-mm-
ddhh:mm:ss'.
f) Write syntax of PHP. 2M
Ans. A PHP script starts with the tag <?php and end with tag ?>. 2M for
The PHP delimiter in the following example simply tells the PHP correct
engine to treat the enclosed code block as PHP code, rather than syntax
simple HTML
Syntax:
<?php
echo „Hello World‟;
?>
g) How to create session variable in PHP? 2M
Ans.  Session variable can be set with a help of a PHP global variable: 1M for
$_SESSION. explanatio
 Data in the session is stored in the form of keys and values pair. n
 We can store any type of data on the server, which include 1M for
arrays and objects. correct
 For example, we want to store username in the session so it can syntax /
be assessed whenever it is required throughout the session. example

Page 3 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

<?php
session_start();
$_SESSION["username"] = "abc";
?>
2. Attempt any THREE of the following: 12
a) Write down rules for declaring PHP variable 4M
Ans. a. A variable starts with the $ sign, followed by the name of the 1M for
variable. each
b. A variable name must start with a letter or the underscore correct
character. rule, any
c. A variable name should not contain spaces. If a variable name is four rules
more than one word, it should be separated with an underscore can be
($first_name), or with capitalisation ($firstName). considered
d. Variables used before they are assigned have default values.
e. A variable name cannot start with a number.
f. A variable name can only contain alpha-numeric characters (A-
Z, a-z) and underscores.
g. Variable names are case-sensitive ($name and $NAME are two
different variables)
h. Variables can, but do not need, to be declared before
assignment. PHP automatically converts the variable to the
correct data type, depending on its value.
i. Variables in PHP do not have intrinsic types - a variable does
not know in advance whether it will be used to store a number
or a string of characters
b) Write a program to create associative array in PHP. 4M
Ans. <?php 4M for any
$a = array("sub1"=>23,"sub2"=>23,"sub3"=>12,"sub4"=>13); correct
var_dump($a); code for
echo "<br>"; associative
foreach ($a as $x) array
echo "$x<br>";
echo "using for loop<br>";
$aLength= count($a);
echo "Count of elements=$aLength<br>";
for ($i=0;$i<$aLength;$i++)
echo "$a[$i]<br>";
echo "array function extract<br>";
extract($a);

Page 4 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

echo $a1."<br>".$a2."<br>".$a3."<br>".$a4."<br>";
?>
c) Define Introspection and explain it with suitable example. 4M
Ans.  Introspection in PHP offers the useful ability to examine an 1M for
object's characteristics, such as its name, parent class (if any) definition
properties, classes, interfaces and methods. 1M for
 PHP offers a large number functions that can be used to explanatio
accomplish the above task. n
 Following are the functions to extract basic information about 2M for any
classes such as their name, the name of their parent class etc. correct
example

Example:
<?php
class Test
{
function testing_one()
{
return(true);
}
function testing_two()
{
return(true);
}
function testing_three()

Page 5 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

{
return(true);
}
//Class "Test" exist or not
if (class_exists('Test'))
{
$t = new Test();
echo "The class is exist. <br>";
}
else
{
echo "Class does not exist. <br>";
}
//Access name of the class
$p= new Test();
echo "Its class name is " ,get_class($p) , "<br>";
//Aceess name of the methods/functions
$method = get_class_methods(new Test());
echo "<b>List of Methods:</b><br>";
foreach ($method as $method_name)
{
echo "$method_name<br>";
}
?>
Output :
The class is exist.
Its class name is Test
List of Methods:
testing_one
testing_two
testing_three
d) Write difference between get() and post() method of form (Any 4M
four points)
Ans. HTTP GET HTTP POST 1M for
In GET method we cannot send In POST method large each
large amount of data rather amount of data can be correct
limited data is sent because the sent because the request differentiat
request parameter is appended parameter is appended ion, any
into the URL. into the body. four points

Page 6 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

GET request is comparatively POST request is to be


better than Post so it is used comparatively less better considered
more than the Post request. than Get so it is used less
than the Get request.
GET request is comparatively POST request is
less secure because the data is comparatively more
exposed in the URL bar. secure because the data is
not exposed in the URL
bar.
Request made through GET Request made through
method are stored in Browser POST method is not
history. stored in Browser history.
GET method request can be POST method request
saved as bookmark in browser. cannot be saved as
bookmark in browser.
Request made through GET Request made through
method are stored in cache POST method are not
memory of Browser. stored in cache memory
of Browser.
Data passed through GET Data passed through
method can be easily stolen by POST method cannot be
attackers. easily stolen by attackers.
In GET method only ASCII In POST method all types
characters are allowed. of data is allowed.
3. Attempt any THREE of the following: 12
a) Define function. How to define user defined function in PHP? 4M
Give example. 1M for
Ans. Definition: -A function is a block of code written in a program to definition
perform some specific task.
They take information as parameters, execute a block of statements 1M for
or perform operations on these parameters and return the result. A syntax
function will be executed by a call to the function. 2M for
any
Define User Defined Function in PHP: A user-defined function relevant
declaration starts with the keyword function. example

Syntax
function functionName() {
code to be executed;

Page 7 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

}
Example
<?php
function writeMsg() {
echo "Welcome to PHP world!";
}
writeMsg(); // call the function
?>
(Any other example can be considered)
b) Explain method overloading with example. 4M
Ans. Function overloading or method overloading is the ability to create 2M for
multiple functions of the same name with different implementations explanatio
depending on the type of their arguments. n
In PHP overloading means the behavior of a method changes 2M for
dynamically according to the input parameter. example
__call() is triggered when invoking inaccessible methods in an
object context.
__callStatic() is triggered when invoking inaccessible methods in a
static context.

__call():
If a class execute __call(), then if an object of that class is called
with a method that doesn't exist then__call() is called instead of that
method.

example:-
<?php
// PHP program to explain function
// overloading in PHP
// Creating a class of type shape
class shape {
// __call is magic function which accepts
// function name and arguments

function __call($name_of_function, $arguments) {


// It will match the function name
if($name_of_function == 'area') {
switch (count($arguments)) {
// If there is only one argument

Page 8 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

// area of circle
case 1:
return 3.14 * $arguments[0];

// IF two arguments then area is rectangle;


case 2:
return $arguments[0]*$arguments[1];
}
}
}
}

// Declaring a shape type object


$s = new Shape;

// Function call
echo($s->area(2));
echo "<br>";

// calling area method for rectangle


echo ($s->area(4, 2));
?>
Output:
9.426
48

Here the area() method is created dynamically and executed with


the help of magic method __call() and its behavior changes
according to the pass of parameters as object.
(Any other example can be considered)
c) Define session and cookie. Explain use of session start. 4M
Ans. Session 1M for
Session is a way to store information to be used across multiple each
pages, and session stores the variables until the browser is closed. definition
To start a session, the session_start() function is used and to destroy 2M for use
a session, the session_unset() and the session_destroy() functions of session
are used. start
The session variables of a session can be accessed by using the
$_SESSION super-global variable.

Page 9 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

Cookie
Cookie is a small piece of information stored as a file in the user's
browser by the web server. A cookie stores some data temporarily
(until the expiration date has passed).There is no Unique ID
allocated for a Cookie. The cookie data can be accessed using the
$_COOKIE super-global variable. A cookie can be set using the
setcookie() function.

Use of Session start


PHP session_start() function is used to start the session. It starts a
new or resumes an existing session. It returns an existing session if
the session is created already. If a session is not available, it creates
and returns a new session.
session_start() creates a session or resumes the current one based
on a session identifier passed via a GET or POST request, or passed
via a cookie.

Example optional:-
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["uname"]="Customer1";
$_SESSION["fcolor"]="RED";
echo "The session variable are set with values";
?>
</body>
</html>
d) Explain delete operation of PHP on table data. 4M
Ans. Delete command is used to delete rows that are no longer required 2M for
from the database tables. It deletes the whole row from the table. explanatio
n
The DELETE statement is used to delete records from a table: 2M for
DELETE FROM table_name WHERE some_column = program /
some_value Example

Page 10 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP 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.
Below is a simple example to delete records into the student.pridata
table. To delete a record in any table it is required to locate that
record by using a conditional clause. Below example uses name to
match a record in student.pridata table.
Example:-
Assume Following Table
Database Name-student
Table name - pridata

<?php
$server='localhost';
$username='root';
$password='';
$con=mysqli_connect($server,$username,$password);
if(!$con){
die("Connection to this database failed due to"
.mysqli_connect_error($mysqli));
}
$sql="DELETE FROM student.pridataWHERE name='amit'";
if($con->query($sql)==true){
echo "Record deleted successfully";
}
else{
"ERROR:error".$con->error();
}
$con->close();
?>

Output:-

Page 11 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

Table after Deletion

(Any other example can be considered)

4. Attempt any THREE of the following: 12


a) Write PHP script to sort any five numbers using array 4M
function. 4M for
Ans. <?php correct and
$a = array(1, 8, 9, 4, 5); equivalent
sort($a); code
foreach($a as $i) {
echo $i.' ';
}
?>

OR

<!DOCTYPE html>
<html>
<body>
<H1>Enter five numbers </H1>
<form action = 'sort.php' method = 'post'>
<input type = 'number' name = 'n1' placeholder = 'Number
1...'><br><br>
<input type = 'number' name = 'n2' placeholder = 'Number
2...'><br><br>
<input type = 'number' name = 'n3' placeholder = 'Number
3...'><br><br>
<input type = 'number' name = 'n4' placeholder = 'Number
4...'><br><br>
<input type = 'number' name = 'n5' placeholder = 'Number
5...'><br><br>
<input type = 'submit' value = 'Submit'>
</form>
</body>
</html>

Page 12 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

sort.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$a = array($_POST['n1'], $_POST['n2'], $_POST['n3'],
$_POST['n4'], $_POST['n5']);
sort($a);
}
foreach($a as $i) {
echo $i.' ';
}
?>
(Any other example can be considered)
b) Write PHP program for cloning of an object 4M
Ans. (Any other correct program can be considered) 4M for
Code:- correct
<!DOCTYPE html> program
<html>
<body>

<?php
class car {
public $color;
public $price;
function __construct()
{
$this->color = 'red';
$this->price = 200000;
}
}
$mycar = new car();
$mycar->color = 'blue';
$mycar->price = 500000;
$newcar = clone $mycar;
print_r($newcar);
?>
</body>
</html>

Page 13 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

Explanation
The above code creates a car with a constructor which initializes its
member variable named color and price.
An object of the variable is created, and it is cloned to demonstrate
deep cloning.
c) Create customer form like customer name, address, mobile no, 4M
date of birth using different form of input elements & display
user inserted values in new PHP form.
Ans. <!DOCTYPE html>
<html> 4M for
<body> correct and
<form action = 'data..php' method = 'post'> equivalent
<input type = 'text' name = 'name' placeholder = 'Customer code
Name...'><br><br>
<input type = 'text' name = 'address' placeholder =
'Address...'><br><br>
<input type = 'text' name = 'number' placeholder = 'Mobile
Number...'><br><br>
<label> Date of Birth: </label>
<input type = 'date' name = 'dob'><br><br>
<input type = 'submit' value = 'Submit'><br>
</form>
</body>
</html>

data.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo '<html><body><form>
Customer Name: '.$_POST['name'].'<br>
Address: '.$_POST['address'].'<br>
Mobile Number: '.$_POST['number'].'<br>
Date of Birth: '.$_POST['dob'];
}
?>
(Any other correct program logic can be considered)
d) Inserting and retrieving the query result operations 4M
Ans. <?php 2M for
$con = mysqli_connect('localhost', 'root', '', 'class'); inserting

Page 14 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

# Connecting to Database 2M for


$query = "insert into user values(1, 'Amit')"; retrieving
# Inserting Values the query
$result = mysqli_query($con, $query); result
if($result) { operations
echo 'Insertion Successful <br>';
}
else {
echo 'Insertion Unsuccessful <br>';
}

$query = "select * from user";


# Retrieving Values
$result = mysqli_query($con, $query);

foreach($result as $r) {
echo $r['roll_number'].' '.$r['name'];
}
?>
Output
Insertion Successful
1 Amit
Explanation
The above code connects with a database named „class‟‟.
The exam database has a table named „user‟ with 2 columns
roll_number and name.
It executes an insert query on the user and checks whether the
insertion was successful or not.
It executes a select query on the user and displays the information
retrieved.
(Any other example can be considered)

e) How do you validate user inputs in PHP. 4M


Ans. Invalid user input can make errors in processing. Therefore, 2M for
validating inputs is a must. explanatio
1. Required field will check whether the field is filled or not in the n
proper way. Most of cases we will use the * symbol for required 2M for
field. program
2. Validation means check the input submitted by the user.

Page 15 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

There are two types of validation available in PHP.


Client-Side Validation − Validation is performed on the client
machine web browsers.
Server Side Validation − After submitted by data, The data is sent
to a server and performs validation checks in the server machine.

Some of Validation rules for field


Field Validation Rules
Name Should required letters and white-spaces
Email Should be required @ and .
Website Should required a valid URL
Radio Must be selectable at least once
Check Box Must be checkable at least once
Drop Down menu Must be selectable at least once

The preg_match() function searches a string for pattern, returning


true if the pattern exists, and false otherwise.

To check whether an email address is well-formed is to use PHP's


filter_var() function.

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.

Example:-
Validations for: - name, email, phone no, website url
<!DOCTYPE html>
<body>
<?php
$nerror = $merror = $perror = $werror = $cerror = "";
$name = $email = $phone = $website = $comment = "";
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)* @[a-z0-9-]+(\.[a-z0-9-
]+)*(\.[a-z]{2,3})$^";

Page 16 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

if($_SERVER["REQUEST_METHOD"]=="POST") {
if(empty($_POST["name"])) {
$nerror = "Name cannot be empty!";
}
else {
$name = test_input($_POST["name"]);
if(!preg_match("/^[a-zA-Z-']*$/",$name))
{
$nerror = "Only characters and white spaces allowed";
}
}
if(empty($_POST["email"])) {
$merror = "Email cannot be empty!";
}
else
{
$email = test_input($_POST["email"]);
if(!preg_match($pattern, $email)) {
$merror = "Email is not valid";
}
}
if(empty($_POST["phone"])) {
$perror = "Phone no cannot be empty!";
}
else {
$phone = test_input($_POST["phone"]);
if (!preg_match ('/^[0-9]{10}+$/', $phone)) {
$perror = "Phn no is not valid";
}
}
if(empty($_POST["website"])) {
$werror = "This field cannot be empty!";
}
else {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$werror = "URL is not valid";
}

Page 17 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

}
if (empty($_POST["comment"])) {
$cerror = "";
}
else {
$comment = test_input($_POST["comment"]);
}}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p><span class="error">* required field </span></p>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nerror;?></span><br/><br/>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $merror;?></span><br/><br/>
Phone no: <input type="text" name="phone">
<span class="error">* <?php echo $perror;?></span><br/><br/>
Website: <input type="text" name="website">
<span class="error">* <?php echo $werror;?></span><br/><br/>
Comment: <textarea name="comment" rows="5"
cols="40"></textarea><br/><br/>
<input type="submit" name="submit" value="Submit"></form>
<?php
echo "<h2>Your Input:</h2>";
echo $name; echo "<br>";
echo $email; echo "<br>";
echo $phone; echo "<br>";
echo $website; echo "<br>";
echo $comment;
?>
</body>
</html>

Page 18 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

(Any other correct example can be consider and consider any


two user input validation)
5. Attempt any TWO of the following 12
a) Explain different loops in PHP with example. 6M
Ans. while loop: If the expression/condition specified with while 1M for
evaluates to true then the statements inside loop executes and explanatio
control is transferred back to expression/condition. The process of n and
evaluation and execution 1M for
Example: example
<?php of each
$a=1;
while($a<=5) Any three
{ can be
echo " Iteration $a"; considered
$a++;
}
?>

OR
Example:
<?php
$a=1;
while($a<=5):
echo " Iteration $a";
$a++;
endwhile;
?>

do-while loop:All the statements inside the loop executes for the
first time without checking any condition. The keyword „do‟ passes
the flow of control inside loop. After executing loop for the first
time, expression / condition is evaluated. If it evaluates to true then
all statements inside loop again executes and if it evaluates to false
then loop exits and flow of control passes to the next statement
placed outside the loop. The process of execution and evaluation
continues till expression / condition evaluates to true.
Example:
<?php
$a=1;

Page 19 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

do
{
print("Iteration 1");
$a++;
}while($a<=0);
?>

for loop:It is used to execute same set of statements multiple times.


In for loop variable initialization, condition and increment /
decrement is placed in a single statement. Before starting first
iteration a variable is initialized to specified value. Then condition
is checked. If condition is true then statements inside the loop
executes and variable is incremented or decremented. Control then
passes to condition. If condition is false then control passes to the
statement placed outside the loop. The process of condition
checking, loop statement execution and increment /decrement
continues till condition is true.
Example :
<?php
for ($a=1;$a<=5;$a++)
{
echo("Iteration $a");
}
?>

for each loop: This loop works with arrays and is used to traverse
through values in an array. For each loop iteration, the value of the
current array element is assigned to $value and the array pointer is
moved by one, until it reaches the last array element.
Example :
<?php
$arr=array("Apple","Banana","Orange");
foreach($arr as $fruit)
{
echo("$fruit");
}
?>
b) How do you connect MYSQL database with PHP. 6M
Ans. Using MySQLi Object Interface: 3M for

Page 20 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

<?php Any
$servername = "localhost"; relevant
$username = "root";
$password = "";
statement
$conn = new mysqli($servername, $username, $password); s for
if ($conn->connect_error) { connecti
die("Connection failed: " . $conn->connect_error); ng PHP
} with
echo "Connected successfully"; MySQL
mysqli_close($conn);
database
?>
Explanation:
The first part of the script is three variables (server name,
username, and password) and their respective values. These values 3M for
should correspond to your connection details. explanati
Next is the main PHP function mysqli_connect(). It establishes a
on
connection with the specified database.
When the connection fails, it gives the message Connection failed.
The die function prints the message and then exits out of the script

If the connection is successful, it displays “Connected


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

OR
using MySQLi Procedural interface:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {

Page 21 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

echo "Database created successfully";


} else {
echo "Error creating database: " ;
mysqli_error($conn);
}
mysqli_close($conn);
?>

Explanation:
The first part of the script is three variables (server name,
username, and password) and their respective values. These values
should correspond to your connection details.
Next is the main PHP function mysqli_connect(). It establishes a
connection with the specified database.
When the connection fails, it gives the message Connection failed.
The die function prints the message and then exits out of the script
If the connection is successful, it displays “Connected
successfully.”
Next, write a sql statement to create a database. If connection
established successfully then echo "Database created successfully";
else echo "Error creating database: "
When the script ends, the connection with the database also closes.
If you want to end the code manually, use
the mysqli_close function.

OR
using PDO - PHP Data Object
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try
{
$conn = new PDO("mysql:host=$servername;dbname=myDB",
$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}

Page 22 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Explanation:
The first part of the script is three variables (server name,
username, and password) and their respective values. These values
should correspond to your connection details.
If a problem arises while trying to connect, it stops running and
attempts to catch and solve the issue. Catch blocks can be set to
show error messages or run an alternative code.
Following is the setAttribute method adding two parameters to the
PDO:
1. PDO::ATTR_ERRMODE
2. PDO::ERRMODE_EXCEPTION
This method instructs the PDO to run an exception in case a query
fails.
Add the echo “Connected successfully.” to confirm a connection is
established.
Define the PDOException in the catch block by instructing it to
display a message when the connection fails.
c) Create a class as “Percentage” with two properties length & 6M
width. Calculate area of rectangle for two objects.
Ans <?php 3M for
class Percentage correct
{ syntax
public $length; 3M for
public $width; correct
public $a; logic
function area($l,$w)
{
$this->length=$l;
$this->width=$w;
$this->a=$this->length*$this->width;
echo "Area of rectangle = " . $this->a;
}
}
$p1=new Percentage();

Page 23 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

$p1->area(2,3);
$p2=new Percentage();
$p2->area(5,6);
?>
(Any other relevant logic can be considered)
6. Attempt any TWO of the following: 12
a) Write a PHP program to demonstrate use of cookies. 6M
Ans. Cookies can be used to identify user, managing session, etc. 6M for
Setting cookies for human identification: Any PHP
In the code below, two fields name and year are set as cookies on program
user's machine. From the two fields, name field can be used to
identify the user's revisit to the web site.
with
<?php correct
setcookie("name", "WBP", time()+3600, "/","", 0); demonstr
setcookie("Year", "3", time()+3600, "/", "", 0); ation for
?> use of
For the first time when user visits the web site, cookies are stored cookies
on user's machine. Next time when user visits the same page,
cookies from the user's machine are retrieved.
In the code below isset() function is used to check if a cookie is set
or not on the user's machine.
<html>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . " Thanks for
Revisiting"."<br />";
else
echo "First Time Visitor". "<br />";
?>
</body>
</html>
b) Explain any four string functions in PHP with example. 6M
Ans. 1. str_word_count() function: This function is used to count the
number of words in a string. 1M for
syntax : str_word_count(string,return,char); explanati
string : It indicates string to be checked.
return :It is optional. It specifies the return value of the
on &
function. 1/2 M for
correct
Page 24 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

0- default. Returns the number of words found. example


1- returns an array with the words from the string. of each
2- returns an array where the key is the position of
the word in the string, and value is the actual Any four
word. functions
char : Optional. It specifies special characters to be to be
considered as words. considered
Example:

<?php
$str1="Welcome to WBP Theory & practical";
echo " <br> Total words in string str1=
".str_word_count($str1,0,"&");
?>
2. strlen() function : This function is used to find number of
characters in a string . While counting number characters from
string, function also considers spaces between words.
syntax : strlen(string);
- string specify name of the string from which characters
have to be counted.
Example :
<?php
$str3="Hello,welcome to WBP";
echo "<br> Number of characters in a string '$str3' = "
.strlen($str3);
?>

3. strrev() function : This function accepts string as an argument


and returns a reversed copy of it.
Syntax : $strname=strrev($string variable/String );
Example :
<?php
$str4="Polytechnic";
$str5=strrev($str4);
echo "Orginal string is '$str4' and reverse of it is '$str5'";
?>

4. strcmp() function : This function is used to compare two strings

Page 25 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

with each other . It is a case sensitive comparison.


Syntax : $result= strcmp(string1,string2);
- string1 and string2 indicates strings to be compared with
each other.
-This function returns 0 if both the strings are equal. It
returns a value <0 if string1 is less than string2 and >0 if
string 1 is greater than string2
Example 1 :
<?php
$str6="Welcome";
$str7="Welcome";
echo strcmp($str7,$str6);
?>
5. strpos() function : This function is used to find the position of
the first occurrence of specified word inside another string. It
returns False if word is not present in string. It is a case sensitive
function. by default, search starts with 0th position in a string.
Syntax : strpos(String,findstring,start);
- string specify string to be searched to find another word
- findstring specify word to be searched in specified first
parameter.
- start is optional . It specifies where to start the search in a
string. If start is a negative number then it counts from the
end of the string.
Example:
<?php
$str8="Welcome to Polytechnic";
$result=strpos($str8,"Poly",0);
echo $result;
?>
6. str_replace() function : This function is used to replace some
characters with some other characters in a string.
Syntax : str_replace(findword,replace,string,count);
- Find word specify the value to find
- replace specify characters to be replaced with search
characters.
- string specify name of the string on which find and replace
has to be performed.

Page 26 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

- count is optional . It indicates number of occurrences


replaced from a string.

Example 1:
$str10="Welcome to poly";
$str11=str_replace("poly","msbte",$str10);
echo $str11;

7. ucwords() function: This function is used to convert first


character of each word from the string into uppercase.
Syntax : $variable=ucwords($Stringvar);
Example :
<?php
$str9="welcome to poly for web based development";
echo ucwords($str9);
?>

8. strtoupper() function :This function is used to convert any


character of string into uppercase.
Syntax : $variable=strtoupper($stringvar);
Example:
<?php
$str9="POLYtechniC";
echo strtoupper($str9);
?>

9. strtolower() function : This function is used to convert any


character of string into lowercase.
Syntax: $variable=strtolower($stringvar);
Example :
<?php
$str9="POLYtechniC";
echo strtolower($str9);
?>

c) i) What is inheritance? 6M
ii) Write update operation on table data.
Ans. Inheritance: It is the process of inheriting (sharing) properties 3M for
and methods of base class in its child class. Inheritance provides re- explanatio

Page 27 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

usability of code in a program. PHP uses extends keyword to n of


establish relationship between two classes. inheritance
Syntax : class derived_class_name extends base_class_name
{
Class body
}
- derived_class_name is the name of new class which is also
known as child class.
- 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.

Example :
<?php
class college
{
public $name="ABC College";
protected $code=7;
}
class student extends college 3M for
{ update
public $sname="s-xyz"; operation
public function display()
{
echo "College name=" .$this->name;
echo "<br>College code=" .$this->code;
echo "<br>Student name=" .$this->sname;
}
}
$s1=new student();
$s1->display();
?>

ii) Any correct statements for connecting database and

Page 28 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

updating data in database table


(Any data can be considered for updation)
Update data :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ifdept";
$conn = new mysqli($servername, $username, $password,
$dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE student SET rollno=4 WHERE
name='abc'";
if ($conn->query($sql) === TRUE)
{
echo "Record updated successfully";
} else
{
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>

Page 29 / 29

You might also like