PHP Merged
PHP Merged
PHP Merged
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: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Page 1 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
5. User-friendly:
It has a less learning curve, and one can learn it quickly.
6. Flexible:
It is highly flexible, and people can readily use it to combine its function
with various other programming languages.
7. PHP uses its own memory space, so the workload of the server and
loading time reduces automatically, which results into the faster processing
speed.
8.PHP has multiple layers of security to prevent threats and malicious
attacks.
b) State the use of strlen() and strrev() 2M
Ans. Strlen(): Use of each
The strlen() function is used to count number of characters in a string. It method- 1M
returns the length of a string.
Strrev():
The strrev() function is used to reverse a string.
c) Define introspection 2M
Ans. Introspection is the ability of a program to examine object characteristics Correct
definition 2M
such as its name, parent class, properties and method.
d) Enlist the attributes of cookies. 2M
Ans. Attributes of Cookies are as follows: List any four
1. name attributes 1/2M
each
2. value
3. expire
4. path
5. domain
6. secure
e) Write syntax of constructing PHP webpage with MySQL 2M
Ans. Using MySQLi object-oriented procedure: Correct syntax
Syntax: 2M
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = new mysqli($servername, $username, $password);
// Checking connection
Page 2 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
OR
POST method:
POST method is a way to pass data entered in form to the server securely
without adding it to URL.
OR
It Handles request in servlet which is sent by the client. If a client is entering
registration data in an html form, the data can be sent using post method.
Page 3 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Page 4 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Multidimensional Arrays
In multi-dimensional array, each element in the main array can also be an
array. A multidimensional array is an array containing one or more arrays. It
has more than one dimension in the form of rows and columns. Values in the
multi-dimensional array are accessed using multiple indexes.
Example:
In this example we create a two dimensional array to store marks of three
students in three subjects:
<?php
$marks = array(
"Arjun" => array
("physics" => 35, "maths" => 30, "chemistry" => 39),
"Dinesh" => array
("physics" => 30, "maths" => 32, "chemistry" => 29),
"Surabhi" => array
("physics" => 31, "maths" => 22, "chemistry" => 39)
);
/* Accessing multi-dimensional array values */
echo "Marks for Arjun in physics : " ;
echo $marks['Arjun']['physics'] . "<br />";
echo "Marks for Dinesh in maths : ";
echo $marks['Dinesh']['maths'] . "<br />";
echo "Marks for Surabhi in chemistry : " ;
echo $marks['Surabhi']['chemistry'] . "<br />";
echo "<pre>";
print_r($marks);
echo "</pre>";
?>
OR
$cars = array (array("Volvo",22,18), array("BMW",15,13),
array("Ciaaz",10,15));
OR
$row0 = array("Volvo",22,18);
$row1 = array("BMW",15,13);
$row2 = array("Ciaaz",10,15);
Page 5 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Page 6 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
BCC is the acronym for blind carbon copy. It is similar to CC. The email
addresses included in the BCC section will not be shown to the other
recipients.
4. PHP mailer uses Simple Mail Transmission Protocol (SMTP) to send mail.
On a hosted server, the SMTP settings would have already been set. The
SMTP mail settings can be configured from “php.ini” & “sendemail.ini”
file in the PHP installation folder.
The implode function returns string. The explode function returns array.
The first parameter of the implode The first parameter of the explode
function is optional. function is required.
Syntax: Syntax:
string implode(string $seperator, array explode(string
array $array) separator,string string)
Example: Example:
<?php <?php
$arr = array('CO','IF','EJ'); $str = "CO-IF-EJ";
$str = implode(" ",$arr); $arr = implode("-",$str);
echo $str; print_r($arr);
?> ?>
Page 7 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Example:
<?php
// Creating instance of Animals class
$objAnimals = new Animals();
// Assigning values
$objAnimals->name = "Lion";
$objAnimals->category = "Wild Animal";
// Cloning the original object
$objCloned = clone $objAnimals;
$objCloned->name = "Elephant";
$objCloned->category = "Wild Animal";
print_r($objAnimals);
print_r($objCloned);
?>
c) Describe the procedure of validation of web page 4M
Ans. Validating a web page in PHP involves checking the input data provided by
Explanation
users to ensure that it meets the required criteria and is safe for further 3M
processing. Here's a general procedure for validating a web page in PHP:
The procedure of validation of web page.
Define the Validation Rules: Determine the validation rules for each input Example 1M
field on the web page. This includes constraints such as required fields, data
formats (e.g., email, date), length limits, and any specific patterns or
restrictions.
Create the HTML Form: Design and create the HTML form that collects
user input. Specify the appropriate input types, such as text, email, number,
etc., and include any necessary attributes like required or pattern.
Page 8 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Submitting the Form: Set up the PHP script that processes the form
submission. This script will be responsible for handling the validation and
processing the data. Ensure that the form's method attribute is set to "POST"
so that the data is sent securely.
Retrieve and Sanitize Input: In the PHP script, retrieve the submitted data
using the $_POST superglobal array. Sanitize the input to remove any
unwanted characters or tags that could potentially pose security risks. You
can use functions like htmlspecialchars or filter_input to sanitize specific
inputs.
Display Validation Errors: If any input fails validation, store the error
messages in an array or variable. Display these error messages next to the
corresponding input fields on the web page, informing the user about the
specific validation issues they need to address.
Process Valid Data: If all the input data passes validation, proceed with
further processing, such as storing the data in a database, sending emails, or
performing other necessary operations.
Page 9 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Page 10 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
if ($conn->connect_error) die($conn->connect_error);
$query = "DELETE from student WHERE rollno='CO103'";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
?>
4. Attempt any THREE of the following: 12M
a) State user defined functions and explain it with example. 4M
Ans. A function is a named block of code that performs a specific task.PHP
supports user defined functions, where user can define his own functions. Correct
explanation -
A function doesn't execute when its defined, it executes when it is called.
2M
The syntax to create a PHP user defined function –
A PHP user-defined function declaration starts with the keyword function as
shown below – Any correct
function funName($arg1, $arg2, ... $argn) Example-2M
{
// code to be executed inside a function
//return $val
}
The syntax to call a PHP user-defined function –
$ret=funName($arg1, $arg2, ... $argn);
Example:
<?php
// user-defined function definition
function printMessage(){
echo "Hello, How are you?";
}
//user-defined function call
printMessage();
?>
As in the above program, the printMessage() function is created using the
keyword function. The function prints the message “Hello, How are you?”.
So, farther in the program when it is calling the function as
“printMessage();”. It prints a message, as we can see in the above output.
Page 11 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Page 12 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Explanation
3M
Page 13 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
server can handle requests for static files like CSS, JavaScript, and images,
delivering them directly to the client without involving PHP processing. It
can also handle URL rewriting or redirection for search engine optimization
(SEO) purposes or to create user-friendly URLs.
5. Content Delivery: Once the PHP script execution is complete, the web
server sends the generated content (usually HTML) back to the client's
browser as an HTTP response. The server sets the appropriate headers, such
as Content-Type, Content-Length, and caching directives, to ensure the
correct interpretation and rendering of the response by the client.
6. Error Handling and Logging: The web server is responsible for handling
errors and logging relevant information. If an error occurs during PHP script
execution, the web server can be configured to display an error message or
redirect to a custom error page. It also logs information about requests, errors,
and server events, which can be helpful for debugging, monitoring, and
performance analysis.
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "INSERT INTO student(rollno,name,percent) VALUES
('CO103','Reena Patel',98.45)";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
?>
Page 14 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Retrieving operation:
The data can be retrieved from the table using SQL SELECT statement which
is used to select the records from database tables.
SQL query using the SELECT statement will be executed by passing this
SQL query to the PHP query() function to retrieve the table data.
For example data from the student table can be executed by using the
SELECT statement.
select_sample.php
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "SELECT * FROM student";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " .
$conn->error);
$rows = $result->num_rows;
echo "<table
border='1'><tr><th>RollNo.</th><th>Name</th><th>Percentage</th></tr>";
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo "<tr>";
for ($k = 0 ; $k < 3 ; ++$k) echo
"<td>$row[$k]</td>";
echo "</tr>";
}
echo "</table>";
?>
e) Create a web page using GUI components 4M
Ans. <!DOCTYPE html>
<html> Correct syntax
of any four
<head> GUI
<title>Registration form</title> components
<link rel="stylesheet" href="styel.css" type="text/css">
</head> 1M for each
component
Page 15 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
<body>
<div class="main">
<div class="register">
<h2>Register Here</h2>
<form id="register" action="registrationform.php" method="post">
<label>First name:</label>
<br>
<input type="text" id="fname" name="fname" placeholder="Enter your first
name">
<br>
<br>
<label>Last name:</label>
<br>
<input type="text" id="lname" name="lname" placeholder="Enter your last
name">
<br>
<br>
<label>Date of Birth:</label>
<br>
<input type="date" id="dob" name="dob" placeholder="Enter your
Birthday">
<br>
<br>
<label>Gender:</label>
<br>
<input type="radio" id="male" name="gender" value="male">
Page 16 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
<span id="male">Male</span>
<input type="radio" id="female" name="gender" value="female">
<span id="female">Female</span>
<br>
<br>
<label>Select Usertype</label>
<br>
<select name="usertype" id="usertype">
<option value="Student">Student</option>
<option value="Staff">Staff</option>
<option value="Alumni">Alumni</option>
</select>
<br>
<br>
<label>Password:</label>
<br>
<input type="password" id="pwd" name="password" placeholder="Enter
your password" pattern ="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must
contain at least one number and one uppercase and lowercase letter, and at
least 8 or more characters" required>
<br>
<br>
</form>
</div><!-----end of register--->
Page 17 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
</div><!-----end of main---->
</body>
</html>
5. Attempt any TWO of the following 12M
a) Implement any three data types used in PHP with illustration 6M
Ans. Data Types :
PHP provides eight types of values, or data types: Implementation
Four are scalar (single-value) types: integers, floating-point numbers, strings, / example of
and Booleans. any three data
types -2Meach
Two are compound (collection) types: arrays and objects.
Two are special types: resource andNULL.
Integers: Integers are whole numbers, such as 1, 12, and 256. Integer literals
can be written in decimal, octal, or hexadecimal.
Example :
Decimal1998 ,−641 , +33
Octal0755 // decimal 493 , 010 // decimal 8
Hexadecimal0xFF // decimal 255 ,0x10 // decimal 16 , -0xDAD1 // decimal
−56017
Binary numbers begin with 0b, followed by a sequence of digits (0 and 1).
Like other values, you can include a sign in binary numbers: 0b01100000 //
decimal 1 ,0b00000010 // decimal 2
Page 18 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Arrays :An array holds a group of values, which you can identify by position
(a number, with zero being the first position) or some identifying name (a
string), called an associative index.
Example: The array() construct creates an array.
$person = array("Edison", "Wankel", "Crapper");
$creator = array('Light bulb' =>"Edison", 'Rotary Engine' =>"Wankel",
'Toilet' =>"Crapper");
Resource :Many modules provide several functions for dealing with the
outside world. For example, every database extension has at least a function
to connect to the database, a function to send a query to the database, and a
function to close the connection to the database.
Example :$res = database_connect();
database_query($res);
Page 19 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
OR
Solution2:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
OR
Solution 3:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Page 20 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Page 21 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Example :
<?php
class student
{
var $name;
function __construct($name)
{
$this->name=$name;
}
function __destruct()
{
echo "Destructor is executing " .$this->name;
}
}
$s1=new student("xyz");
?>
6. Attempt any TWO of the following 12M
a) Describe form controls – text box, text area, radio button, check box, list 6M
& buttons
Ans. Form Controls : Description of
each control
1. Textbox : A text box is used to enter data. It is a single line input on a web 1M
page.
Tag :<input type=“text”> : It is used to display a text box on a web page.
Attributes of <input> tag used with text box:
name=“ text” : Specify name of text box for unique identification.
maxlength=number : Specify maximum number of characters that can be
accepted in a textbox.
size=number : Specify the width of text box in number of characters.
value=“text” : Specify default text value that appears in the text box when
loaded on a web page.
Example:<input type=“text” name=“n1” maxlength=20 size=15
value=“Enter your name” >
Page 22 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
Attributes:
name=“ text” : Specify name of the element for unique identification.
cols=number : Specify width of the text area.
rows=number : Specify height of the text area.
readonly : Specify a text area as read only element.
Example:<textarea name=“t1” cols=10 rows=10>Enter your
suggestions</textarea>
3. Radio / option button : Radio buttons are used to display multiple options
from which user can select only one option. When a radio button is selected
by user, a dot symbol appears inside button. Multiple option buttons are
group together to allow user to select only one option from the group. A
group can be created by giving same name to all option buttons in that group.
Tag :<input type=“radio”> : It is used to display a radio button on a web
page.
Attributes of <input> tag used with radio button:
name=“ text” : Specify name of radio button for unique identification.
value=“text” : Specify value to be returned to the destination if that radio
button is selected.
checked: Specify default selection
Example:<input type=“radio” name=“r1” value=“male”>male
<input type=“radio” name=“r1” value=“female” checked>female
Page 23 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
iii) Reset button : Reset button is used to clear all elements with their
original state after user clicks on it.
Page 24 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
__call() :In PHP, for function overloading , __call() method is used. This
function is triggered while invoking overloaded methods in the object
context.The $name argument is the name of the method being called.
The $arguments argument is an enumerated array containing the parameters
passed to the $named method.
Example :
<?php
class Shape1 {
const PI1 = 3.142 ;
function __call($name1,$arg1){
if($name1 == 'area1')
switch(count($arg1)){
Page 25 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619
case 0 : return 0 ;
case 1 : return self::PI1 * $arg1[0] ;
case 2 : return $arg1[0] * $arg1[1];
}
}
}
$circle1 = new Shape1();
echo "Area of Circle= ".$circle1->area1(3);
echo "<br><br>";
$rect1 = new Shape1();
echo "Area of Rectangle= ".$rect1->area1(8,6);
?>
ii) Mysqli_connect()
Mysqli_connect() function opens a new connection to the MySQL server.
Syntax :
mysqli_connect(host, username, password, dbname)
Example :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Page 26 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 1 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 2 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 3 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
<?php
session_start();
$_SESSION["username"] = "abc";
?>
2. Attempt any THREE of the following: 12
a) Write down rules for declaring PHP variable 4M
Ans. a. A variable starts with the $ sign, followed by the name of the 1M for
variable. each
b. A variable name must start with a letter or the underscore correct
character. rule, any
c. A variable name should not contain spaces. If a variable name is four rules
more than one word, it should be separated with an underscore can be
($first_name), or with capitalisation ($firstName). considered
d. Variables used before they are assigned have default values.
e. A variable name cannot start with a number.
f. A variable name can only contain alpha-numeric characters (A-
Z, a-z) and underscores.
g. Variable names are case-sensitive ($name and $NAME are two
different variables)
h. Variables can, but do not need, to be declared before
assignment. PHP automatically converts the variable to the
correct data type, depending on its value.
i. Variables in PHP do not have intrinsic types - a variable does
not know in advance whether it will be used to store a number
or a string of characters
b) Write a program to create associative array in PHP. 4M
Ans. <?php 4M for any
$a = array("sub1"=>23,"sub2"=>23,"sub3"=>12,"sub4"=>13); correct
var_dump($a); code for
echo "<br>"; associative
foreach ($a as $x) array
echo "$x<br>";
echo "using for loop<br>";
$aLength= count($a);
echo "Count of elements=$aLength<br>";
for ($i=0;$i<$aLength;$i++)
echo "$a[$i]<br>";
echo "array function extract<br>";
extract($a);
Page 4 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
echo $a1."<br>".$a2."<br>".$a3."<br>".$a4."<br>";
?>
c) Define Introspection and explain it with suitable example. 4M
Ans. Introspection in PHP offers the useful ability to examine an 1M for
object's characteristics, such as its name, parent class (if any) definition
properties, classes, interfaces and methods. 1M for
PHP offers a large number functions that can be used to explanatio
accomplish the above task. n
Following are the functions to extract basic information about 2M for any
classes such as their name, the name of their parent class etc. correct
example
Example:
<?php
class Test
{
function testing_one()
{
return(true);
}
function testing_two()
{
return(true);
}
function testing_three()
Page 5 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
{
return(true);
}
//Class "Test" exist or not
if (class_exists('Test'))
{
$t = new Test();
echo "The class is exist. <br>";
}
else
{
echo "Class does not exist. <br>";
}
//Access name of the class
$p= new Test();
echo "Its class name is " ,get_class($p) , "<br>";
//Aceess name of the methods/functions
$method = get_class_methods(new Test());
echo "<b>List of Methods:</b><br>";
foreach ($method as $method_name)
{
echo "$method_name<br>";
}
?>
Output :
The class is exist.
Its class name is Test
List of Methods:
testing_one
testing_two
testing_three
d) Write difference between get() and post() method of form (Any 4M
four points)
Ans. HTTP GET HTTP POST 1M for
In GET method we cannot send In POST method large each
large amount of data rather amount of data can be correct
limited data is sent because the sent because the request differentiat
request parameter is appended parameter is appended ion, any
into the URL. into the body. four points
Page 6 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Syntax
function functionName() {
code to be executed;
Page 7 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
}
Example
<?php
function writeMsg() {
echo "Welcome to PHP world!";
}
writeMsg(); // call the function
?>
(Any other example can be considered)
b) Explain method overloading with example. 4M
Ans. Function overloading or method overloading is the ability to create 2M for
multiple functions of the same name with different implementations explanatio
depending on the type of their arguments. n
In PHP overloading means the behavior of a method changes 2M for
dynamically according to the input parameter. example
__call() is triggered when invoking inaccessible methods in an
object context.
__callStatic() is triggered when invoking inaccessible methods in a
static context.
__call():
If a class execute __call(), then if an object of that class is called
with a method that doesn't exist then__call() is called instead of that
method.
example:-
<?php
// PHP program to explain function
// overloading in PHP
// Creating a class of type shape
class shape {
// __call is magic function which accepts
// function name and arguments
Page 8 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
// area of circle
case 1:
return 3.14 * $arguments[0];
// Function call
echo($s->area(2));
echo "<br>";
Page 9 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Cookie
Cookie is a small piece of information stored as a file in the user's
browser by the web server. A cookie stores some data temporarily
(until the expiration date has passed).There is no Unique ID
allocated for a Cookie. The cookie data can be accessed using the
$_COOKIE super-global variable. A cookie can be set using the
setcookie() function.
Example optional:-
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["uname"]="Customer1";
$_SESSION["fcolor"]="RED";
echo "The session variable are set with values";
?>
</body>
</html>
d) Explain delete operation of PHP on table data. 4M
Ans. Delete command is used to delete rows that are no longer required 2M for
from the database tables. It deletes the whole row from the table. explanatio
n
The DELETE statement is used to delete records from a table: 2M for
DELETE FROM table_name WHERE some_column = program /
some_value Example
Page 10 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
<?php
$server='localhost';
$username='root';
$password='';
$con=mysqli_connect($server,$username,$password);
if(!$con){
die("Connection to this database failed due to"
.mysqli_connect_error($mysqli));
}
$sql="DELETE FROM student.pridataWHERE name='amit'";
if($con->query($sql)==true){
echo "Record deleted successfully";
}
else{
"ERROR:error".$con->error();
}
$con->close();
?>
Output:-
Page 11 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
OR
<!DOCTYPE html>
<html>
<body>
<H1>Enter five numbers </H1>
<form action = 'sort.php' method = 'post'>
<input type = 'number' name = 'n1' placeholder = 'Number
1...'><br><br>
<input type = 'number' name = 'n2' placeholder = 'Number
2...'><br><br>
<input type = 'number' name = 'n3' placeholder = 'Number
3...'><br><br>
<input type = 'number' name = 'n4' placeholder = 'Number
4...'><br><br>
<input type = 'number' name = 'n5' placeholder = 'Number
5...'><br><br>
<input type = 'submit' value = 'Submit'>
</form>
</body>
</html>
Page 12 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
sort.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$a = array($_POST['n1'], $_POST['n2'], $_POST['n3'],
$_POST['n4'], $_POST['n5']);
sort($a);
}
foreach($a as $i) {
echo $i.' ';
}
?>
(Any other example can be considered)
b) Write PHP program for cloning of an object 4M
Ans. (Any other correct program can be considered) 4M for
Code:- correct
<!DOCTYPE html> program
<html>
<body>
<?php
class car {
public $color;
public $price;
function __construct()
{
$this->color = 'red';
$this->price = 200000;
}
}
$mycar = new car();
$mycar->color = 'blue';
$mycar->price = 500000;
$newcar = clone $mycar;
print_r($newcar);
?>
</body>
</html>
Page 13 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Explanation
The above code creates a car with a constructor which initializes its
member variable named color and price.
An object of the variable is created, and it is cloned to demonstrate
deep cloning.
c) Create customer form like customer name, address, mobile no, 4M
date of birth using different form of input elements & display
user inserted values in new PHP form.
Ans. <!DOCTYPE html>
<html> 4M for
<body> correct and
<form action = 'data..php' method = 'post'> equivalent
<input type = 'text' name = 'name' placeholder = 'Customer code
Name...'><br><br>
<input type = 'text' name = 'address' placeholder =
'Address...'><br><br>
<input type = 'text' name = 'number' placeholder = 'Mobile
Number...'><br><br>
<label> Date of Birth: </label>
<input type = 'date' name = 'dob'><br><br>
<input type = 'submit' value = 'Submit'><br>
</form>
</body>
</html>
data.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo '<html><body><form>
Customer Name: '.$_POST['name'].'<br>
Address: '.$_POST['address'].'<br>
Mobile Number: '.$_POST['number'].'<br>
Date of Birth: '.$_POST['dob'];
}
?>
(Any other correct program logic can be considered)
d) Inserting and retrieving the query result operations 4M
Ans. <?php 2M for
$con = mysqli_connect('localhost', 'root', '', 'class'); inserting
Page 14 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
foreach($result as $r) {
echo $r['roll_number'].' '.$r['name'];
}
?>
Output
Insertion Successful
1 Amit
Explanation
The above code connects with a database named „class‟‟.
The exam database has a table named „user‟ with 2 columns
roll_number and name.
It executes an insert query on the user and checks whether the
insertion was successful or not.
It executes a select query on the user and displays the information
retrieved.
(Any other example can be considered)
Page 15 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
empty() function will ensure that text field is not blank it is with
some data, function accepts a variable as an argument and returns
TRUE when the text field is submitted with empty string, zero,
NULL or FALSE value.
Is_numeric() function will ensure that data entered in a text field is
a numeric value, the function accepts a variable as an argument and
returns TRUE when the text field is submitted with numeric value.
Example:-
Validations for: - name, email, phone no, website url
<!DOCTYPE html>
<body>
<?php
$nerror = $merror = $perror = $werror = $cerror = "";
$name = $email = $phone = $website = $comment = "";
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)* @[a-z0-9-]+(\.[a-z0-9-
]+)*(\.[a-z]{2,3})$^";
Page 16 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
if($_SERVER["REQUEST_METHOD"]=="POST") {
if(empty($_POST["name"])) {
$nerror = "Name cannot be empty!";
}
else {
$name = test_input($_POST["name"]);
if(!preg_match("/^[a-zA-Z-']*$/",$name))
{
$nerror = "Only characters and white spaces allowed";
}
}
if(empty($_POST["email"])) {
$merror = "Email cannot be empty!";
}
else
{
$email = test_input($_POST["email"]);
if(!preg_match($pattern, $email)) {
$merror = "Email is not valid";
}
}
if(empty($_POST["phone"])) {
$perror = "Phone no cannot be empty!";
}
else {
$phone = test_input($_POST["phone"]);
if (!preg_match ('/^[0-9]{10}+$/', $phone)) {
$perror = "Phn no is not valid";
}
}
if(empty($_POST["website"])) {
$werror = "This field cannot be empty!";
}
else {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$werror = "URL is not valid";
}
Page 17 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
}
if (empty($_POST["comment"])) {
$cerror = "";
}
else {
$comment = test_input($_POST["comment"]);
}}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p><span class="error">* required field </span></p>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nerror;?></span><br/><br/>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $merror;?></span><br/><br/>
Phone no: <input type="text" name="phone">
<span class="error">* <?php echo $perror;?></span><br/><br/>
Website: <input type="text" name="website">
<span class="error">* <?php echo $werror;?></span><br/><br/>
Comment: <textarea name="comment" rows="5"
cols="40"></textarea><br/><br/>
<input type="submit" name="submit" value="Submit"></form>
<?php
echo "<h2>Your Input:</h2>";
echo $name; echo "<br>";
echo $email; echo "<br>";
echo $phone; echo "<br>";
echo $website; echo "<br>";
echo $comment;
?>
</body>
</html>
Page 18 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
OR
Example:
<?php
$a=1;
while($a<=5):
echo " Iteration $a";
$a++;
endwhile;
?>
do-while loop:All the statements inside the loop executes for the
first time without checking any condition. The keyword „do‟ passes
the flow of control inside loop. After executing loop for the first
time, expression / condition is evaluated. If it evaluates to true then
all statements inside loop again executes and if it evaluates to false
then loop exits and flow of control passes to the next statement
placed outside the loop. The process of execution and evaluation
continues till expression / condition evaluates to true.
Example:
<?php
$a=1;
Page 19 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
do
{
print("Iteration 1");
$a++;
}while($a<=0);
?>
for each loop: This loop works with arrays and is used to traverse
through values in an array. For each loop iteration, the value of the
current array element is assigned to $value and the array pointer is
moved by one, until it reaches the last array element.
Example :
<?php
$arr=array("Apple","Banana","Orange");
foreach($arr as $fruit)
{
echo("$fruit");
}
?>
b) How do you connect MYSQL database with PHP. 6M
Ans. Using MySQLi Object Interface: 3M for
Page 20 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
<?php Any
$servername = "localhost"; relevant
$username = "root";
$password = "";
statement
$conn = new mysqli($servername, $username, $password); s for
if ($conn->connect_error) { connecti
die("Connection failed: " . $conn->connect_error); ng PHP
} with
echo "Connected successfully"; MySQL
mysqli_close($conn);
database
?>
Explanation:
The first part of the script is three variables (server name,
username, and password) and their respective values. These values 3M for
should correspond to your connection details. explanati
Next is the main PHP function mysqli_connect(). It establishes a
on
connection with the specified database.
When the connection fails, it gives the message Connection failed.
The die function prints the message and then exits out of the script
OR
using MySQLi Procedural interface:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
Page 21 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Explanation:
The first part of the script is three variables (server name,
username, and password) and their respective values. These values
should correspond to your connection details.
Next is the main PHP function mysqli_connect(). It establishes a
connection with the specified database.
When the connection fails, it gives the message Connection failed.
The die function prints the message and then exits out of the script
If the connection is successful, it displays “Connected
successfully.”
Next, write a sql statement to create a database. If connection
established successfully then echo "Database created successfully";
else echo "Error creating database: "
When the script ends, the connection with the database also closes.
If you want to end the code manually, use
the mysqli_close function.
OR
using PDO - PHP Data Object
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try
{
$conn = new PDO("mysql:host=$servername;dbname=myDB",
$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
Page 22 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Explanation:
The first part of the script is three variables (server name,
username, and password) and their respective values. These values
should correspond to your connection details.
If a problem arises while trying to connect, it stops running and
attempts to catch and solve the issue. Catch blocks can be set to
show error messages or run an alternative code.
Following is the setAttribute method adding two parameters to the
PDO:
1. PDO::ATTR_ERRMODE
2. PDO::ERRMODE_EXCEPTION
This method instructs the PDO to run an exception in case a query
fails.
Add the echo “Connected successfully.” to confirm a connection is
established.
Define the PDOException in the catch block by instructing it to
display a message when the connection fails.
c) Create a class as “Percentage” with two properties length & 6M
width. Calculate area of rectangle for two objects.
Ans <?php 3M for
class Percentage correct
{ syntax
public $length; 3M for
public $width; correct
public $a; logic
function area($l,$w)
{
$this->length=$l;
$this->width=$w;
$this->a=$this->length*$this->width;
echo "Area of rectangle = " . $this->a;
}
}
$p1=new Percentage();
Page 23 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
$p1->area(2,3);
$p2=new Percentage();
$p2->area(5,6);
?>
(Any other relevant logic can be considered)
6. Attempt any TWO of the following: 12
a) Write a PHP program to demonstrate use of cookies. 6M
Ans. Cookies can be used to identify user, managing session, etc. 6M for
Setting cookies for human identification: Any PHP
In the code below, two fields name and year are set as cookies on program
user's machine. From the two fields, name field can be used to
identify the user's revisit to the web site.
with
<?php correct
setcookie("name", "WBP", time()+3600, "/","", 0); demonstr
setcookie("Year", "3", time()+3600, "/", "", 0); ation for
?> use of
For the first time when user visits the web site, cookies are stored cookies
on user's machine. Next time when user visits the same page,
cookies from the user's machine are retrieved.
In the code below isset() function is used to check if a cookie is set
or not on the user's machine.
<html>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . " Thanks for
Revisiting"."<br />";
else
echo "First Time Visitor". "<br />";
?>
</body>
</html>
b) Explain any four string functions in PHP with example. 6M
Ans. 1. str_word_count() function: This function is used to count the
number of words in a string. 1M for
syntax : str_word_count(string,return,char); explanati
string : It indicates string to be checked.
return :It is optional. It specifies the return value of the
on &
function. 1/2 M for
correct
Page 24 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
<?php
$str1="Welcome to WBP Theory & practical";
echo " <br> Total words in string str1=
".str_word_count($str1,0,"&");
?>
2. strlen() function : This function is used to find number of
characters in a string . While counting number characters from
string, function also considers spaces between words.
syntax : strlen(string);
- string specify name of the string from which characters
have to be counted.
Example :
<?php
$str3="Hello,welcome to WBP";
echo "<br> Number of characters in a string '$str3' = "
.strlen($str3);
?>
Page 25 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 26 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Example 1:
$str10="Welcome to poly";
$str11=str_replace("poly","msbte",$str10);
echo $str11;
c) i) What is inheritance? 6M
ii) Write update operation on table data.
Ans. Inheritance: It is the process of inheriting (sharing) properties 3M for
and methods of base class in its child class. Inheritance provides re- explanatio
Page 27 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
A derived class can access properties of base class and also can
have its own properties. Properties defined as public in base class
can be accessed inside as well as outside of the class but properties
defined as protected in base class can be accessed only inside its
derived class. Private members of class cannot be inherited.
Example :
<?php
class college
{
public $name="ABC College";
protected $code=7;
}
class student extends college 3M for
{ update
public $sname="s-xyz"; operation
public function display()
{
echo "College name=" .$this->name;
echo "<br>College code=" .$this->code;
echo "<br>Student name=" .$this->sname;
}
}
$s1=new student();
$s1->display();
?>
Page 28 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 29 / 29