PHP W24 Model Answer by Campusify
PHP W24 Model Answer by Campusify
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
?>
ii) <?php
if ($conn->connect_error) {
$conn->close();
?>
Page No: 10 | 38
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
PDF format using PHP.
Page No: 29 | 38
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy
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
Campusify - Free Study Material - https://t.me/campusifyy