Faizan.
Question Bank
Color Code for Difficulty Levels:
*** COMPULSORY - Red (#FF0000)
** V.IMP - Blue (#0000FF)
* IMP - Green (#008000)
Questions for 2M
Write syntax of PHP.
Ans:
<?php
echo "Hello World";
?>
List types of variables.
Ans:Four are scalar (single-value) types: integers, floating-point numbers, strings,
and Booleans.
o Two are compound (collection) types: arrays and objects.
o Two are special types: resource and NULL.
List uses of PHP.(Any Eight)
Ans:
•PHP can be used to develop open-source web applications that are completely
free of cost1 ....
•Due to its platform independence, PHP is used to build web applications that can
run on various operating systems such as UNIX, Windows, and Linux1 ....
Faizan.M
Faizan.M
•PHP is used for web development that requires database connectivity, as it
supports all leading databases including MySQL, ODBC, and SQLite1 ....
•With its strong library support, PHP is used for applications requiring diverse
function modules for data representation2 .
•PHP's user-friendly nature and less steep learning curve make it suitable for
developing web applications that are easy to learn and use1 ....
•Its flexibility allows PHP to be used to combine its functionality with various
other programming languages, making it useful in diverse development scenarios4
.
•PHP is employed to create effective and efficient programming solutions for
web applications1 . Its efficient memory management results in faster processing
speeds, reducing server workload and loading time1 ....
•PHP is one of the tools used for developing secure websites and dynamic web
applications, offering multiple layers of security to prevent threats and malicious
attacks4 ....
•PHP can be used for user identification by setting and retrieving cookies6 .
•PHP is also used for managing user sessions across multiple pages of a website
using sessions and cookies.
What is an array ? How to store data in an array ?
Ans:
Definition: An array is a special type of variable that can store multiple values in a
single reference, allowing efficient data management and retrieval.
Examples:
1. Indexed Array:
php
$colors = array("Red", "Green", "Blue");
Faizan.M
Faizan.M
2. Associative Array:
php
$student_one = array("Maths" => 95, "Physics" => 90, "Chemistry" => 96);
3. Multidimensional Array:
php
$movies = array(
"comedy" => array("Pink Panther", "Johnny English"),
"action" => array("Die Hard", "Inception"),
"epic" => array("The Lord of the Rings") );
Write the use of array_flip().
Ans: The array_flip() function in PHP is used to exchange the keys with their
associated values in an array. If an array has duplicate values, only the last
encountered key will become the value, and the others will be lost.
Write a PHP script to sort any five numbers using the array function.OR Explain
four ways to sort the data.
Ans: <?php $a = array(1, 8, 9, 4, 5); sort($a); foreach($a as $i) { echo $i.' '; } ?>
Define Serialization with Syntax.
Ans: Definition: Serializing an object means converting it to a bytestream
representation that can be stored in a file. Serialization in PHP is mostly automatic,
it requires little extra work from you, beyond calling the serialize() and
unserialize() functions.
Faizan.M
Faizan.M
The serialize() function converts a storable representation of a value. To serialize
data means to convert a value to a sequence of bits so that it can be stored in a file,
a memory buffer, or transmitted across a network.
Syntax: serialize(value);
List different types of arrays.
Ans: •Indexed Arrays: Arrays where elements are accessed using numerical
indices, starting from 0.
•Associative Arrays: Arrays that use strings as keys to access the values, storing
data as key-value pairs.
•Multidimensional Arrays: Arrays where elements of the main array can
themselves be other arrays, allowing for multiple dimensions.
State any 2 differences between for and for each.
Ans:
o For Loop is used to execute a set of statements multiple times using a variable,
condition, and increment/decrement, while foreach loop is used to traverse through
values in an array.
o For Loop is used to execute a set of statements multiple times, whereas foreach
loop is specifically for arrays.
Explain functions. List its types.
Ans:
Definition: A function is a block of code written to perform a specific task. It takes
information as parameters, executes a block of statements, and returns the result. A
function is executed by calling it.
Types of Functions in PHP:
Faizan.M
Faizan.M
o Default Function
o Parameterized Function
o Variable Function
o Lambda (Anonymous) Function
o Arrow Function (Short Closure)
Syntax:
php
function functionName() {
// Code to be executed
Example:
php
<?php
function writeMsg() {
echo "Welcome to PHP World!";
// Call the function
writeMsg();
?>
Define MySQL.
Faizan.M
Faizan.M
Ans: MySQL is a leading database system that PHP supports1 . PHP has built-
in functions that facilitate connecting to and interacting with MySQL databases2 .
The sources demonstrate how to use PHP to connect to a MySQL server3 ... and
perform operations such as creating databases5 ..., inserting data4 ..., retrieving
data4 ..., updating data7 ..., and deleting data
Describe the advantages of PHP.
Ans:
1. Open Source and Free of Cost: People can download it from an open source and
get it for free.
2. Platform Independence: PHP-based applications can run on any OS such as
UNIX, Windows, Linux, etc.
3. Database Connection: It has a built-in database connection that helps to connect
databases.
4. Library Support: PHP has strong library support using which one can utilize
various function modules for data representation.
Enlist the attributes of cookies.OR Syntax for cookies.
Ans: Attributes of Cookies are as follows:
1. name
2. value
3. expire
4. path
5. domain
6. secure
setcookie("cookie_name", "value", time() + 3600);
Faizan.M
Faizan.M
Define GET & POST methods.
Ans:
Faizan.M
Faizan.M
State the use of '$' sign in PHP.
Ans:
The $ sign in PHP is used to indicate a variable. A variable starts with the $ sign,
followed by the name of the variable. Example:
php
$a = 10;
How can we destroy cookies ?
Ans: We can destroy the cookie just by updating the expire-time value
of the cookie by setting it to a past time using the
setcookie() function.
Syntax: setcookie(name, time() - 3600);
List any four data types in MySQL.
Ans:
How to create session variables in PHP ?
Ans: Session variable can be set with a help of a PHP global variable:
$_SESSION.
Data in the session is stored in the form of keys and values pair.
We can store any type of data on the server, which include
arrays and objects.
Faizan.M
Faizan.M
For example, we want to store username in the session so it can
be assessed whenever it is required throughout the session.
<?php
session_start();
$_SESSION["username"] = "abc";
?>
Questions for 4M
Describe the advantages of PHP.
Ans:
1. Open Source and Free of Cost: People can download it from an open source and
get it for free.
2. Platform Independence: PHP-based applications can run on any OS such as
UNIX, Windows, Linux, etc.
3. Database Connection: It has a built-in database connection that helps to connect
databases.
4. Library Support: PHP has strong library support using which one can utilize
various function modules for data representation.
Write down rules for declaring PHP variables.
Ans: a. A variable starts with the $ sign, followed by the variable name.
b. A variable name must start with a letter or an underscore.
c. A variable name cannot start with a number.
d. A variable name can only contain alphanumeric characters and underscores.
Faizan.M
Faizan.M
e. Variable names are case-sensitive ($name and $NAME are two different
variables).
f. Variables do not have intrinsic types; PHP automatically converts them to the
correct type based
on the value assigned.
Example:
php
$firstName = "John"; // String
$age = 25; // Integer
Explain different loops in PHP with examples.
Ans:
1. While Loop: If the expression/condition specified with while evaluates to true,
the statements inside the loop execute, and control is transferred back to the
expression/condition.
Example:
php
<?php
$a = 1;
while ($a <= 5) {
echo "Iteration $a <br>";
$a++;
Faizan.M
Faizan.M
?>
OR
php
<?php
$a = 1;
Faizan.M
while ($a <= 5):
echo "Iteration $a <br>";
$a++;
endwhile;
?>
2. Do-While Loop: All the statements inside the loop execute for the first time
without checking any condition. The keyword do passes the flow of control inside
the loop. After executing the loop for the first time, the expression/condition is
evaluated. If it evaluates to true, all statements inside the loop execute again;
otherwise, the loop exits.
Example:
php
<?php
$a = 1;
do {
echo "Iteration $a <br>";
$a++;
Faizan.M
Faizan.M
} while ($a <= 5);
?>
3. For Loop: The for loop is used when the number of iterations is known in
advance.
Example:
php
<?php
for ($i = 0; $i < 5; $i++) {
echo "Iteration $i <br>";
Faizan.M
?>
4. Foreach Loop: The foreach loop is specifically used for arrays to iterate over
each element.
Example:
php
<?php
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
echo $color . "<br>";
Faizan.M
Faizan.M
?>
List types of variables.Explain any one type in detail with example.
Ans:
PHP provides eight types of values or data types: o Four are scalar (single-value)
types: integers, floating-point numbers, strings, and Booleans.
o Two are compound (collection) types: arrays and objects.
o Two are special types: resource and NULL.
4. Integers: Integers are whole numbers, such as 1, 12, and 256. Integer literals can
be written in decimal, octal, or hexadecimal. Example: $decimal = 1998;
Explain constant with example.
Ans:
In PHP, constants are identifiers that hold a single value. Unlike variables, the
value of a constant cannot be changed during the script's execution. They are
typically defined using the define() function or the const keyword.
Example:
php
<?php
// Defining a constant using define()
define("SITE_NAME", "MyWebsite");
// Defining a constant using const
const PI = 3.14159;
// Displaying constant values
Faizan.M
Faizan.M
echo SITE_NAME . "<br>";
echo "Value of PI: " . PI;
?>
Write a program to create associative arrays in PHP. OR Write a program to create
Multidimensional arrays in PHP.
Ans: 1. Indexed Array:
php
$colors = array("Red", "Green", "Blue");
2. Associative Array:
php
$student_one = array("Maths" => 95, "Physics" => 90, "Chemistry" => 96);
3. Multidimensional Array:
php
$movies = array(
"comedy" => array("Pink Panther", "Johnny English"),
"action" => array("Die Hard", "Inception"),
"epic" => array("The Lord of the Rings") );
Define function. How to define user defined functions in PHP? Give an example.
Ans: A function is a named block of code that performs a specific task. PHP
supports user-defined functions, where the user can define their own functions.
A function doesn't execute when it is defined; it executes when it is called.
The syntax to create a PHP user-defined function: A PHP user-defined function
declaration starts with the keyword function as shown below:
Faizan.M
Faizan.M
php
function functionName($arg1, $arg2, ... $argn)
// Code to be executed inside a function
// return $val;
The syntax to call a PHP user-defined function:
php
$ret = functionName($arg1, $arg2, ... $argn);
Example:
php
<?php
// User-defined function definition
function printMessage() {
echo "Hello, How are you?";
// User-defined function call
printMessage();
?>
As shown in the above program, the printMessage() function is created using the
function keyword. The function prints the message "Hello, How are you?". Later in
the program, when the function is called using printMessage();, it prints the
message, as we can see in the output.
Faizan.M
Faizan.M
Explain any four string functions in PHP with examples.
Ans:
(i) str_replace() (ii) ucwords() (iii) strlen() (iv) strtoupper()
1. str_replace() function: This function is used to replace characters in a string with
other characters.
Syntax:
php
str_replace(findword, replace, string, count);
findword: The word to find in the string.
replace: The word to replace the found word.
string: The string on which the replacement is to be performed.
count: Optional. Indicates the number of occurrences replaced.
Example:
php
<?php
$str = "Welcome to poly";
$newStr = str_replace("poly", "MSBTE", $str);
echo $newStr; // Output: Welcome to MSBTE
?>
2. ucwords() function: This function converts the first character of each word in a
string to uppercase.
Syntax:
php
Faizan.M
Faizan.M
$variable = ucwords($stringvar);
Example:
php
<?php
$str = "welcome to php world";
echo ucwords($str); // Output: Welcome To Php World
?>
3. strlen() function: This function counts the number of characters in a string,
including spaces.
Syntax:
php
strlen(string);
Example:
php
<?php
$str = "Hello, welcome to PHP";
echo "Number of characters: " . strlen($str);
?>
4. strtoupper() function: This function converts all characters in a string to
uppercase.
Syntax:
php
$variable = strtoupper($stringvar);
Faizan.M
Faizan.M
Example:
php
<?php
$str = "polytechnic";
echo strtoupper($str); // Output: POLYTECHNIC
?>
Differentiate between Implode and Explode functions.
Ans:
Explain cloning of an object with example.
Ans:
• The clone keyword is used in PHP to copy an object.
• It does a shallow copy, so any changes made in the cloned object will not affect
the original object.
Faizan.M
Faizan.M
• clone is a magic method in PHP. Magic methods are predefined in PHP and start
with “” (double underscore). They are executed in response to some events in PHP.
Example:
<?php
// Creating an instance of the Animals class
$objAnimals = new Animals();
// Assigning values
$objAnimals->name = "Lion";
$objAnimals->category = "Wild Animal";
// Cloning the original object
$objCloned = clone $objAnimals;
$objCloned->name = "Elephant"; // Modifying the cloned object
// Printing the original object
echo "Original Object: ";
print_r($objAnimals);
// Printing the cloned object
echo "Cloned Object: ";
print_r($objCloned);
?>
Explain method overloading with examples. OR Explain call() with an example.
Ans: Function overloading or method overloading is the ability to create
multiple functions of the same name with different implementations
Faizan.M
Faizan.M
depending on the type of their arguments.
In PHP overloading means the behavior of a method changes
dynamically according to the input parameter.
__call() is triggered when invoking inaccessible methods in an
object context.
__callStatic() is triggered when invoking inaccessible methods in a
static context.
__call():
If a class execute __call(), then if an object of that class is called
with a method that doesn't exist then__call() is called instead of that
method.
example:-
<?php
// PHP program to explain function
// overloading in PHP
// Creating a class of type shape
class shape {
// __call is magic function which accepts
// function name and arguments
function __call($name_of_function, $arguments) {
// It will match the function name
if($name_of_function == 'area') {
switch (count($arguments)) {
Faizan.M
Faizan.M
// If there is only one argument// area of circle
case 1:
return 3.14 * $arguments[0];
// IF two arguments then area is rectangle;
case 2:
return $arguments[0]*$arguments[1];
}}}}
// Declaring a shape type object
$s = new Shape;
// Function call
echo($s->area(2));
echo "<br>";
// calling area method for rectangle
echo ($s->area(4, 2));
?>
Output:
9.426
48
Here the area() method is created dynamically and executed with
the help of magic method __call() and its behavior changes
according to the pass of parameters as object.
(Any other example can be considered)
Faizan.M
Faizan.M
Define Introspection and explain it with suitable examples.
Ans: Introspection is the ability of a program to examine an object's characteristics,
such as its name, parent class (if any), properties, and 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 information at runtime, which makes it possible for us to write
generic debuggers, serializers, profilers, etc.
Example:
<?php class parentclass { 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
exist: "; print_r(method_exists($obj, 'child_fun')); ?>
Explain constructor and destructor in PHP.
Ans:
Constructor:
A constructor is a special built-in method that allows initializing object properties
when an object is created. It executes automatically when an object is created. The
__construct() method starts with two underscores (__).
Syntax:
php
function __construct([argument1, argument2, ..., argumentN]) {
Faizan.M
Faizan.M
// Class initialization code
Example:
<?php
class Student {
var $name;
function __construct($name) {
$this->name = $name;
function display() {
echo $this->name;
}}
$s1 = new Student("John Doe");
$s1->display(); // Output: John Doe
?>
Destructor:
A destructor is the counterpart of a constructor. It is called when the object is
destroyed. A destructor function cleans up any resources allocated to an object.
The __destruct() method starts with two underscores (__).
Syntax:
php
function __destruct() {
// Cleanup code
Faizan.M
Faizan.M
Example:
<?php
class Student {
var $name;
function __construct($name) {
$this->name = $name;
function __destruct() {
echo "Destructor is executing for " . $this->name;
}}
$s1 = new Student("John Doe");
?>
Explain update and delete operations on table data.
Ans: Update operations:
The UPDATE statement is used to change or modify the existing records
in a database table.
SQL query will be formed using the UPDATE statement and WHERE
clause, after that a query will be executed by passing it to the PHPquery()
function to update the tables records.
Example:
The percentage of roll no. C101 will be updated to ‟98.99‟ from student
Faizan.M
Faizan.M
table by using UPDATE statement.
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "UPDATE student SET percent=98.99
WHERE rollno='CO101'";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
?>
Delete operation:
Records can be deleted from a table using the SQL DELETE statement.
SQL query is formed using the DELETE statement and WHERE clause,
after that will be executed by passing this query to the PHP query()
function to delete the tables records.
For example a student record with a roll no. „CO103‟ will be deleted by
using DELETE statement and WHERE clause.
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) die($conn-
>connect_error);
$query = "DELETE from student WHERE rollno='CO103'";
$result = $conn->query($query);
Faizan.M
Faizan.M
if (!$result) die ("Database access failed: " . $conn->error);
?>
Differentiate between session and cookies.OR Define session & cookie. Explain
use of session start.
Ans:
Feature Session Cookie
A way to store information to be A small piece of information
Definition used across multiple pages on a stored as a file in the user's
website1 . browser by the web server2 .
Storage Data is stored on the user's
Data is stored on the server1 ....
Location browser2 .
Stores data temporarily (until
the expiration date has
Data Stores variables until the browser
passed) [20, previous turn]. You
Persistence is closed1 .
can set an expiration time
[previous turn].
Session variables are accessed Cookie data can be accessed
Data
using the $_SESSION super-global using the $_COOKIE super-
Access
variable1 .... global variable2 .
Started using the
Set using the setcookie()
session_start() function1 .... It
Initialization function [6, 20, 38, previous
starts a new or resumes an existing
turn].
session2 .
Can be destroyed by updating
Destroyed using the
the expire-time value to a past
Destruction session_unset() and
time using the setcookie()
session_destroy() functions1 .
function [6, previous turn].
Faizan.M
Faizan.M
Generally more secure as data Generally less secure as data is
resides on the server and is not stored on the user's machine and
Security
directly exposed to the user's can potentially be viewed and
browser. modified by the user.
Typically uses a unique session ID
There is no Unique ID allocated
Unique which is often stored in a cookie on
for a Cookie in the same way as
Identifier the user's browser to maintain the
a session ID2 .
session.
Used to identify user,
Used to store information to be used
managing session, etc.5 . Can
Primary across multiple pages1 . Commonly
be used for website preferences
Uses used for more sensitive data like
or remembering login details
login information [previous turn].
[122, previous turn].
OR
Session
Session is a way to store information to be used across multiple
pages, and session stores the variables until the browser is closed.
To start a session, the session_start() function is used and to destroy
a session, the session_unset() and the session_destroy() functions
are used.
The session variables of a session can be accessed by using the
$_SESSION super-global variable.
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
Faizan.M
Faizan.M
(until the expiration date has passed).There is no Unique ID
allocated for a Cookie. The cookie data can be accessed using the
$_COOKIE super-global variable. A cookie can be set using the
setcookie() function.
Use of Session start
PHP session_start() function is used to start the session. It starts a
new or resumes an existing session. It returns an existing session if
the session is created already. If a session is not available, it creates
and returns a new session.
session_start() creates a session or resumes the current one based
on a session identifier passed via a GET or POST request, or passed
via a cookie.
Example optional:-
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["uname"]="Customer1";
$_SESSION["fcolor"]="RED";
echo "The session variable are set with values";
?>
Faizan.M
Faizan.M
</body>
</html>
Develop a program to connect PHP with MySQL.
Ans: <?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)) { echo "Database created successfully";
} else {
echo "Error creating database: " ;
mysqli_error($conn);
mysqli_close($conn);
?>
Develop a PHP program for overriding.
Ans: <?php
Faizan.M
Faizan.M
class Animal {
public function makeSound() {
echo "The animal makes a sound.\n";
class Cat extends Animal {
// Override the makeSound method
public function makeSound() {
echo "The cat meows.\n";
class Dog extends Animal {
// Override the makeSound method
public function makeSound() {
echo "The dog barks.\n";
$animal = new Animal();
$cat = new Cat();
$dog = new Dog();
$animal->makeSound(); // Output: The animal makes a sound.
$cat->makeSound(); // Output: The cat meows.
$dog->makeSound(); // Output: The dog barks.?>
Faizan.M
Faizan.M
Explain inserting & retrieving the query result operations.
Ans: Insert operation:
Data can be inserted into an existing database table with an INSERT INTO
query.SQL query using the INSERT INTO statement with appropriate values,
after that we will execute this insert query through passing it to the PHP
query() function to insert data in table.
For example a student data is inserted into a table
using INSERT INTO statement.
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "INSERT INTO student(rollno,name,percent) VALUES
('CO103','Reena Patel',98.45)";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
?>
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.
Faizan.M
Faizan.M
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>";
Faizan.M
Faizan.M
echo "</table>";
?>
Write difference between get() & post() method of form (Any four points).
Ans:
Faizan.M