PHP w24 Merged
PHP w24 Merged
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
WINTER – 2024 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Web Based Application development with PHP (WBP) Subject Code: 22619
Important Instructions to examiners:
222261
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
9
XXXXX
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model
answer.
4)Database support
5)Security
6)Scripting Language
7)Vast Community
Ans Inheritance is a mechanism of extending an existing class by inheriting a class. Correct definition 2 M
We create a new sub class with all functionality of that existing class, and we
Page No: 1 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
can add new members to the new sub class.
When we inherit one class from another we say that inherited class is a
subclass and the class who has inherits is called parent class.
In order to declare that one class inherits the code from another class, we use
the extends keyword.
strops(): Returns the position of the first occurrence of a string inside another
string (case-sensitive)
Trim(): Removes white spaces and predefined characters from a both the sides
of a string.
Ans i) Integer: This data type holds only numeric values. Integers hold only whole Any two data types, 1 M
numbers including positive and negative numbers, i.e., numbers without for each
fractional part or decimal point. The range of integer values are -
Page No: 2 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
2,147,483,648 to +2,147,483,647. Integers can be defined indecimal(base 10),
hexadecimal(base 16), octal(base 8) or binary(base 2) notation.The default
base is decimal (base 10).
(ii) Float: Floating point numbers represents numeric values with decimal
points (real numbers) or a number in exponential form. The range of floating
point values are 1.7E-308 to 1.7E+308. Example: 3.14, 0.25, -5.5, 2E-4, 1.2e2
(iv) Boolean: The Boolean data types represents two values, true(1) or
false(0). Example: $a=True
v)Array: An array stores multiple values in one single variable and each value
is identify by position ( zero is the first position). The array is a collection of
heterogeneous (dissimilar) data types. PHP is a loosely typed language that’s
why we can store any type of values in arrays.
(vi) Object :
Objects are defined as instances of user defined classes that can hold both
values and functions. First we declare class of object using keyword class. A
class is a structure that contain properties (variables) and methods (functions).
(vii) Resource: The special resource type is not an actual data type. It is the
storing of a reference to functions and resources external to PHP. Consider a
function which connect to the database, a function to send a query to the
database, a function to close the connection of database. Resource variables
hold special handles to opened files, database connections, streams etc.
(viii) Null: Null is a special data type which can have only one value NULL
i.e. a variable that has no value assigned to it. If a variable is created without a
value, it is automatically assigned a value of NULL.
Page No: 3 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
an array, i.e., exchange all keys with their associated values in an array and
vice-versa.
Syntax: array_flip(array);
explode():
- The explode() function splits a string based on a string delimeter, i.e. it splits
the string wherever the delimeter character occurs. This function returns an
array containing the strings formed by splitting the original string.
Syntax:
Ans - A class is a unit of code that describes the characteristics and behaviors of Define:1 M, Syntax: ½ M
something, or of a group of things. and any correct Example:
½M
- Class is a collection of objects. Object has properties and behavior.
Syntax :
<? Php
classname_of_class
} ?>
Example:
<?php
class Car
Page No: 4 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
{
?>
Ans 1. The most important advantage of PHP is that it’s open-source and free Any two advantages: 1
from cost. It can be downloaded anywhere and is readily available to M, ½ M for each
use for events or web applications.
2. It is platform-independent. PHP-based applications can run on any OS
like UNIX, Linux, Windows, etc.
3. Applications can easily be loaded which are based on PHP and
connected to the database. It’s mainly used due to its faster rate of
loading over slow internet speed than other programming language.
4. It has less learning curve because it is simple and straightforward to
use. Someone familiar with C programming can easily work on PHP.
5. It is more stable for a few years with the assistance of providing
continuous support to various versions.
6. It helps in reusing an equivalent code and not got have to write lengthy
code and sophisticated structure for events of web applications.
7. It helps in managing code easily.
8. It has powerful library support to use various function modules for data
representation.
9. PHP’s built-in database connection modules help in connecting
databases easily reducing trouble and time for the development of web
applications and content-based sites.
10. The popularity of PHP gave rise to various communities of developers,
a fraction of which may be potential candidates for hire.
11. Flexibility makes PHP ready to effectively combine with many other
programming languages in order that the software package could use
Page No: 5 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
foremost effective technology for every particular feature.
In for loop, a loop variable is used to control the loop. First initialize this loop
variable to some value, then check whether this variable is less than or greater
than counter value. If statement is true, then loop body is executed and loop
variable gets updated. Steps are repeated till exit condition comes.
Syntax :
// code to be executed
Example:
<?php
$sum=0;
Page No: 6 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
for($i=0; $i<=10;$i+=2)
echo "$i<br/>";
$sum+=$i;
echo "Sum=$sum";
?>
for-each statement:
foreach loop is used for array and objects. For every counter of loop, an array
element is assigned and the next counter is shifted to the next element.
Syntax:
//code to be executed
Example:
<?php
echo "$i<br/>";
?>
Example :
class MyClass
function __construct()
- You have to manually dispose of objects you created, but in PHP, it's
handled by the Garbage Collector, which keeps an eye on your objects and
automatically destroys them when they are no longer needed.
- Destructors are useful for tidying up an object before it’s removed from
memory.
- Destructors don’t have any types or return value. It is just called before de-
allocating memory for an object or during the finish of execution of PHP
scripts or as soon as the execution control leaves the block.
- For example, if an object has a few files open or contains data that should be
written to a database, it’s a good idea to close the files or write the data before
the object disappears.
- You can create destructor methods in the same way as constructors, except
that you use __destruct() function
Example:
<?php
class MyDestClass
Page No: 8 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
{
function __construct()
function __destruct()
?>
$num1 = 10;
$num2 = 20;
echo "The largest number between $num1 and $num2 is: " .
findLargest($num1, $num2);
Page No: 9 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
?>
ii) <?php
if ($conn->connect_error) {
$conn->close();
?>
Page No: 10 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
$password = ""; // MySQL password (default: empty string for local
MySQL setup)
if ($conn->connect_error) {
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
} else {
$conn->close();
Page No: 11 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
?>
Ans − PHP cookie is a small piece of information which is stored at client Definition of cookie-1M
browser. It is used to recognize the user.
Creation of cookie with
− Cookie is created at server side and saved to client browser. Each time syntax and example-
when client sends request to the server, cookie is embedded with request. 1.5M
Such way, cookie can be received at the server side. In short, cookie can be
created, sent and received at server end.
− A cookie is a small file with the maximum size of 4KB that the web server
Deletion of cookie with
stores on the client computer.
syntax and example-
− A cookie can only be read from the domain that it has been issued from. 1.5M
Cookies are usually set in an HTTP header but JavaScript can also set a
cookie directly on a browser.
Page No: 12 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<?php
$cookie_name = "username";
$cookie_value = "abc";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400
= 1 day
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie name '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete Cookies
− Cookie can be deleted from user browser simply by setting expires
argument to any past date it will automatically delete the cookie from user
browser.
− Deleted cookie can be checked by calling the same cookie with its name
to check if it exists or not.
− There is no special dedicated function provided in PHP to delete a cookie.
All we have to do is to update the expire-time value of the cookie by
setting it to a past time using the setcookie() function. A very simple way
of doing this is to deduct a few seconds from the current time.
− Syntax:
− setcookie(name, time() - 3600);
<html>
<body>
<?php
setcookie("user"," ",time()-3600);
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Page No: 13 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans Bitwise operators allow evaluation and manipulation of specific bits within an List of Bitwise operators
integer. with use-2M
$a ^ $b Xor (exclusive or) Bits that are set in $a or $b but not both
are set.
1. & (Bitwise AND) : This binary operator works on two operands. Bitwise
AND operator in PHP takes two numbers as operands and does AND on every
bit of two numbers. The result of AND is 1 only if both bits are 1.
2. | (Bitwise OR) :Bitwise OR operator takes two numbers as operands and
does OR on every bit of two numbers. The result of OR is 1 any of the two bits
is 1.
3. ^ (Bitwise XOR ) : This is also known as Exclusive OR operator. Bitwise
XOR takes two numbers as operands and does XOR on every bit of two
numbers. The result of XOR is 1 if the two bits are different.
4. ~ (Bitwise NOT) : This is a unary operator i.e. works on only one operand.
Bitwise NOT operator takes one number and inverts all bits of it.
5. << (Bitwise Left Shift) :Bitwise Left Shift operator takes two numbers, left
shifts the bits of the first operand, the second operand decides the number of
places to shift.
6. >> (Bitwise Right Shift) :Bitwise Right Shift operator takes two numbers,
right shifts the bits of the first operand, the second operand decides the number
of places to shift.
Example:
// Bitwise AND
$First = 5;
Page No: 14 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
$second = 3;
$answer = $First & $second;
print_r("Bitwise & of 5 and 3 is $answer");
print_r("\n");
// Bitwise OR
$answer = $First | $second;
print_r("Bitwise | of 5 and 3 is $answer");
print_r("\n");
// Bitwise XOR
$answer = $First ^ $second;
print_r("Bitwise ^ of 5 and 3 is $answer");
print_r("\n");
// Bitwise NOT
$answer = ~$First;
print_r("Bitwise ~ of 5 is $answer");
print_r("\n");
// Bitwise Left shift
$second = 1;
$answer = $First << $second;
print_r("5 << 1 will be $answer");
print_r("\n");
// Bitwise Right shift
$answer = $First >> $second;
print_r("5 >> 1 will be $answer");
print_r("\n");
?>
Output:
Bitwise & of 5 and 3 is 1
Bitwise | of 5 and 3 is 7
Page No: 15 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Bitwise ^ of 5 and 3 is 6
Bitwise ~ of 5 is -6
5 << 1 will be 10
5 >> 1 will be 2
i) MySQL_select_db()
ii) ImageCopyReszied()
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
// Change db to "test" db
mysqli_select_db($con, "test");
// Close connection
mysqli_close($con);
?>
ii) imageCopyReszied()
The imagecopyresized() function is an inbuilt function in PHP which is used
to copy a rectangular portion of one image to another image. dst_image is the
destination image, src_image is the source image identifier.
Syntax:
bool imagecopyresized( resource $dst_image,
resource $src_image, int $dst_x, int $dst_y,
int $src_x, int $src_y, int $dst_w,
int $dst_h, int $src_w, int $src_h )
Parameters:This function accepts ten parameters as mentioned above and
described below:
• $dst_image: It specifies the destination image resource.
• $src_image: It specifies the source image resource.
• $dst_x: It specifies the x-coordinate of destination point.
• $dst_y: It specifies the y-coordinate of destination point.
• $src_x: It specifies the x-coordinate of source point.
• $src_y: It specifies the y-coordinate of source point.
• $dst_w: It specifies the destination width.
• $dst_h: It specifies the destination height.
• $src_w: It specifies the source width.
Page No: 17 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
• $src_h: It specifies the source height.
<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight,
$width, $height);
// Output
imagejpeg($thumb);
?>
Ans It is a type of overloading for creating dynamic methods that are not declared concept of overloading-
within the class scope. PHP method overloading also triggers magic methods 2M and example- 2M
dedicated to the appropriate purpose. Unlike property overloading, PHP
method overloading allows function call on both object and static context. The
related magic functions are,
• __call() – triggered while invoking overloaded methods in the object
context.
• __callStatic() – triggered while invoking overloaded methods in static
context.
<?php
Page No: 18 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
class GFG {
public function __call($name, $arguments) {
class GFG {
function multiply($var1){
return $var1;
}
function multiply($var1,$var2){
return $var1 * $var1 ;
}
}
$ob = new GFG();
$ob->multiply(3,6);
?>
b) Develop PHP program to create database and insert records in 4M
database.
<?php
if(isset($_POST)) {
$servername = "localhost";
$username = "root";
Page No: 19 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
$password = "";
//$dbname = "clg";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
<?php
{
$servername = "localhost";
Page No: 20 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO staff (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
Ans These are arrays that contain other nested arrays. Concept and syntax of
An array which contains single or multiple arrays within it and can be multidimensional array-
accessed via multiple indices. 2M
We can create one dimensional and two dimensional array using
multidimensional arrays. The advantage of multidimensional arrays is that Implementation/example-
they allow us to group related data together. 2M
Syntax for creating multidimensional array in php
array (
array (elements...),
array (elements...),
...
)
Example :
<?php
// Defining a multidimensional array
$person = array(
array(
"name" => "Yogita K",
"mob" => "5689741523",
"email" => "[email protected]",
),
array(
"name" => "Manisha P.",
"mob" => "2584369721",
"email" => "[email protected]",
),
array(
"name" => "Vijay Patil",
"mob" => "9875147536",
Page No: 21 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
"email" => "[email protected]",
)
);
// Accessing elements
echo "manisha P's email-id is: " . $person[1]["email"], "<br>";
echo "Vijay Patil's mobile no: " . $person[2]["mob"];
?>
Output :
manisha P's email-id is: [email protected]
Vijay Patil's mobile no: 9875147536
d) Explain print and echo statement in PHP. 4M
Page No: 22 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
echo $x + $y;
?>
Output :
Hello, Welcome to PHP Programming
Hello Welcome PHP
Hello, PHP
10+20=30
The PHP print Statement :
The PHP print statement is similar to the echo statement and can be used
alternative to echo at many times. It is
also language construct and so we may not use parenthesis : print or print().
print statement can also be used to print
strings and variables.
Web Based Application Development using PHP (MSBTE) 1-6 Expressions
and Control Statements in PHP
Example :
<?php
// Displaying strings
print "Hello, Welcome to PHP Programming";
print "<br/>";
//Displaying variables
$s="Hello, PHP";
$x=10;
$y=20;
print "$s <br/>";
print $x."+".$y."=";
print $x + $y;
?>
Output :
Page No: 23 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Hello, Welcome to PHP Programming
Hello, PHP
10+20=30
e) Create a form given below also write PHP code to find given number is 4M
odd or even.
OR
<html>
<body>
<?php
if($_POST)
{
$num = $_POST['num'];
if(!is_numeric($num))
{
echo "String not allowed.
Input should number";
return;
}
if($num % 2==0)
{
echo "Number is an even number";
}
else
{
echo "Number is an odd number ";
}
}
?>
</body>
</html>
Page No: 25 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
a) State applications of serialization. Illustrate its use with example. 6M
Ans Serialization in PHP refers to the process of converting a data structure (like Any three correct
an object, array, or variable) into a string format that can be stored, applications-3 M
transmitted, or manipulated. Deserialization is the reverse process, converting
the serialized string back into its original data structure. Any Correct example in
PHP – 3 M
Applications of serialization in PHP:
1. Serialization allows developers to store complex data structures, like
objects and arrays, in databases or files.
2. When data needs to be sent over a network (e.g., via APIs or sockets),
it is serialized to ensure compatibility with the transmission format.
3. PHP sessions often use serialization to store session data as strings.
The session data is serialized before being written to a storage medium
like files or databases.
4. Serialization is used in caching systems like Redis or Memcached to
store PHP objects or arrays for faster retrieval.
5. Serialization can preserve the state of objects by storing their
properties and values. This is useful when saving the state of an object
between requests or sessions.
6. Developers use serialization to log complex data structures in a
readable and storable format for debugging purposes.
7. Serialization is often used in queue systems to serialize tasks or
messages before pushing them into the queue.
8. When applications written in PHP need to communicate with systems
in other programming languages, serialization ensures that the data can
be properly transmitted and interpreted.
Example:
<?php
class User
{
public $name;
public $email;
Page No: 26 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
$this->name = $name;
$this->email = $email;
}
}
$user = new User('Rina', '[email protected]');
$serializedUser = serialize($user);
echo $serializedUser;
?>
OUTPUT:
O:4:"User":2:{s:4:"name";s:4:"Rina";s:5:"email";s:15:"[email protected]";}
Page No: 27 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<style>
.error {color: #FF0001;}
</style>
</head>
<body>
<?php
// define variables to empty values
$nameErr = " ";
//Input fields validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validating Name field
if (emptyempty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = input_data($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only alphabets and white space are allowed";
}
}
?>
<h2>Input Form</h2>
<span class = "error">* required field </span>
<br><br>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr; ?> </span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
</form>
<?php
if(isset($_POST['submit'])) {
if($nameErr == "") {
echo "<h3 color = #FF0001> <b>You have sucessfully
registered.</b> </h3>";
echo "<h2>Your Input:</h2>";
echo "Name: " .$name;
echo "<br>";
} else {
echo "<h3> <b>Please input name in correct fomat.</b> </h3>";
}
}
?>
</body>
</html>
c) Display the given text "this is server side coding using PHP" in 6M
Page No: 28 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
PDF format using PHP.
Page No: 29 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<input type="number" name="rollno" id="rollno" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
PHP Code: result.php
<?php
// Database credentials
$servername = "localhost";
$username = "root";
$password = ""; // Adjust if needed
$dbname = "My_db";
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get the roll number from the form
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$rollno = intval($_POST['rollno']);
// Query to check the result
$sql = "SELECT Status FROM result_table WHERE Rollno = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $rollno);
$stmt->execute();
$result = $stmt->get_result();
// Check if the Rollno exists
Page No: 30 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo "Roll Number: " . $rollno . "<br>";
echo "Result: " . $row['Status'];
} else {
echo "No result found for Roll Number: " . $rollno;
}
$stmt->close();
}
$conn->close();
?>
Create table result_table
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = " My_db";
// Creating connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br>";
// sql to create table
$sql = "CREATE TABLE result_table ( Rollno INT PRIMARY KEY, Status
VARCHAR(10) NOT NULL)";
if ($conn->query($sql) === TRUE) {
echo "Table created successfully";
Page No: 31 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
File - Insert.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "My_db";
// Creating connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br>";
$sql = "INSERT INTO result_table (Rollno, Status)
VALUES (1, 'Pass');";
$sql .= " INSERT INTO result_table (Rollno, Status)
VALUES (2, 'Fail')";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Page No: 32 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
?>
Code to delete the record:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "My_db";
// Creating connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br>";
$sql = "DELETE from result_table WHERE Rollno=2";
if ($conn->query($sql) === TRUE) {
echo "record deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Page No: 34 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
return $marks*100/$maxmarks;
};
echo "marks=285 percentage=". $percent(285);
?>
(ii) Variable function:
If name of a variable has parentheses (with or without parameters in it) in front
of it, PHP
parser tries to find a function whose name corresponds to value of the variable
and executes
it. Such a function is called variable function.
Syntax:
<?php
function valueofvariable (arg list)
{
//block of code;
}
$variable_name= valueofvariable;
$variable_name (arg list);
?>
Example:
<?php
function add($x, $y){
echo $x+$y;
}
function sub($x, $y){
echo $x-$y;
}
$var=readline("enter name of function: ");
$var(10,20);
Page No: 35 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
?>
OUTPUT
add
30
c) Explain: 6M
(i) _clone()
(ii) class_exists()
(iii) get_parent_class()
Page No: 36 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
public function __clone()
{
$this->address = clone $this->address;
}
}
$bob = new Person('Bob');
$bob->address->street = 'North 1st Street';
$bob->address->city = 'San Jose';
$alex = clone $bob;
$alex->name = 'Alex';
$alex->address->street = '1 Apple Park Way';
$alex->address->city = 'Cupertino';
var_dump($bob);
var_dump($alex);
?>
In above example, using __clone() method in the Person class we can create a
separate
copy of the Address object for both the references which is known as deep
copy of
object,.
(ii) class_exists()
The class_exists() function checks whether a class with a given name has been
defined or not. It is useful for verifying the availability of a class before
instantiating it or calling its methods.
Syntax
bool class_exists(string $className, bool $autoload = true)
Example:
<?php
Page No: 37 | 38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
class MyClass {}
if (class_exists('MyClass')) {
echo "Class 'MyClass' exists.";
} else {
echo "Class 'MyClass' does not exist.";
}
?>
Output:
Class 'MyClass' exists.
(iii) get_parent_class()
The get_parent_class() function retrieves the name of the parent class for a
given class or object. It is used in object-oriented programming to examine
class inheritance.
Syntax
string|false get_parent_class(object|string $objectOrClass = null)
Example:
<?php
class ParentClass {}
class ChildClass extends ParentClass {}
$child = new ChildClass();
echo get_parent_class($child);
?>
Output:
ParentClass
Page No: 38 | 38
lOMoARcPSD|29458053
Page 1 / 22
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
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
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
{
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";
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
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
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
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>
Also notice that all session variable values are stored in the global
$_SESSION variable:
Page 7 / 22
?>
</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);
Page 8 / 22
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.
function accept($name,$rollno)
{
$this->name=$name;
$this->rollno=$rollno;
Page 9 / 22
}
}
?>
$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
$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
Page 11 / 22
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.
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
?>
Page 12 / 22
Page 13 / 22
Page 14 / 22
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
Page 16 / 22
Solution2:
Create login.php
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
?>
Page 17 / 22
Example:
(Any type of inheritance example shall be considered)
<?php
class student {
var $var = "This is first var";
protected $fist_name;
protected $last_name;
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
<?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
?>
</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]
?>
OR
Page 20 / 22
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
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
Subject Name: Web Based Application Development with PHP Subject Code: 22619
Important Instructions to examiners:
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model
answer.
Ans 1. Performance: PHP script is executed much faster than those scripts which are Any 4
written in other languages such as JSP and ASP. PHP uses its own memory, so the correct
server workload and loading time is automatically reduced, which results in faster points-2 M
processing speed and better performance.
2. Open Source: PHP source code and software are freely available on the web. We
can develop all the versions of PHP according to our requirement without paying
any cost. All its components are free to download and use.
3. Embedded: PHP code can be easily embedded within HTML tags and script.
4. Platform Independent: PHP is available for WINDOWS, MAC, and LINUX&
UNIX operating system. A PHP application developed in one OS can be easily
executed in other OS also.
5. Database Support: PHP supports all the leading databases such as MySQL,
SQLite, ODBC, etc.
6. Security: PHP is a secure language to develop the website. It consists of multiple
Page No: 1 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
layers of security to prevent threads and malicious attacks.
7. Loosely Typed Language: PHP allows us to use a variable without declaring its
datatype. It will be taken automatically at the time of execution based on the type
of data it contains on its value.
8. Error Reporting: PHP has predefined error reporting constants to generate an error
notice or warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT,
E_PARSE.
9. Control: Different programming languages require long script or code, whereas
PHP can do the same work in a few lines of code. It has maximum control over the
websites like we can make changes easily whenever we want.
10. Web servers Support: PHP is compatible with almost all local servers used today
like Apache, Netscape, Microsoft IIS, etc.
11. Familiarity with syntax: PHP has easily understandable syntax. Programmers are
comfortable coding with it.
12. Helpful PHP Community: It has a large community of developers who regularly
updates documentation, tutorials, online help, and FAQs. Learning PHP from the
communities is one of the significant benefits.
Syntax:
str_word_count ( $string , $returnVal, $chars )
Parameters Used:
$string: Input string.
$returnVal: $returnVal parameter. It is an optional parameter and its default value is 0.
$chars: This is an optional parameter which specifies a list of additional characters which
shall be considered as a ‘word’.
c) Define Serialization. 2M
Ans In PHP, serialization is the process of converting a data structure or object into a string Correct
Definition- 2
representation that can be stored or transmitted. This allows you to save the state of an
M
object or data structure to a database, cache, or send it over a network connection, and
then later recreate the object or data structure from the serialized string.
Page No: 2 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
d) Differentiate between Session & Cookies. (Any two points) 2M
Page No: 3 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
echo "$element";
echo "</br>";
}
?>
g) Explain in short how can we destroy cookies. 2M
Ans To delete or destroy the cookie, we can use the setcookie() function with the same cookie Correct
name, an empty value, and a past expiration time (specifically, one hour ago). Setting the explanation-
expiration time to the past causes the cookie to be immediately expired and removed from 2M
the browser.
Example:
<?php
$cookieName = "username";
// Set the cookie expiration time to the past to delete the cookie
setcookie($cookieName, "", time() - 3600);
Page No: 4 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$i++;
}
?>
Do while statement is same as the while statement, the only difference is that it evaluates
the expression at the end.
Syntax –
do
{
code to be executed
}
while(condition);
Example:
<?php
$i=0;
do
{ //output value 0 from 10
echo "The Number is ".$i."<br>";
$i++;
}
while($i<=10)
?>
The For Loop
The for loop is used when we know in advance how many times the script should run.
Syntax:
for(initialization; condition; increment)
{
code to be executed
}
Example:
<?php
for($i=0;$i<=10;$i++)
{
echo "The Number is ".$i."<br/>";
}
?>
The Foreach Loop
Syntax: Syntax:
implode (separator, array) explode (separator,string,limit)
c) Define Introspection and explain it with suitable example. 4M
3. get_parent_class() Returns the class name of a Return object's parent class. Any Correct
Example- 2
Page No: 6 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
4. is_subclass_of() Checks whether an object has a given parent class. M
5. get_declared_classes() Returns a list of all declared classes.
6. get_class_methods() Returns the names of the class methods.
7. get_class_vars() Returns the default properties of a class
8. interface_exists() Checks whether the interface is defined.
9. method_exists() Checks whether an object defines a method.
Example:
<?php
class Rectangle
{
var $dim1 = 2;
var $dim2 = 10;
function Rectangle($dim1,$dim2)
{
$this->dim1 = $dim1;
$this->dim2 = $dim2;
}
function area()
{
return $this->dim1*$this->dim2;
}
function display()
{
// any code to display info
}
}
$S = new Rectangle(4,2);
//get the class varibale i.e properties
$class_properties = get_class_vars("Rectangle");
//get object properties
$object_properties = get_object_vars($S);
//get class methods
$class_methods = get_class_methods("Rectangle");
//get class corresponding to an object
$object_class = get_class($S);
print_r($class_properties);
print_r($object_properties);
print_r($class_methods);
print_r($object_class);
?>
OUTPUT:
Array ( [dim1] => 2 [dim2] => 10 )
Array ( [dim1] => 4 [dim2] => 2 )
Page No: 7 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
Array ( [0] => Rectangle [1] => area [2] => display )
Rectangle
d) Explain mail () function in PHP with example. 4M
Ans PHP mail() function is used to send email in PHP. You can send text message, html Syntax with
message and attachment with message using PHP mail() function. description-2
M
Syntax:
Example-2
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, M
string $additional_parameters ]] )
Description:
$additional_headers (optional): specifies the additional headers such as From, CC, BCC
etc.
Example:
<html>
<head>
</head>
<body>
<?php
$to_email = "[email protected]";
$headers = 'From:[email protected]';
$retvalue=mail($to_email,$subject,$message,$headers);
echo $retvalue;
Page No: 8 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
echo "Message sent successfully...";
}else {
?>
</body>
</html>
2. Associative array -
• This type of arrays is like the indexed arrays but instead of linear storage, every
value can be assigned with a user-defined key of string type.
• An array with a string index where instead of linear storage, each value can be
assigned a specific key.
• Associative array differ from numeric array in the sense that associative arrays
Page No: 9 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
use descriptive names for id keys.
Example:
<?php
class student{
public $name;
function construct()
{
echo "Constructor is executed for " .$this->name;
}
function destruct()
{
echo "Destructor is executing for " .$this->name;
}
}
$s1=new student("Sneha");
?>
c) Define session & cookie. Explain use of session start. 4M
Ans Cookie: Cookie is a small piece of information which is stored at client browser. It is used Definition
to recognize the user. each – 1 M
Page No: 10 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
• Cookie is created at server side and saved to client browser. Each time when client Use – 2 M
sends request to the server, cookie is embedded with request. Such way, cookie
can be received at the server side. In short, cookie can be created, sent and
received at server end.
Session: Session data is stored on the server side and each Session is assigned with a
unique Session ID (SID) for that session data. As session data is stored on the server there
is no need to send any data along with the URL for each request to server.
Session_start-
• PHP session_start() function is used to start the session.
• It starts a new or resumes existing session.
• It returns existing session if session is created already.
• If session is not available, it creates and returns new session
Session variables are set with the PHP global variable: $_SESSION.
Example:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Ans The below given code will demonstrate to insert and retrieve the respective query result Relevant
operations. code – 4 M
<?php
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
Page No: 11 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
}
$sql = "SELECT id, firstname, lastname FROM staff";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"].
"<br>";
}
} else {
echo "0 results";
}
$conn->close();
}
?>
<?php
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO staff (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
?>
b) Write a program to demonstrate concept of inheritance in PHP. 4M
Syntax:
derived_class_name is the name of new class which is also known as child class and
base_class_name is the name of existing class which is also known as parent class.
A derived class can access properties of base class and also can have its own properties.
Properties defined as public in base class can be accessed inside as well as outside of the
class but properties defined as protected in base class can be accessed only inside its derived
class. Private members of class cannot be inherited.
Single Inheritance
Multilevel Inheritance
Page No: 13 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
Hierarchical Inheritance
Multiple Inheritance
Example:
<?php
class college
protected $code=7;
public $sname;
$this->sname=$n;
$s1=new student();
$s1->setName(“Ramesh”);
$s1->display();
Page No: 14 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
?>
OUTPUT:
<label for="address">Address:</label><br>
<input type="text" id="address" name="address"><br><br>
<label for="post">Post:</label><br>
<input type="text" id="post" name="post"><br><br>
<label for="salary">Salary:</label><br>
<input type="text" id="salary" name="salary"><br><br>
Page No: 15 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
PHP Program
<!DOCTYPE html>
<html lang="en">
<head>
<title>Employee Information</title>
</head>
<body>
<h2>Employee Information</h2>
<?php
// Retrieve form data using PHP
$employee_name = $_POST['employee_name'];
$address = $_POST['address'];
$mobile_no = $_POST['mobile_no'];
$dob = $_POST['dob'];
$post = $_POST['post'];
$salary = $_POST['salary'];
Ans In the below example a student record with a roll no. ‘CO103’ will be deleted by using Relevant
DELETE statement and WHERE clause. code – 4 M
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Page No: 16 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
e) Explain web page validation with example. 4M
Ans There are some built-in functions in PHP which will validate the web page. Explanation
• User may by mistakenly submit the data through form with empty fields or in wrong –2M
format.
• PHP script must ensure that required fields are complete and submitted data is in Example – 2
valid format. M
• PHP provides some inbuilt function using these functions that input data can be
validated.
• empty() function will ensure that text field is not blank it is with some data, function
accepts a variable as an argument and returns TRUE when the text field is submitted
with empty string, zero, NULL or FALSE value.
• Is_numeric() function will ensure that data entered in a text field is a numeric value,
the function accepts a variable as an argument and returns TRUE when the text
field is submitted with numeric value.
• preg_match() function is specifically used to performed validation for entering text
in the text field, function accepts a “regular expression” argument and a variable as
an argument which has to be in a specific pattern. Typically it is for validating email,
IP address and pin code in a form.
• For Example a PHP page formvalidation.php is having three text fields name,
mobile number and email from user, on clicking Submit button a data will be
submitted to PHP script validdata.php on the server, which will perform three
different validation on these three text fields, it will check that name should not be
blank, mobile number should be in numeric form and the email is validated with an
email pattern.
<html>
<head>
<title> Validating Form Data</title>
</head>
<body>
<form method="post" action="validdata.php">
Name :<input type="text" name="name" id="name" /><br/>
Mobile Number :<input type="text" name="mobileno" id="mobileno" /><br/>
Email ID :<input type="text" name="email" id="email" /><br/>
<input type="submit" name="submit_btn" value="Submit" />
</form>
</body>
</html>
Page No: 17 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if(empty($_POST['name']))
{
echo "Name can't be blank<br/>";
}
if(!is_numeric($_POST['mobileno']))
{
echo "Enter valid Mobile Number<br/>";
}
$pattern ='/\b[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}\b/';
if(!preg_match($pattern,$_POST['email']))
{
echo "Enter valid Email ID.<br/>";
}
}
?>
Ans Program Instructions are executed sequentially. In some cases it is necessary to change Each Syntax
the sequence of executions based on certain conditions. For this purpose decision control Carries – 1
structure is required. M
Decision making statements are
1. if statement
2. if else statement
3. Else if else statement
4. Switch statement
5. Break statement
6. Continue statement
If statement-
Syntax
if (condition) {
// code to be executed if condition is true;
Page No: 18 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
}
Example-
<?php
$a=10;
if ($a > 0)
{
echo "The number is positive";
}
?>
1. If else statement –
If you want to execute some code if a condition is true and another code if a condition is
false, use the if ... else statement.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
<?php
$d = date("D");
if ($d == "Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
Page No: 19 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
if(condition1)
{
// Code to be executed
if condition1 is true
}
elseif(
condition2)
{
// Code to be executed if the condition1 is false and condition2 is true
}
else
{
// Code to be executed if both condition1 and condition2 are false
}
4. The if...elseif...else statement executes different codes for more than two
conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
// code to be executed if first condition is false and this condition is true;
} else {
// code to be executed if all conditions are false;
}
Example
Output "Have a good morning!" if the current time is less than 10, and "Have a
good day!" if the current time is less than 20. Otherwise it will output "Have a
Page No: 20 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
good night!":
<?php
$t = date("H");
} else {
echo "Have a good night!";
}
?>
4.swich case –
The PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (expression) {
case label1:
//code block
break;
case label2:
//code block;
break;
case label3:
//code block
break;
default:
Page No: 21 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
//code block
}
This is how it works:
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
The break keyword breaks out of the switch block
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
4 Break : The keyword break ends execution of the current for, for each, while, do
while or switch structure. When the
keyword break executed inside a loop the control automatically passes to the first
Page No: 22 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
statement outside the loop. A
Example :
<?php
for($i=1; $i<=5;$i++)
echo "$i<br/>";
if($i==3)
break;
?>
Output :
2. Continue : It is used to stop processing the current block of code in the loop and
goes to the next iteration. It is used to skip a part of the body of the loop under
certain conditions. It causes the loop to be continued with the next iteration after
skipping any statement in between. The continue statement tells the compiler
”SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH THE
NEXT ITERATION”.
Example :
<?php
for($i=1; $i<=5;$i++)
Page No: 23 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
if($i==3)
continue;
echo "$i<br/>";
?>
Output :
5
b) Write PHP program to demonstrate database operation using PHP and 6M
MySQL.
Ans Note - Assessor may consider any one database operation from this. Any One
Correct
CREATE – Database
Operation
A database consists of one or more tables. You will need special CREATE privileges to Carries 6 M
create or to delete a MySQL database. (Create,
Select,
− A database is a collection of data. MySQL allows us to store and retrieve the data Insert,
from the database in a efficient way. Update,
Delete)
<?php
if(isset($_POST)) {
$servername = "localhost";
$username = "root";
$password = "";
//$dbname = "clg";
Page No: 24 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
} else {
$conn->close();
?>
INSERT –
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
if ($conn->connect_error)
Page No: 25 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$sql = "SELECT id, firstname, lastname FROM staff";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"].
"<br>";
} else {
$conn->close();
?>
DELETE-
• Record scan be deleted from a table using the SQL DELETE statement.
• DELETE statement is typically used in conjugation with the WHERE clause to
delete only those records that matches specific criteria or condition.
• SQL query is formed using the DELETE statement and WHERE clause, after that
will be executed by passing this query to the PHP query() function to delete the tables
records.
• For example a student record with a roll no. ‘CO103’ will be deleted by using
DELETE statement and WHERE clause.
• <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
Page No: 26 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
} else {
$conn->close();
?>
INSERT-
After a database and a table have been created, we can start adding data in them.
The INSERT INTO statement is used to add new records to a MySQL table:
<?php
$servername = "localhost";
Page No: 27 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$username = "root";
$password = "";
$dbname = "clg";
if ($conn->connect_error) {
} else {
$conn->close();
?>
UPDATE-
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
<?php
$servername = "localhost";
$username = "root";
Page No: 28 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
$password = "";
$dbname = "clg";
if ($conn->connect_error) {
Ans In function overriding, both parent and child classes should have same function name and Explanation-
number of arguments. 2 M,
Script- 4 M
It is used to replace the parent method in child class.
The two methods with the same name and same parameter is called overriding.
Inherited methods can be overridden by redefining the methods (use the same name) in
the child class.
Example-
<?php
Page No: 29 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
class Shape
public $length;
public $width;
$this->length = $length;
$this->width = $width;
public $height;
$this->length = $length;
$this->width = $width;
$this->height = $height;
echo "The length is {$this->length}, the width is {$this->width}, the height is {$this-
>height} ";
Page No: 30 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
}
$s->intro();
?>
Output :
Page No: 31 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
</body>
</html>
b) Explain the following string functions with example: 6M
(i) Str-replace
(ii) Vcwords()
(ii) Strlen()
(iv) Strtoupper()
Ans Note: in sub question (ii) instead of Vcwords() read it as ucwords() Each Correct
1. str_replace()-Replaces some characters in a string (case-sensitive) String
Function
Syntax- Str_replace(string tobe replaced, text, string) Carries-
Example- 1.5 M
<?php
echo str_replace("Clock","Click","Click and Clock");
?>
Output:
Click and Click
Page No: 32 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
Output:
INFORMATION TECHNOLOGY
Ans An Interface allows the users to create programs, specifying the public methods that a Interface
class must implement, without involving the complexities and details of how the explanation -
particular methods are implemented. 3 M,
example-3 M
− An Interface is defined just like a class but with the class keyword replaced by the
interface keyword and just the function prototypes.
− The interface contains no data variables.
− An interface consists of methods that have no implementations, which means the
interface methods are abstract methods.
− All the methods in interfaces must have public visibility scope.
-Interfaces are different from classes as the class can inherit from one class only whereas
the class can implement one or more interfaces.
− Interface enables you to model multiple inheritance
Syntax-1 :
implements interface_name1, ..
Example :
Example :
<?php
class A
interface B
function disp2()
echo "\nChild-C";
$obj->disp1();
$obj->disp2();
$obj->disp3();
?>
Output :
Parent-A
Parent-B
Child-C
Page No: 34 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
Syntax-2 :
interface_name2, ...
Example :
<?php
interface A
interface B
function disp1()
function disp2()
Page No: 35 | 36
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
public function disp3()
$obj->disp1();
$obj->disp2();
$obj->disp3();
?>
Output :
Parent-A
Parent-B
Child-C
Page No: 36 | 36