0% found this document useful (0 votes)
5 views13 pages

QB UT2 Solution

The document is a question bank for Unit Test 2 covering various PHP concepts including constructors, introspection, inheritance, cloning, database operations, form handling, and session management. It provides definitions, examples, and syntax for each topic, illustrating how to implement these concepts in PHP. Key topics include the role of constructors, types of inheritance, database CRUD operations, and the use of superglobal variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views13 pages

QB UT2 Solution

The document is a question bank for Unit Test 2 covering various PHP concepts including constructors, introspection, inheritance, cloning, database operations, form handling, and session management. It provides definitions, examples, and syntax for each topic, illustrating how to implement these concepts in PHP. Key topics include the role of constructors, types of inheritance, database CRUD operations, and the use of superglobal variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Question Bank for Unit Test 2

1. State the role of constructor.


 A constructor is a special function in PHP classes that is automatically called when an
object of the class is created.
 It is mainly used to initialize object properties and set up the environment for the object.
 The constructor function in PHP is defined using __construct().
 Example:
class Car {
public $brand;
public function __construct($brand) {
$this->brand = $brand;
}
public function displayBrand() {
echo "The car brand is " . $this->brand;
}
}
$car1 = new Car("Toyota");
$car1->displayBrand(); // Outputs: The car brand is Toyota
This example demonstrates how a constructor initializes an object property automatically when an
object is created.
2. Define Introspection. Explain it with suitable example.
 Introspection in PHP refers to the ability to examine classes, methods, and properties at
runtime.
 It allows developers to dynamically inspect object details, making debugging and reflection
easier.
 Functions like get_class(), get_methods(), get_object_vars(), and property_exists() help
achieve introspection.
Example:
class Example {
public $name;
public function show() {
return "Hello";
}
}
$obj = new Example();
echo "Class: " . get_class($obj) . "<br>";
print_r(get_class_methods($obj));
This example fetches the class name and methods at runtime, showing how introspection can be
used in PHP.
3. What is inheritance? List all types and explain any one.
 Inheritance in PHP allows a class to acquire properties and methods from another class.
 The class that inherits is called a child class, and the class being inherited from is the parent
class.
 This promotes code reuse and modularity.
 Types of Inheritance:
o Single Inheritance
o Multiple Inheritance (via Traits)
o Multilevel Inheritance
o Hierarchical Inheritance
Example of Single Inheritance:
class Animal {
public function sound() {
echo "Animals make sounds";
}
}
class Dog extends Animal {
public function bark() {
echo "Dog barks";
}
}
$dog = new Dog();
$dog->sound(); // Outputs: Animals make sounds
$dog->bark(); // Outputs: Dog barks
Single inheritance allows the Dog class to inherit the sound() method from the Animal class while
having its own method bark().

4. Write syntax to create class and object in PHP.


class MyClass {
public $name = "ABC";
public function display() {
echo "Hello, " . $this->name;
}
}
$obj = new MyClass();
$obj->display();
This example creates a class MyClass with a property and method, instantiates an object, and calls
the method.
5. Explain cloning of an object.

 In PHP, cloning an object means creating a duplicate (copy) of an existing object.


 However, objects in PHP are passed by reference, meaning if you assign an object to
another variable, both variables will point to the same object.
 Cloning ensures that a new, independent object is created with the same properties.
 To achieve cloning, PHP provides the clone keyword.
 When you clone an object, PHP automatically copies all properties of the original object
into a new one.
 If the class has a __clone() method, it is automatically called on the newly created object.
This allows modifying the cloned object if needed.
 Syntax: $newObject = clone $existingObject;
Example:
class Demo {
public $value = 100;
}
$obj1 = new Demo();
$obj2 = clone $obj1;
$obj2->value = 200;
echo "Original Value: " . $obj1->value . "<br>"; //100
echo "Cloned Value: " . $obj2->value; // 200
Here, modifying $obj2 does not affect $obj1, showing how cloning works.
6. List Database operations and explain any one with example.
Database operations in PHP using MySQL include:
1. Creating a Database
2. Creating Tables
3. Inserting Data
4. Retrieving Data (SELECT)
5. Updating Data
6. Deleting Data
Example: Retrieving Data (SELECT Query)
The SELECT query is used to fetch records from a database table.
<?php
$conn = new mysqli("localhost", "root", "", "my_database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>";
}
} else {
echo "No records found";
}
$conn->close();
?>
This query retrieves all records from the users table and displays them.
7. Explain the webpage having multiple forms.
 A web page having multiple forms can be processed in two steps:
o Posting each form to a different PHP script file for processing: Multiple
functionality can be provided in a single web page by providing multiple forms in
a web page having different functionality.
o Each form on this web page will be given a separate name that will uniquely
identify the form in the web page with multiple forms.
 Data from each form should be given to a separate PHP script file for processing by
specifying PHP script filename in the action attribute of the form.
 Each PHP script should be written in such a fashion that will handle all the data coming
from the form.
 Disadvantage - we have to write separate files for each form.
<form method="post">
<h3>personal information form</h3>
user name:<input type="text" name="username"/><br/><br/>
address:<input type="text" name="address"/><br/><br/>
<input type="submit" name="submit_personal_info" value="submit"/> <br/>
</form>
<form method="post">
<h3>Feedback Form</h3>
<textarea name="feedback" rows="5" cols="50"></textarea><br/>
<input type="submit" name="submit_feedback"/>
</form>
<?php
if(!empty($_POST['submit_personal_info']))
echo "<h3>welcome user:".$_POST['username']."</h3>";
if(!empty($_POST['submit_feedback']))
{
echo "<h3>we value your feedback:</h3>";
echo "your feedback is<br/>".$_POST["feedback"];
}
?>
8. State role of GET and POST method.
GET method:
 The GET method sends the encoded user information appended to the page request (to the
url). The code and the encoded information are separated by the ‘?’ character.
 http://www.test.com/index.htm?name1=value1&name2=value2
 The GET method produces a long string that appears in our server logs, in the browser’s
location:box.
 Never use the GET method if we have a password or other sensitive information to be sent
to the server. Get cannot be used to send binary data, like images or word documents, to
the server.
 The data sent by the GET method can be accessed using the QUESRY_STRING
environment variable.
 PHP provides a $_GET associative array to access all the sent information using the GET
method.
POST method:
 The POST method transfers information via HTTP headers. The information is encoded as
described in the case of the GET method and put into a header called QUERY_STRING.
 The POST method does not have any restriction on data size to be sent.
 The POST method can be used to send ASCII as well as binary data.
 The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
 The PHP provides a $_POST associative array to access all the sent information using the
POST method.

9. What is super global variables? List it and write the use of it.
Superglobals are built-in PHP variables that are always accessible, regardless of scope.
List of Superglobal Variables:
1. $_GET – Retrieves data sent via GET method.
2. $_POST – Retrieves data sent via POST method.
3. $_REQUEST – Combines both $_GET and $_POST.
4. $_SESSION – Stores session variables.
5. $_COOKIE – Stores cookies.
6. $_SERVER – Provides server and execution environment information.
7. $_FILES – Handles file uploads.
8. $_ENV – Stores environment variables.
Example: Using $_SERVER to get server details
echo $_SERVER['PHP_SELF']; // Outputs the current script name
echo $_SERVER['SERVER_NAME']; // Outputs the server name
10. Write syntax to create a class and object in PHP.
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 methods go inside the braces. An object is an instance of a class.
Syntax:
class class_name
{
//Block of Code
}
$object = new class_name();

Example:
class Car {
public $brand;
public function setBrand($brand) {
$this->brand = $brand;
}
public function getBrand() {
return $this->brand;
}
}
$car1 = new Car();
$car1->setBrand("Toyota");
echo $car1->getBrand();

11. What is method overriding?


 Method overriding in PHP allows a child class to redefine a method inherited from the
parent class.
 This means the child class provides its own implementation of a method, replacing the
behavior of the parent class method with the same name.
Key Rules for Method Overriding:
1. The method name in the child class must be the same as in the parent class.
2. The method in the child class must have the same parameters as the parent method.
3. The child class method replaces the parent method when called from an object of the child
class.
4. If needed, the overridden method from the parent class can still be accessed using
parent::methodName().
12. Write steps to create database using PHP.
Creating a database in PHP involves connecting to MySQL, executing SQL queries, and handling
errors. Below are the steps to create a database using PHP:
Step 1: Establish a Connection to MySQL
Before creating a database, we need to establish a connection with the MySQL server using PHP’s
mysqli or PDO.
Step 2: Create a Database
Once connected, use the SQL CREATE DATABASE statement to create a new database.
Step 3: Select and Use the Created Database
Once a database is created, we need to select it before creating tables or inserting data.
$conn = mysqli_connect("localhost", "root", "", "myDatabase");
Step 4: Create a Table in the Database
After selecting the database, we can create tables using CREATE TABLE SQL query.
Step 5: Insert Sample Data
Once the table is created, we can insert records into it.
13. Explain queries to update and delete data in database.

Once data is inserted into a database, we often need to modify or remove records. The UPDATE
and DELETE queries in SQL allow us to make these changes.

1. UPDATE Query: It is used to modify existing records in a table.


Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
 table_name: The name of the table where data needs to be updated.
 SET: Specifies the columns and their new values.
 WHERE: Defines the condition to identify which rows should be updated.
<?php
$conn = mysqli_connect("localhost", "root", "", "myDatabase");
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
$sql = "UPDATE users SET email='[email protected]' WHERE id=1";
if (mysqli_query($conn, $sql))
echo "Record updated successfully";
else
echo "Error updating record: " . mysqli_error($conn);
mysqli_close($conn);
?>
2. DELETE Query: It is used to remove one or more records from a table.
Syntax: DELETE FROM table_name WHERE condition;
 table_name: The name of the table from which records should be deleted.
 WHERE: Defines the condition to identify which rows should be deleted. Without
WHERE, all records will be deleted!
<?php
$conn = mysqli_connect("localhost", "root", "", "myDatabase");
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
$sql = "DELETE FROM users WHERE id=2";
if (mysqli_query($conn, $sql))
echo "Record deleted successfully";
else
echo "Error deleting record: " . mysqli_error($conn);
mysqli_close($conn);
?>

14. State and explain any four form controls to get users input in PHP.
 Text Field: A text input field allows the user to enter a single line of text. Textbox field
enable the user to input text information to be used by the program.
 Text Area: A text area field is similar to a text input field but it allows the user to enter
multiple line of text.
 Radio Button (<input type="radio">) – Selects one option from multiple choices.
 Dropdown (<select>) – Presents a list of options.
 File Upload (<input type="file">) – Uploads files.
Example:
<form method="post" enctype="multipart/form-data">
Name: <input type="text" name="name"><br>
Gender: <input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br>
Country: <select name="country">
<option value="India">India</option>
<option value="USA">USA</option>
</select><br>
Upload Resume: <input type="file" name="resume"><br>
<input type="submit">
</form>
15. Describe i) Start session ii) Get session variables iii) Modify session variables iv)
Delete session
What is a Session in PHP?

 A session in PHP is used to store user information (like login credentials, shopping cart
items, or preferences) across multiple pages.
 Unlike cookies, session data is stored on the server, making it more secure.
 Steps to Work with Sessions:
o Start a session → session_start();
o Store session variables → $_SESSION['key'] = 'value';
o Retrieve session variables → $_SESSION['key'];
o Modify session variables → Change the value of $_SESSION['key']
o Destroy a session → session_unset(); session_destroy();

i) Start a Session in PHP


Before using session variables, you must start a session using session_start(). This function must
be called at the beginning of the script before any HTML output.
Example: Starting a Session
<?php
session_start(); // Start a new session or resume an existing one
$_SESSION["username"] = "Abc"; // Store data in session variable
$_SESSION["role"] = "Admin"; // Another session variable
echo "Session has been started and values are set.";
?>
Explanation:
session_start(); starts a session or resumes an existing session. $_SESSION["username"] =
"ABC"; creates a session variable. The session is now active and can store user-specific data.
ii) Get (Access) Session Variables
Once a session is started, session variables can be accessed on any page of the website.
Example: Retrieving Session Variables
<?php
session_start(); // Resume session
echo "Username: " . $_SESSION["username"] . "<br>";
echo "Role: " . $_SESSION["role"];
?>
Explanation:
The session variables $_SESSION["username"] and $_SESSION["role"] are retrieved. Even if the
user navigates to another page, these values remain available.
iii) Modify Session Variables
Session variables can be updated by assigning new values to the existing $_SESSION keys.
Example: Modifying a Session Variable
<?php
session_start(); // Resume session
$_SESSION["username"] = "Xyz"; // Modify session variable
echo "Updated Username: " . $_SESSION["username"];
?>

Explanation:

$_SESSION["username"] is changed from "Abc" to "Xyz". Any subsequent page using this
session variable will now display "Xyz".
iv) Delete (Destroy) a Session
When a session is no longer needed, it can be cleared or completely destroyed.
1. Remove a Specific Session Variable
<?php
session_start();
unset($_SESSION["username"]); // Remove only "username" session variable
echo "Username session variable has been removed.";
?>
2. Destroy the Entire Session
<?php
session_start();
session_unset(); // Unset all session variables
session_destroy(); // Completely destroy the session
echo "Session has been destroyed.";
?>

16. List any four datatypes in MYSQL.


 INT – Stores integers.
 VARCHAR – Stores strings.
 DATE – Stores dates.
 TEXT – Stores large text.
17. How can you send e – mail using php?

 PHP provides a built-in function called mail() to send emails directly from a server.
 Additionally, external libraries like PHPMailer can be used for advanced features such as
attachments, authentication, and sending emails via SMTP (Simple Mail Transfer
Protocol).
 The mail() function is the simplest way to send emails in PHP. It takes the following
parameters: mail(to, subject, message, headers, parameters);
Example: Sending a Basic Email
<?php
$to = "[email protected]"; // Recipient's email
$subject = "Welcome to PHP Mail!";
$message = "Hello, this is a test email sent from PHP.";
$headers = "From: [email protected]";
if(mail($to, $subject, $message, $headers)) {
echo "Email successfully sent to $to";
} else {
echo "Email sending failed.";
}
?>
$to → Recipient's email address.
$subject → The subject of the email.
$message → The body of the email.
$headers → The sender's email (From field).
mail() → Sends the email and returns true if successful, otherwise false.
 Limitations of mail():
o Requires a proper mail server setup on the hosting server.
o No authentication (SMTP authentication is not supported).
o Emails may land in the spam folder.
 To send an email with attachments, use addAttachment() in PHPMailer.

$mail->addAttachment('file.pdf'); // Attach a file


$mail->send();

 Sending an HTML EmailTo send an HTML-formatted email, set isHTML(true).

$mail->isHTML(true);
$mail->Subject = 'HTML Email Example';
$mail->Body = '<h1>Hello!</h1><p>This is an HTML email.</p>';
$mail->send();
 Sending Emails with CC & BCC
o CC (Carbon Copy): Sends a copy of the email to additional recipients.
o BCC (Blind Carbon Copy): Sends a copy without showing the recipients.
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');
$mail->send();

SMTP Server Settings for Different Providers


Provider SMTP Server Port Security
Gmail smtp.gmail.com 587 TLS
Yahoo smtp.mail.yahoo.com 587 TLS
Outlook smtp.office365.com 587 TLS
Zoho Mail smtp.zoho.com 587 TLS

Note: Gmail and other providers require App Passwords instead of real passwords for security.

18. Explain what a cookie is. How can we create, modify, and destroy cookies?

 A cookie is a small piece of data that a web server stores on the client’s browser.
 It is used to remember user preferences, login information, or track user behavior.
 Cookies in PHP are stored as key-value pairs and can persist even after the user closes
the browser (depending on expiration time).
 Creating a Cookie: We use the setcookie() function to create a cookie in PHP.
Syntax: setcookie(name, value, expire, path, domain, secure, httponly);
Parameter Description
name Name of the cookie (string)
value Value to store in the cookie
expire Expiration time (timestamp in seconds)
path URL path where cookie is accessible (default: "/")
domain The domain where the cookie is available
secure true if cookie should be sent only over HTTPS
httponly true if cookie should be accessible only via HTTP (not JavaScript)

 Retrieving (Reading) a Cookie: Once a cookie is set, it can be accessed using the
$_COOKIE superglobal array.
 Modifying a Cookie: To modify a cookie, simply use setcookie() with the same name but
a new value.
 Deleting (Destroying) a Cookie in PHP: To delete a cookie, set its expiration time to a past
date using setcookie().
Example:
<?php
// Step 1: Set a cookie
setcookie("user", "abc", time() + (86400 * 7), "/");

// Step 2: Retrieve a cookie


if (isset($_COOKIE["user"])) {
echo "User: " . $_COOKIE["user"] . "<br>";
} else {
echo "Cookie not set.<br>";
}

// Step 3: Modify a cookie


setcookie("user", "bcd", time() + (86400 * 7), "/");
echo "Cookie updated!<br>";

// Step 4: Delete a cookie


setcookie("user", "", time() - 3600, "/");
echo "Cookie deleted!";
?>

Output:

User: abc
Cookie updated!
Cookie deleted!

You might also like