Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
35 views26 pages

W-22 WBP - 22619 (2 Files Merged)

The document is a model answer for the Winter 2022 examination for the subject 'Web Based Application Development Using PHP' by the Maharashtra State Board of Technical Education. It provides important instructions for examiners on how to assess student answers, including guidelines on language errors, credit for understanding, and examples of PHP programming concepts. Additionally, it includes sample questions and answers related to PHP arrays, session management, and image processing functions.

Uploaded by

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

W-22 WBP - 22619 (2 Files Merged)

The document is a model answer for the Winter 2022 examination for the subject 'Web Based Application Development Using PHP' by the Maharashtra State Board of Technical Education. It provides important instructions for examiners on how to assess student answers, including guidelines on language errors, credit for understanding, and examples of PHP programming concepts. Additionally, it includes sample questions and answers related to PHP arrays, session management, and image processing functions.

Uploaded by

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

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

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

WINTER – 2022 EXAMINATION WINTER – 2022 EXAMINATION


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

Important Instructions to examiners: Example:


1) The answers should be examined by key words and not as word-to-word as given 1)Indexed array: Any one
in the model answer scheme. example 1M
$colors = array("Red", "Green", "Blue");
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.
2)Associative array:
3) The language errors such as grammatical, spelling errors should not be given more
Importance (Not applicable for subject English and Communication Skills.
$student_one = array("Maths"=>95, "Physics"=>90,
4) While assessing figures, examiner may give credit for principal components "Chemistry"=>96, "English"=>93,
indicated in the figure. The figures drawn by candidate and model answer may "Computer"=>98);
vary. The examiner may give credit for anyequivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the 3)Multidimensional array
assumed constant values may vary and there may be some difference in the $movies =array(
candidate’s answers and model answer. "comedy" =>array("Pink Panther", "John English", "See no evil hear
6) In case of some questions credit may be given by judgement on part of examiner no evil"),
of relevant answer based on candidate’s understanding. "action" =>array("Die Hard", "Expendables","Inception"),
7) For programming language papers, credit may be given to any other program "epic" =>array("The Lord of the rings")
based on equivalent concept. );
8) As per the policy decision of Maharashtra State Government, teaching in
c) State the role of constructor. 2M
English/Marathi and Bilingual (English + Marathi) medium is introduced at first year
of AICTE diploma Programme from academic year 2021-2022. Hence if the 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
students in first year (first and second semesters) write answers in Marathi or
bilingual language (English +Marathi), the Examiner shall consider the same and that class is declared. The main purpose of this method is to initialize
assess the answer based on matching of concepts with model answer. the object.
d) State the use of cookies. 2M
Q. Sub Answer Marking Ans. Cookie is used to keep track of information such as a username that Correct use
No Q.N. Scheme the site can retrieve to personalize the page when the user visits the 2M
1. Attempt any FIVE of the following: 10 website next time.
a) List any four data types of PHP. 2M e) List two database operations. 2M
Ans.  boolean Any four Ans. 1.mysqli_affected_rows() Any two
 integer types ½ M operations
each 2. mysqli_close() 1M each
 float
3. mysqli_connect()
 string
 array 4. mysqli_fetch_array()
 object 5.mysqli_fetch_assoc()
 resource 6.mysqli_affected_rows()
 NULL 7. mysqli_error()
b) Define Array. State its example. 2M
f) Write syntax of for each loop 2M
Ans. Definition:An array is a special variable, which can hold more than Definition
one value at a time. 1M Ans. foreach ($array as $value) { Correct
code to be executed; syntax 2M
}

Page 1 / 22 Page 2 / 22

www.diplomachak www.diplomachak
hazana.in hazana.in
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION WINTER – 2022 EXAMINATION


MODEL ANSWER MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619 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: if ($i == 5)continue;
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 echo " $i<br>";
}}
ii)Post method echo "end";
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 b) Explain Indexed array and associative arrays with suitable 4M
post method. examples.
2. Attempt any THREE of the following: 12 Ans.  In indexed arrays the value is accessed using indexes 0,1,2 etc.
a) Explain the use of break and continue statements. 4M  These types of arrays can be used to store any type of elements,
Ans. Break statement:-break keyword is used to terminate and transfer but an index is always a number. By default, the index starts at Explanation
the control to the next statement when encountered inside a loop or zero. These arrays can be created in two different ways as shown of each array
switch case statement. in the following with suitable
Syntax:  Array initialization example -2M
if (condition) Use and First method
{ break; } relevant $colors = array("Red", "Green", "Blue");
Example: example of
each - 2M
<?php Second method
$colors[0] = "Red";
for ($a = 0; $a < 10; $a++) $colors[1] = "Green";
{ $colors[2] = "Blue";
if ($a == 7)
{ Example:-initialize an array elements and display the same
break; /* Break the loop when condition is true. */ <?php
} $name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");
echo "Number: $a <br>"; // Accessing the elements directly
} echo "Accessing the 1st array elements directly:\n";
echo " Terminate the loop at $a number"; echo $name_one[2], "\n";
?> echo $name_one[0], "\n";
echo $name_one[4], "\n";
ii)Continue Statement ?>
It is used to skip the execution of a particular statement inside the
loops. ii)Associative array
if (condition) Associative arrays are used to store key value pairs.
{ continue; } Associative arrays have strings as keys and behave more liketwo-
Example: column tables. The first column is the key, which is used to access the
<?php value.
for ($i = 0; $i< 10; $i++)

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

WINTER – 2022 EXAMINATION WINTER – 2022 EXAMINATION


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

Here array() function is used to create associative array. public $roll;


<?php public function par_function()
/* First method to create an associate array. */ {}}
$student_one = array("Maths"=>95, "Physics"=>90, class childclass extends parentclass
"Chemistry"=>96, "English"=>93, {public $name;
"Computer"=>98); public function child_fun()
Second method to create an associate array. {}}
$student_two["Maths"] = 95; $obj=new childclass();
$student_two["Physics"] = 90; //class introspection
$student_two["Chemistry"] = 96; print_r("parent class exists:".class_exists('parentclass'));
$student_two["English"] = 93; echo"<br> child class methods: ";
$student_two["Computer"] = 98; print_r(get_class_methods('childclass'));
echo"<br> child class variables: ";
Example print_r(get_class_vars('childclass'));
<?php echo"<br> parent class variables: ";
$student_two["Maths"] = 95; print_r(get_class_vars('parentclass'));
$student_two["Physics"] = 90; echo"<br> parent class: ";
$student_two["Chemistry"] = 96; print_r(get_parent_class('childclass'));
$student_two["English"] = 93; //object introspection;
$student_two["Computer"] = 98; echo"<br> is object: ";
echo "Marks for student one is:\n"; print_r(is_object($obj));
echo "Maths:" . $student_two["Maths"], "\n"; echo"<br> object of a class: ";
echo "Physics:" . $student_two["Physics"], "\n"; print_r(get_class($obj));
echo "Chemistry:" . $student_two["Chemistry"], "\n"; echo"<br> object variables: ";
echo "English:" . $student_two["English"], "\n"; print_r(get_object_vars($obj));
echo "Computer:" . $student_two["Computer"], "\n"; echo"<br> methods exists: ";
?> print_r(method_exists($obj,'child_fun'));
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 d) 4M
1M
Describe
methods. With introspection, we can write code that operates on any i) Start session
class or object. We don't need to know which methods or properties ii) Get session variables
are defined when we write code; instead, we can discover that Ans. PHP session_start() function is used to start the session. It starts a
informationat runtime, which makes it possible for us to write generic new or resumes existing session. It returns existing session if session
debuggers, serializers, profilers, etc. is created already. If session is not available, it creates and returns Description
Example:- of Start
new session session 2M
<?php Any relevant Syntax 1.
class parentclass Program /
Example -
boolsession_start( void )
{ 3M

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

WINTER – 2022 EXAMINATION WINTER – 2022 EXAMINATION


MODEL ANSWER MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619 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 </body>
variables. It is used to set and get session variable values. </html>
Example: Store information 3. Attempt any THREE of the following: 12
2. $_SESSION["CLASS"] = "TYIF STUDENTS“ a) Explain two functions to scale the given image. 4M
Example: Program to set the session variable (demo_session1.php) Ans. imagecopyresized() function : It is an inbuilt function in PHP which
<?php is used to copy a rectangular portion of one image to another image
session_start(); and resize it. dst_image is the destination image, src_image is the Explanation
?> source image identifier. of two
functions -
<html> Syntax: 2M each
<body> imagecopyresized(dst_image, src_image, dst_x, dst_y,src_x, src_y,
<?php dst_w,dst_h,src_w, src_h)
$_SESSION["CLASS"] = "TYIF STUDDENTS"; dst_image: It specifies the destination image resource.
echo "Session information are set successfully.<br/>"; src_image: It specifies the source image resource.
?> dst_x: It specifies the x-coordinate of destination point.
</body> dst_y: It specifies the y-coordinate of destination point.
</html> src_x: It specifies the x-coordinate of source point.
src_y: It specifies the y-coordinate of source point.
ii)Get Session variables dst_w: It specifies the destination width.
We create another page called "demo_session2.php". From this page, dst_h: It specifies the destination height.
we will access the session information we set on the first page Description src_w: It specifies the source width.
("demo_session1.php"). of src_h: It specifies the source height.
Get session
2M Example:
Notice that session variables are not passed individually to each new imagecopyresized($d_image,$s_image,0,0,50,50,200,200,$s_width,
page, instead they are retrieved from the session we open at the $s_height);
beginning of each page (session_start()).
imagecopyresampled() function : It is used to copy a rectangular
Also notice that all session variable values are stored in the global portion of one image to another image, smoothly interpolating pixel
$_SESSION variable: values thatresize an image.
Syntax:
Example:- program to get the session variable imagecopyresampled(dst_image, src_image, dst_x, dst_y,src_x,
values(demo_session2.php) src_y, dst_w,dst_h,src_w, src_h)
<?php dst_image: It specifies the destination image resource.
session_start(); src_image: It specifies the source image resource.
?> dst_x: It specifies the x-coordinate of destination point.
<html> dst_y: It specifies the y-coordinate of destination point.
<body> ṇsrc_x: It specifies the x-coordinate of source point.
<?php src_y: It specifies the y-coordinate of source point.
echo "CLASS is: ".$_SESSION["CLASS"]; dst_w: It specifies the destination width.

Page 7 / 22 www.diplomachakhazana.in Page 8 / 22


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

WINTER – 2022 EXAMINATION WINTER – 2022 EXAMINATION


MODEL ANSWER MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619 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. ?>
$s1=new student( );
Example: c) State any four form controls to get user’s input in PHP. 4M
imagecopyresampled($d_image,$s_image,0,0,50,50,200,200,$s_widt Ans. 1. Textbox control:It is used to enter data. It is a single line input on a
h,$s_height); web page.
b) Write syntax to create class and object in PHP. 4M Tag :<input type=“text”> Any four
Ans. A class is defined by using the class keyword, followed by the name form controls
2. Password control:It is used to enter data that appears in the form of 1M each
of the class and a pair of curly braces ({}). All its properties and special characters on a web page inside box. Password box looks
Correct
methods go inside the curly brackets. syntax for like a text box on a wab page.
Syntax : creating Tag:<input type=“password”>
<?php class-2M, 3. Textarea : It is used to display a textbox that allow user to enter
class classname [extends baseclass][implements
Object-2M multiple lines of text.
interfacename,[interfacename,…]]
{ Tag :<textarea> … </textarea>
(Example is 4. Checkbox:It is used to display multiple options from which user
[visibility $property [=value];…] optional)
[functionfunctionname(args) { code }…] // method declaration & can select one or more options.
definition Tag: <input type=“checkbox”>
} 5. Radio / option button :These are used to display multiple options
?> from which user can select only one option.
In the above syntax, terms in squarebrackets are optional. Tag :<input type=“radio”>
6. Select element (list) / Combo box / list box:
Object : An object is an instance of class. The data associated with an <select> … </select> : This tag is used to create a drop-down list
object are called its properties. The functions associated with an box or scrolling list box from which user can select one or more
object are called its methods. Object of a class is created by using the options.
new keyword followed by classname. <option> … </option> tag is used to insert item in a list.
Syntax : $object = new Classname( ); d) Write steps to create database using PHP 4M
Example: Ans. Steps using PHP Code:Creating database: With CREATE Correct steps
<?php DATABASE query 4M
class student Step 1: Set variables with values for servername, username,
{ password.
public $name; Step 2: Set connection object by passing servername, username,
public $rollno; password as parameters.
Step 3: Set query object with the query as "CREATE DATABASE
function accept($name,$rollno) dept";
{ Step 4: Execute query with connection object.
$this->name=$name; Code (Optional)-
$this->rollno=$rollno; <?php

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

WINTER – 2022 EXAMINATION WINTER – 2022 EXAMINATION


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

$servername = "localhost";
$username = "root"; Step 5 : In the created Database, click on the 'Structure' tab. Towards
$password = ""; the end of the tables list, the user will see a 'Create Table' option.
$conn = new mysqli($servername, $username, $password); Give appropriate "Name" and "Number of Columns" for table and
if ($conn->connect_error) click on 'Go' button.
{
die("Connection failed: " . $conn->connect_error); 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
$sql = "CREATE DATABASE ifdept"; the input field. Click on "Save" in the bottom right corner. The table
if ($conn->query($sql) === TRUE) with the initialized columns will be created.
{
echo "Database created successfully"; 4. Attempt any THREE of the following: 12
} a) Define user defined function with example. 4M
else 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
echo "Error creating database: " . $conn->error; 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
$conn->close (); The function name can be any string that starts with a letter or
?> underscore followed by zero or more letters, underscores, and digits.

OR Syntax:
function function_name([parameters if any])
Steps using phpMyAdmin {
Step 1: Click on Start and select XAMPP from the list. Open Xampp Function body / statements to be executed
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. Example:
<?php
Step2: Click on the "Start" button corresponding function display() // declare and define a function
to Apache and MySQL modules. Once it starts working, the user can {
see the following screen: echo "Hello,Welcome to function";
Step 3: Now click on the "Admin" button corresponding to }
the MySQL module. This automatically redirects the user to a web display(); // function call
browser to the following address - http://localhost/phpmyadmin ?>

Step 4: Screen with multiple tabs such as Database, SQL, User When a function is defined in a script, to execute thefunction,
Accounts, Export, Import, Settings, etc. Will appear. Click on programmer have to call it with its name and parameters if required.
the "Database" tab. Give an appropriate name for the Database in the
first textbox and click on create option.

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

WINTER – 2022 EXAMINATION WINTER – 2022 EXAMINATION


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

b) Write a program for cloning of an object. 4M Step 2) If user required to add CSS in <head> section.
Ans. (Any other correct program shall be considered) <head>
Correct (any other
program 4M <style> relevant steps
<?php to design web
.error {color: #FF0000;}
class student page shall be
{ </style> considered)
function getdata($nm,$rn) </head>
{ Step 3) In <body> section design form with all mentioned
$this->name=$nm; components.
$this->rollno=$rn; Step 4) using <?php
} Write script for validation for all required input field.
function display()
Save the file with php extension to htdocs (C:/Program
{
echo "<br>name = ".$this->name; Files/XAMPP/htdocs)
echo "<Br>rollno = ".$this->rollno; 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’.
$s1 = new student(); Step 6)Now to run your code, open localhost/abc.php on any web
$s1->getdata("abc",1); browser then it gets executed.
$s1->display();
$s2 = clone $s1; d) Explain queries to update and delete data in the database. 4M
echo "<br> Cloned object data "; Ans. Update data : UPDATE query
$s2->display(); 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.
c) Write steps to create webpage using GUI components. 4M
The UPDATE query syntax:
Ans. Following are the GUI components to design web page:
 Button - has a textual label and is designed to invoke an action Correct UPDATE Table_name SET field_name=New_value WHERE
steps-4M field_name=existing_value
when pushed.
Example :
 Checkbox - has textual label that can be toggled on and off.
UPDATE student SET rollno=4 WHERE name='abc'
 Option - is a component that provides a pop-up menu of choices.
In the above query, a value from rollno field from student table is
 Label - is a component that displays a single line of read-only,
updated with new value as 4 if its name field contains name as ‘abc’.
non-selectable text.
 Scrollbar - is a slider to denote a position or a value.
Delete data: DELETE query
 TextField - is a component that implements a single line of text. Explanation
Delete command is used to delete rows that are no longer required of
 TextArea - is a component that implements multiple lines of text.
from the database tables. It deletes the whole row from the table. Delete query
To design web pages in PHP: The DELETE query syntax: 2M
Step 1) start with <html> DELETE FROM table_name WHERE some_column =
some_value

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

WINTER – 2022 EXAMINATION WINTER – 2022 EXAMINATION


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

[WHERE condition] is optional. The WHERE clause specifies which Ans. PHP Code-
record or records that should be deleted. If the WHERE clause is not <?php For loop
syntax 2M
used, all records will be deleted. echo "Output<br>";
Example :- for($i=1;$i<=10;$i++) Correct
$sql = "DELETE FROM student WHERE rollno=2"; { syntax 2M
echo "$i<br/>";
In the above query, a row from student table is deleted if rollno field } Correct logic
2M
contains 2 in that row. ?>
e) Describe the syntax of if-else control statement with example in 4M Output
(Output is
PHP. 1
optional)
Ans. if-else control statement is used to check whether the 2
Description
condition/expression is true or false. Ifthe expression / condition of if-else
3
evaluates to true then true block code associated with the if statement control 4
is executed otherwise if it evaluates to false then false block of code statement 5
associated with else is executed. 2M, 6
Syntax: 7
Syntax1M,
if (expression/condition) 8
{ Example1M 9
True code block; 10
} b) Write a program to connect PHP with MYSQL. 6M
else Ans. Solution1:
{ <?php
False code block; $servername = "localhost"; Correct
} $username = "root"; syntax 2M
$password = "";
Example: // Connection Correct code
<?php $conn = new mysqli($servername,$username, $password); 4M
$a=30; // For checking if connection issuccessful or not
if ($a<20) if ($conn->connect_error)
echo "variable value a is less than 20"; {
else die("Connection failed: ". $conn->connect_error);
echo "variable value a is greater than 20"; }
Writing
?> echo "Connected successfully"; Output is
In the above example, variable a holds value as 30. Condition checks ?> optional
whether the value of a is less than 20. It evaluates to false so the Output:
output displays the text as ‘variable value a is greater than 20’. Connected successfully
5. Attempt any TWO of the following: 12 OR
a) Write a PHP program to display numbers from 1-10 in a 6M
sequence using for loop.

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

WINTER – 2022 EXAMINATION WINTER – 2022 EXAMINATION


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

Solution2:
Create login.php Example:
<?php (Any type of inheritance example shall be considered)
$hostname = 'localhost'; <?php
$username = 'root'; class student {
$password = ''; var $var = "This is first var";
?> protected $fist_name;
protected $last_name;
Create db2.php file
<?php // simple class method
require_once 'login.php'; function returnVar() {
$conn = new mysqli($hostname, $username, $password); echo $this->fist_name;
//if ($conn->connect_error) die($conn->connect_error); }
if ($conn->connect_error) { function set_fist_name($fname,$lname){
die("Connection failed: " $this->fist_name = $fname;
. $conn->connect_error); $this->last_name = $lname;
} }
echo "Connected successfully"; }
?> class result extends student {
Output: public $percentage;
Connected successfully
function set_Percentage($p){
c) Illustrate class inheritance in PHP with example. 6M $this->percentage = $p;
Ans.  Inheritance is a mechanism of extending an existing class where }
a newly created or derived class have all functionalities of function getVal(){
Definition /
existing class along with its own properties and methods. Explanation
echo "Name:$this->fist_name $this->last_name";
 The parent class is also called a base class or super class. And the and echo "<br/>";
child class is also known as a derived class or a subclass. Types of echo "Result: $this->percentage %";
 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
$res1 = new result();
cost, effort, and increases a program’s reliability. Program / $res1->set_fist_name("Rita","Patel");
 To define a class inherits from another class, you use the extends example- 4M $res1->set_Percentage(95);
keyword. $res1->getVal();
 Types of Inheritance: ?>
Single Inheritance Output:
Multilevel Inheritance Name:Rita Patel
Multiple Inheritance Result: 95 %
Hierarchical Inheritance

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

WINTER – 2022 EXAMINATION WINTER – 2022 EXAMINATION


MODEL ANSWER MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619 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 </body>
Ans. PHP program to set cookies </html>
<html> Correct Code
to set cookie -
<body> 3M
Output:
<?php Cookie Value: xyz
$cookie_name = "username"; b) Write a PHP program to 6M
$cookie_value = "abc";
i) Calculate length of string
setcookie($cookie_name, $cookie_value, time() + Program to
(86400 * 30), "/"); // 86400 = 1 day ii) Count number of words in string calculate
length of
if(!isset($_COOKIE[$cookie_name])) { Correct Code Ans.
i) Calculate length of string string 3M
echo "Cookie name '" . $cookie_name . "' is not to modify
set!"; cookies- 3M <?php
} else { $str = 'Have a nice day ahead!';
echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Input String is:".$str;
echo "Value is: " . $_COOKIE[$cookie_name]; echo "<br>";
} echo "Length of String str:".strlen($str);
?> // output =12 [including whitespace]
</body> ?>
</html>
Output: ii) Count number of words in string Program to
Cookie 'username' is set! count
Solution1-
Value is: abc number of
<?php words in
// PHP program to count number of string 3M
PHP program to modify cookies
// words in a string
<?php
$str = " This is a string ";
setcookie("user", "xyz");
?>
// Using str_word_count() function to count number of words in a
<html>
string
<body>
$len = str_word_count($str);
<?php
if(!isset($_COOKIE["user"]))
// Printing the result
{
echo "Number of words in string : $len";
echo "Sorry, cookie is not found!";
?>
} else {
Output:
echo "<br/>Cookie Value: " .
Number of words in string : 4
$_COOKIE["user"];
}
OR

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

WINTER – 2022 EXAMINATION WINTER – 2022 EXAMINATION


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

print_r($us_data);
Solution 2: ?>
<?php
// PHP program to count number of Output:a:3:{i:0;s:7:"Welcome";i:1;s:2:"to";i:2;s:3:"PHP";} Correct
// words in a string Array ( [0] => Welcome [1] => to [2] => PHP ) example of
$string = " This is a string "; insert query-
$str = trim($string); 3M
while (substr_count($str, " ") > 0) { ii) Query to insert data in the database
$str = str_replace(" ", " ", $str); <?php
} require_once 'login.php';
$len = substr_count($str, " ")+1; $conn = newmysqli($hostname,$username, $password,$dbname);
// Printing the result $query = "INSERT INTO studentinfo(rollno,name,percentage)
echo "Number of words in string: $len"; VALUES
?> ('CO103','Yogita Khandagale',98.45)";
$result = $conn->query($query);
Output: if (!$result)
Number of words in string: 4 die ("Database access failed: " . $conn->error);
c) i) State the use of serialization. 6M else
ii) State the query to insert data in the database. echo "record inserted successfully";
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 Output:
calling the serialize () and unserialize( ) functions. record inserted successfully

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 Page 22 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

Important Instructions to examiners:  PHP is one of the most secure ways of developing websites and
1) The answers should be examined by key words and not as word-to-word as given in the dynamic web applications. PHP has multiple layers of security
model answer scheme. to prevent threats and malicious attacks.
2) The model answer and the answer written by candidate may vary but the examiner may try
b) What is array? How to store data in array? 2M
to assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Ans. 1. An array in PHP is an ordered map where a map is a type that
Importance (Not applicable for subject English and Communication Skills. associates values to keys.
4) While assessing figures, examiner may give credit for principal components indicated in the 1M for
figure. The figures drawn by candidate and model answer may vary. The examiner may give 2. Ways to store an array. definition
credit for anyequivalent figure drawn. Using array variable 1M to store
5) Credits may be given step wise for numerical problems. In some cases, the assumed <?php data
constant values may vary and there may be some difference in the candidate’s answers and $array_fruits= array('Apple', 'Orange', 'Watermelon', 'Mango');
model answer. ?>
6) In case of some questions credit may be given by judgement on part of examiner of relevant OR
answer based on candidate’s understanding. Using array indices
7) For programming language papers, credit may be given to any other program based on <?php
equivalent concept.
$array= [];// initializing an array
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
$array[] = 'Apple';
Programme from academic year 2021-2022. Hence if the students in first year (first and $array[] = 'Orange';
second semesters) write answers in Marathi or bilingual language (English +Marathi), the $array[] = 'Watermelon;
Examiner shall consider the same and assess the answer based on matching of concepts $array[] = „Mango;
with model answer. print_r($array);
?>
Q.No Sub Answer Marking
Q.N. Scheme c) List types of inheritance. 2M
1. Attempt any FIVE of the following: 10 Ans. 1. Single Level Inheritance 2M for any
a) Describe advantages of PHP. 2M 2. Multiple Inheritance four
Ans.  Easy to Learn ½ M each, 3. Multiple Inheritance (Interfaces) correct
 Familiarity with Syntax any four 4. Hierarchical Inheritance names of
 PHP is an open-source web development language, it‟s advantages inheritance
completely free of cost.
 PHP is one of the best user-friendly programming languages in d) How can we destroy cookies? 2M
the industry. Ans. We can destroy the cookie just by updating the expire-time value 1M for
 PHP supports all of the leading databases, including MySQL, of the cookie by setting it to a past time using the explanatio
ODBC, SQLite and more setcookie() function. n
 effective and efficient programming language 1M for
 Platform Independent Syntax: setcookie(name, time() - 3600); syntax/
 PHP uses its own memory space, so the workload of the server example
and loading time will reduce automatically, which results into e) List any four data types in MYSQL 2M
the faster processing speed.

www.diplomachakhazana.in Page 1 / 29 Page 2 / 29


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

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

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


Data Type Size Description session_start();
$_SESSION["username"] = "abc";
CHAR(size) Maximum 255 characters Fixed-length 2M for ?>
Character strings. any four 2. Attempt any THREE of the following: 12
VARCHAR Maximum 255 characters Variable length correct a) Write down rules for declaring PHP variable 4M
(size) string types Ans. a. A variable starts with the $ sign, followed by the name of the 1M for
TEXT(size) Maximum size of 65,535 Here size is the variable. each
characters. number of b. A variable name must start with a letter or the underscore correct
characters to character. rule, any
store. c. A variable name should not contain spaces. If a variable name is four rules
INT(m)/ Signed values range from - Standard integer more than one word, it should be separated with an underscore can be
INTEGER( 2147483648 to value. ($first_name), or with capitalisation ($firstName). considered
m) 2147483647. Unsigned d. Variables used before they are assigned have default values.
values range from 0 to e. A variable name cannot start with a number.
4294967295. (4 bytes) f. A variable name can only contain alpha-numeric characters (A-
DATE() (3 bytes) Displayed as Displayed as Z, a-z) and underscores.
'yyyy-mm-dd'. 'yyyy-mm-dd' g. Variable names are case-sensitive ($name and $NAME are two
DATETIM Values range from '1000- (8 bytes) different variables)
E() 01-01 00:00:00' to '9999- Displayed as h. Variables can, but do not need, to be declared before
12-31 23:59:59'. 'yyyy-mm- assignment. PHP automatically converts the variable to the
ddhh:mm:ss'. correct data type, depending on its value.
f) Write syntax of PHP. 2M i. Variables in PHP do not have intrinsic types - a variable does
Ans. A PHP script starts with the tag <?php and end with tag ?>. 2M for not know in advance whether it will be used to store a number
The PHP delimiter in the following example simply tells the PHP correct or a string of characters
engine to treat the enclosed code block as PHP code, rather than syntax b) Write a program to create associative array in PHP. 4M
simple HTML Ans. <?php 4M for any
Syntax: $a = array("sub1"=>23,"sub2"=>23,"sub3"=>12,"sub4"=>13); correct
<?php var_dump($a); code for
echo „Hello World‟; echo "<br>"; associative
?> foreach ($a as $x) array
g) How to create session variable in PHP? 2M echo "$x<br>";
Ans.  Session variable can be set with a help of a PHP global variable: 1M for echo "using for loop<br>";
$_SESSION. explanatio $aLength= count($a);
 Data in the session is stored in the form of keys and values pair. n echo "Count of elements=$aLength<br>";
 We can store any type of data on the server, which include 1M for for ($i=0;$i<$aLength;$i++)
arrays and objects. correct echo "$a[$i]<br>";
 For example, we want to store username in the session so it can syntax / echo "array function extract<br>";
be assessed whenever it is required throughout the session. example extract($a);

www.diplomachakhazana.in Page 3 / 29 Page 4 / 29


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

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

echo $a1."<br>".$a2."<br>".$a3."<br>".$a4."<br>"; {
?> return(true);
c) Define Introspection and explain it with suitable example. 4M }
Ans.  Introspection in PHP offers the useful ability to examine an 1M for //Class "Test" exist or not
object's characteristics, such as its name, parent class (if any) definition if (class_exists('Test'))
properties, classes, interfaces and methods. 1M for {
 PHP offers a large number functions that can be used to explanatio $t = new Test();
accomplish the above task. n echo "The class is exist. <br>";
 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 else
example {
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
Example: List of Methods:
<?php testing_one
class Test testing_two
{ testing_three
function testing_one() d) Write difference between get() and post() method of form (Any 4M
{ four points)
return(true); Ans. HTTP GET HTTP POST 1M for
} In GET method we cannot send In POST method large each
function testing_two() large amount of data rather amount of data can be correct
{ limited data is sent because the sent because the request differentiat
return(true); request parameter is appended parameter is appended ion, any
} into the URL. into the body. four points
function testing_three()

Page 5 / 29 Page 6 / 29

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

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


MODEL ANSWER MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619 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 Example
more than the Post request. than Get so it is used less <?php
than the Get request. function writeMsg() {
GET request is comparatively POST request is echo "Welcome to PHP world!";
less secure because the data is comparatively more }
exposed in the URL bar. secure because the data is writeMsg(); // call the function
not exposed in the URL ?>
bar. (Any other example can be considered)
Request made through GET Request made through b) Explain method overloading with example. 4M
method are stored in Browser POST method is not Ans. Function overloading or method overloading is the ability to create 2M for
history. stored in Browser history. multiple functions of the same name with different implementations explanatio
GET method request can be POST method request depending on the type of their arguments. n
saved as bookmark in browser. cannot be saved as In PHP overloading means the behavior of a method changes 2M for
bookmark in browser. dynamically according to the input parameter. example
Request made through GET Request made through __call() is triggered when invoking inaccessible methods in an
method are stored in cache POST method are not object context.
memory of Browser. stored in cache memory __callStatic() is triggered when invoking inaccessible methods in a
of Browser. static context.
Data passed through GET Data passed through
method can be easily stolen by POST method cannot be __call():
attackers. easily stolen by attackers. If a class execute __call(), then if an object of that class is called
In GET method only ASCII In POST method all types with a method that doesn't exist then__call() is called instead of that
characters are allowed. of data is allowed. method.
3. Attempt any THREE of the following: 12
a) Define function. How to define user defined function in PHP? 4M example:-
Give example. 1M for <?php
Ans. Definition: -A function is a block of code written in a program to definition // PHP program to explain function
perform some specific task. // overloading in PHP
They take information as parameters, execute a block of statements 1M for // Creating a class of type shape
or perform operations on these parameters and return the result. A syntax class shape {
function will be executed by a call to the function. 2M for // __call is magic function which accepts
any // function name and arguments
Define User Defined Function in PHP: A user-defined function relevant
declaration starts with the keyword function. example function __call($name_of_function, $arguments) {
// It will match the function name
Syntax if($name_of_function == 'area') {
function functionName() { switch (count($arguments)) {
code to be executed; // If there is only one argument

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

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

// area of circle
case 1: Cookie
return 3.14 * $arguments[0]; 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
// IF two arguments then area is rectangle; (until the expiration date has passed).There is no Unique ID
case 2: allocated for a Cookie. The cookie data can be accessed using the
return $arguments[0]*$arguments[1]; $_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
// Declaring a shape type object the session is created already. If a session is not available, it creates
$s = new Shape; and returns a new session.
session_start() creates a session or resumes the current one based
// Function call on a session identifier passed via a GET or POST request, or passed
echo($s->area(2)); via a cookie.
echo "<br>";
Example optional:-
// calling area method for rectangle <?php
echo ($s->area(4, 2)); session_start();
?> ?>
Output: <html>
9.426 <body>
48 <?php
$_SESSION["uname"]="Customer1";
Here the area() method is created dynamically and executed with $_SESSION["fcolor"]="RED";
the help of magic method __call() and its behavior changes echo "The session variable are set with values";
according to the pass of parameters as object. ?>
(Any other example can be considered) </body>
c) Define session and cookie. Explain use of session start. 4M </html>
Ans. Session 1M for d) Explain delete operation of PHP on table data. 4M
Session is a way to store information to be used across multiple each Ans. Delete command is used to delete rows that are no longer required 2M for
pages, and session stores the variables until the browser is closed. definition from the database tables. It deletes the whole row from the table. explanatio
To start a session, the session_start() function is used and to destroy 2M for use n
a session, the session_unset() and the session_destroy() functions of session The DELETE statement is used to delete records from a table: 2M for
are used. start DELETE FROM table_name WHERE some_column = program /
The session variables of a session can be accessed by using the some_value Example
$_SESSION super-global variable.

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

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

[WHERE condition] is optional. The WHERE clause specifies Table after Deletion
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 (Any other example can be considered)
match a record in student.pridata table.
Example:- 4. Attempt any THREE of the following: 12
Assume Following Table a) Write PHP script to sort any five numbers using array 4M
Database Name-student function. 4M for
Table name - pridata Ans. <?php correct and
$a = array(1, 8, 9, 4, 5); equivalent
sort($a); code
foreach($a as $i) {
echo $i.' ';
}
?>
<?php
$server='localhost'; OR
$username='root';
$password=''; <!DOCTYPE html>
$con=mysqli_connect($server,$username,$password); <html>
if(!$con){ <body>
die("Connection to this database failed due to" <H1>Enter five numbers </H1>
.mysqli_connect_error($mysqli)); <form action = 'sort.php' method = 'post'>
} <input type = 'number' name = 'n1' placeholder = 'Number
$sql="DELETE FROM student.pridataWHERE name='amit'"; 1...'><br><br>
if($con->query($sql)==true){ <input type = 'number' name = 'n2' placeholder = 'Number
echo "Record deleted successfully"; 2...'><br><br>
} <input type = 'number' name = 'n3' placeholder = 'Number
else{ 3...'><br><br>
"ERROR:error".$con->error(); <input type = 'number' name = 'n4' placeholder = 'Number
} 4...'><br><br>
$con->close(); <input type = 'number' name = 'n5' placeholder = 'Number
?> 5...'><br><br>
<input type = 'submit' value = 'Submit'>
Output:- </form>
</body>
</html>

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

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

sort.php Explanation
<?php The above code creates a car with a constructor which initializes its
if($_SERVER['REQUEST_METHOD'] == 'POST') { member variable named color and price.
$a = array($_POST['n1'], $_POST['n2'], $_POST['n3'], An object of the variable is created, and it is cloned to demonstrate
$_POST['n4'], $_POST['n5']); deep cloning.
sort($a);
c) Create customer form like customer name, address, mobile no, 4M
}
date of birth using different form of input elements & display
foreach($a as $i) {
user inserted values in new PHP form.
echo $i.' ';
Ans. <!DOCTYPE html>
}
<html> 4M for
?>
<body> correct and
(Any other example can be considered)
<form action = 'data..php' method = 'post'> equivalent
b) Write PHP program for cloning of an object 4M <input type = 'text' name = 'name' placeholder = 'Customer code
Ans. (Any other correct program can be considered) 4M for Name...'><br><br>
Code:- correct <input type = 'text' name = 'address' placeholder =
<!DOCTYPE html> program 'Address...'><br><br>
<html>
<input type = 'text' name = 'number' placeholder = 'Mobile
<body>
Number...'><br><br>
<label> Date of Birth: </label>
<?php
<input type = 'date' name = 'dob'><br><br>
class car {
<input type = 'submit' value = 'Submit'><br>
public $color;
</form>
public $price;
</body>
function __construct()
</html>
{
$this->color = 'red';
data.php
$this->price = 200000;
<?php
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
}
echo '<html><body><form>
$mycar = new car();
Customer Name: '.$_POST['name'].'<br>
$mycar->color = 'blue';
Address: '.$_POST['address'].'<br>
$mycar->price = 500000;
Mobile Number: '.$_POST['number'].'<br>
$newcar = clone $mycar;
Date of Birth: '.$_POST['dob'];
print_r($newcar);
}
?>
?>
</body>
(Any other correct program logic can be considered)
</html>
d) Inserting and retrieving the query result operations 4M
Ans. <?php 2M for
$con = mysqli_connect('localhost', 'root', '', 'class'); inserting

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

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

# Connecting to Database 2M for There are two types of validation available in PHP.
$query = "insert into user values(1, 'Amit')"; retrieving Client-Side Validation − Validation is performed on the client
# Inserting Values the query machine web browsers.
$result = mysqli_query($con, $query); result Server Side Validation − After submitted by data, The data is sent
if($result) { operations to a server and performs validation checks in the server machine.
echo 'Insertion Successful <br>';
} Some of Validation rules for field
else { Field Validation Rules
echo 'Insertion Unsuccessful <br>'; Name Should required letters and white-spaces
} Email Should be required @ and .
Website Should required a valid URL
$query = "select * from user"; Radio Must be selectable at least once
# Retrieving Values Check Box Must be checkable at least once
$result = mysqli_query($con, $query); Drop Down menu Must be selectable at least once

foreach($result as $r) { The preg_match() function searches a string for pattern, returning
echo $r['roll_number'].' '.$r['name']; true if the pattern exists, and false otherwise.
}
?> To check whether an email address is well-formed is to use PHP's
Output filter_var() function.
Insertion Successful
1 Amit empty() function will ensure that text field is not blank it is with
Explanation some data, function accepts a variable as an argument and returns
The above code connects with a database named „class‟‟. TRUE when the text field is submitted with empty string, zero,
The exam database has a table named „user‟ with 2 columns NULL or FALSE value.
roll_number and name.
Is_numeric() function will ensure that data entered in a text field is
It executes an insert query on the user and checks whether the
insertion was successful or not. a numeric value, the function accepts a variable as an argument and
It executes a select query on the user and displays the information returns TRUE when the text field is submitted with numeric value.
retrieved.
(Any other example can be considered) Example:-
Validations for: - name, email, phone no, website url
e) How do you validate user inputs in PHP. 4M <!DOCTYPE html>
Ans. Invalid user input can make errors in processing. Therefore, 2M for <body>
validating inputs is a must. explanatio <?php
1. Required field will check whether the field is filled or not in the n $nerror = $merror = $perror = $werror = $cerror = "";
proper way. Most of cases we will use the * symbol for required 2M for $name = $email = $phone = $website = $comment = "";
field. program $pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)* @[a-z0-9-]+(\.[a-z0-9-
2. Validation means check the input submitted by the user. ]+)*(\.[a-z]{2,3})$^";

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

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

if($_SERVER["REQUEST_METHOD"]=="POST") { }
if(empty($_POST["name"])) { if (empty($_POST["comment"])) {
$nerror = "Name cannot be empty!"; $cerror = "";
} }
else { else {
$name = test_input($_POST["name"]); $comment = test_input($_POST["comment"]);
if(!preg_match("/^[a-zA-Z-']*$/",$name)) }}
{ function test_input($data)
$nerror = "Only characters and white spaces allowed"; {
} $data = trim($data);
} $data = stripslashes($data);
if(empty($_POST["email"])) { $data = htmlspecialchars($data);
$merror = "Email cannot be empty!"; return $data;
} }
else ?>
{ <p><span class="error">* required field </span></p>
$email = test_input($_POST["email"]); <form method="post" action="<?php echo
if(!preg_match($pattern, $email)) { htmlspecialchars($_SERVER["PHP_SELF"]);?>">
$merror = "Email is not valid"; Name: <input type="text" name="name">
} <span class="error">* <?php echo $nerror;?></span><br/><br/>
} E-mail: <input type="text" name="email">
if(empty($_POST["phone"])) { <span class="error">* <?php echo $merror;?></span><br/><br/>
$perror = "Phone no cannot be empty!"; Phone no: <input type="text" name="phone">
} <span class="error">* <?php echo $perror;?></span><br/><br/>
else { Website: <input type="text" name="website">
$phone = test_input($_POST["phone"]); <span class="error">* <?php echo $werror;?></span><br/><br/>
if (!preg_match ('/^[0-9]{10}+$/', $phone)) { Comment: <textarea name="comment" rows="5"
$perror = "Phn no is not valid"; cols="40"></textarea><br/><br/>
} <input type="submit" name="submit" value="Submit"></form>
} <?php
if(empty($_POST["website"])) { echo "<h2>Your Input:</h2>";
$werror = "This field cannot be empty!"; echo $name; echo "<br>";
} echo $email; echo "<br>";
else { echo $phone; echo "<br>";
$website = test_input($_POST["website"]); echo $website; echo "<br>";
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0- echo $comment;
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { ?>
$werror = "URL is not valid"; </body>
} </html>

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

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

(Any other correct example can be consider and consider any do


two user input validation) {
5. Attempt any TWO of the following 12 print("Iteration 1");
a) Explain different loops in PHP with example. 6M $a++;
Ans. while loop: If the expression/condition specified with while 1M for }while($a<=0);
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 for loop:It is used to execute same set of statements multiple times.
Example: example In for loop variable initialization, condition and increment /
<?php of each decrement is placed in a single statement. Before starting first
$a=1; iteration a variable is initialized to specified value. Then condition
while($a<=5) Any three is checked. If condition is true then statements inside the loop
{ can be executes and variable is incremented or decremented. Control then
echo " Iteration $a"; considered passes to condition. If condition is false then control passes to the
$a++; statement placed outside the loop. The process of condition
} checking, loop statement execution and increment /decrement
?> continues till condition is true.
Example :
OR <?php
Example: for ($a=1;$a<=5;$a++)
<?php {
$a=1; echo("Iteration $a");
while($a<=5): }
echo " Iteration $a"; ?>
$a++;
endwhile; 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
do-while loop:All the statements inside the loop executes for the moved by one, until it reaches the last array element.
first time without checking any condition. The keyword „do‟ passes Example :
the flow of control inside loop. After executing loop for the first <?php
time, expression / condition is evaluated. If it evaluates to true then $arr=array("Apple","Banana","Orange");
all statements inside loop again executes and if it evaluates to false foreach($arr as $fruit)
then loop exits and flow of control passes to the next statement {
placed outside the loop. The process of execution and evaluation echo("$fruit");
continues till expression / condition evaluates to true. }
Example: ?>
<?php b) How do you connect MYSQL database with PHP. 6M
$a=1; Ans. Using MySQLi Object Interface: 3M for

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

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

<?php Any echo "Database created successfully";


$servername = "localhost"; relevant } else {
$username = "root"; echo "Error creating database: " ;
$password = "";
statement mysqli_error($conn);
$conn = new mysqli($servername, $username, $password); s for }
if ($conn->connect_error) { connecti mysqli_close($conn);
die("Connection failed: " . $conn->connect_error); ng PHP ?>
} with
echo "Connected successfully"; MySQL Explanation:
mysqli_close($conn); The first part of the script is three variables (server name,
database username, and password) and their respective values. These values
?> should correspond to your connection details.
Explanation: Next is the main PHP function mysqli_connect(). It establishes a
The first part of the script is three variables (server name, connection with the specified database.
username, and password) and their respective values. These values 3M for When the connection fails, it gives the message Connection failed.
should correspond to your connection details. explanati The die function prints the message and then exits out of the script
If the connection is successful, it displays “Connected
Next is the main PHP function mysqli_connect(). It establishes a
on successfully.”
connection with the specified database. Next, write a sql statement to create a database. If connection
When the connection fails, it gives the message Connection failed. established successfully then echo "Database created successfully";
The die function prints the message and then exits out of the script else echo "Error creating database: "
When the script ends, the connection with the database also closes.
If the connection is successful, it displays “Connected If you want to end the code manually, use
successfully.” When the script ends, the connection with the the mysqli_close function.
database also closes. If you want to end the code manually, use
the mysqli_close function. OR
using PDO - PHP Data Object
OR <?php
using MySQLi Procedural interface: $servername = "localhost";
<?php $username = "username";
$servername = "localhost"; $password = "password";
$username = "username"; try
$password = "password"; {
$conn = mysqli_connect($servername, $username, $password); $conn = new PDO("mysql:host=$servername;dbname=myDB",
if (!$conn) { $username, $password);
die("Connection failed: " . mysqli_connect_error()); $conn->setAttribute(PDO::ATTR_ERRMODE,
} PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDB"; echo "Connected successfully";
if (mysqli_query($conn, $sql)) { }

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

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

catch(PDOException $e) $p1->area(2,3);


{ $p2=new Percentage();
echo "Connection failed: " . $e->getMessage(); $p2->area(5,6);
} ?>
?> (Any other relevant logic can be considered)
Explanation: 6. Attempt any TWO of the following: 12
The first part of the script is three variables (server name, a) Write a PHP program to demonstrate use of cookies. 6M
username, and password) and their respective values. These values Ans. Cookies can be used to identify user, managing session, etc. 6M for
should correspond to your connection details. Setting cookies for human identification: Any PHP
If a problem arises while trying to connect, it stops running and In the code below, two fields name and year are set as cookies on program
attempts to catch and solve the issue. Catch blocks can be set to user's machine. From the two fields, name field can be used to
show error messages or run an alternative code. identify the user's revisit to the web site.
with
Following is the setAttribute method adding two parameters to the <?php correct
PDO: setcookie("name", "WBP", time()+3600, "/","", 0); demonstr
1. PDO::ATTR_ERRMODE setcookie("Year", "3", time()+3600, "/", "", 0); ation for
2. PDO::ERRMODE_EXCEPTION ?> use of
This method instructs the PDO to run an exception in case a query For the first time when user visits the web site, cookies are stored cookies
fails. on user's machine. Next time when user visits the same page,
Add the echo “Connected successfully.” to confirm a connection is cookies from the user's machine are retrieved.
established. In the code below isset() function is used to check if a cookie is set
Define the PDOException in the catch block by instructing it to or not on the user's machine.
display a message when the connection fails. <html>
c) Create a class as “Percentage” with two properties length & 6M <body>
width. Calculate area of rectangle for two objects. <?php
Ans <?php 3M for if( isset($_COOKIE["name"]))
class Percentage correct echo "Welcome " . $_COOKIE["name"] . " Thanks for
{ syntax Revisiting"."<br />";
public $length; 3M for else
public $width; correct echo "First Time Visitor". "<br />";
public $a; logic ?>
function area($l,$w) </body>
{ </html>
$this->length=$l; b) Explain any four string functions in PHP with example. 6M
$this->width=$w; Ans. 1. str_word_count() function: This function is used to count the
$this->a=$this->length*$this->width; number of words in a string. 1M for
echo "Area of rectangle = " . $this->a; 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 &
$p1=new Percentage(); function. 1/2 M for
correct
Page 23 / 29 Page 24 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

0- default. Returns the number of words found. example with each other . It is a case sensitive comparison.
1- returns an array with the words from the string. of each Syntax : $result= strcmp(string1,string2);
2- returns an array where the key is the position of - string1 and string2 indicates strings to be compared with
the word in the string, and value is the actual Any four each other.
word. functions -This function returns 0 if both the strings are equal. It
char : Optional. It specifies special characters to be to be returns a value <0 if string1 is less than string2 and >0 if
considered as words. considered string 1 is greater than string2
Example: Example 1 :
<?php
<?php $str6="Welcome";
$str1="Welcome to WBP Theory & practical"; $str7="Welcome";
echo " <br> Total words in string str1= echo strcmp($str7,$str6);
".str_word_count($str1,0,"&"); ?>
?> 5. strpos() function : This function is used to find the position of
2. strlen() function : This function is used to find number of the first occurrence of specified word inside another string. It
characters in a string . While counting number characters from returns False if word is not present in string. It is a case sensitive
string, function also considers spaces between words. function. by default, search starts with 0th position in a string.
syntax : strlen(string); Syntax : strpos(String,findstring,start);
- string specify name of the string from which characters - string specify string to be searched to find another word
have to be counted. - findstring specify word to be searched in specified first
Example : parameter.
<?php - start is optional . It specifies where to start the search in a
$str3="Hello,welcome to WBP"; string. If start is a negative number then it counts from the
echo "<br> Number of characters in a string '$str3' = " end of the string.
.strlen($str3); Example:
?> <?php
$str8="Welcome to Polytechnic";
$result=strpos($str8,"Poly",0);
3. strrev() function : This function accepts string as an argument echo $result;
and returns a reversed copy of it. ?>
Syntax : $strname=strrev($string variable/String ); 6. str_replace() function : This function is used to replace some
Example : characters with some other characters in a string.
<?php Syntax : str_replace(findword,replace,string,count);
$str4="Polytechnic"; - Find word specify the value to find
$str5=strrev($str4); - replace specify characters to be replaced with search
echo "Orginal string is '$str4' and reverse of it is '$str5'"; characters.
?> - string specify name of the string on which find and replace
has to be performed.
4. strcmp() function : This function is used to compare two strings

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

SUMMER – 2022 EXAMINATION SUMMER – 2022 EXAMINATION


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

- count is optional . It indicates number of occurrences usability of code in a program. PHP uses extends keyword to n of
replaced from a string. establish relationship between two classes. inheritance
Syntax : class derived_class_name extends base_class_name
Example 1: {
$str10="Welcome to poly"; Class body
$str11=str_replace("poly","msbte",$str10); }
echo $str11; - derived_class_name is the name of new class which is also
known as child class.
7. ucwords() function: This function is used to convert first - base_class_name is the name of existing class which is
character of each word from the string into uppercase. also known as parent class.
Syntax : $variable=ucwords($Stringvar);
Example : A derived class can access properties of base class and also can
<?php have its own properties. Properties defined as public in base class
$str9="welcome to poly for web based development"; can be accessed inside as well as outside of the class but properties
echo ucwords($str9); defined as protected in base class can be accessed only inside its
?> derived class. Private members of class cannot be inherited.

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


character of string into uppercase. <?php
Syntax : $variable=strtoupper($stringvar); class college
Example: {
<?php public $name="ABC College";
$str9="POLYtechniC"; protected $code=7;
echo strtoupper($str9); }
?> class student extends college 3M for
{ update
9. strtolower() function : This function is used to convert any public $sname="s-xyz"; operation
character of string into lowercase. public function display()
Syntax: $variable=strtolower($stringvar); {
Example : echo "College name=" .$this->name;
<?php echo "<br>College code=" .$this->code;
$str9="POLYtechniC"; echo "<br>Student name=" .$this->sname;
echo strtolower($str9); }
?> }
$s1=new student();
c) i) What is inheritance? 6M $s1->display();
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 ii) Any correct statements for connecting database and

Page 27 / 29 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