[go: up one dir, main page]

100% found this document useful (1 vote)
2K views18 pages

Winter 23 22619

Model answer of winter 23 22619

Uploaded by

dingraritika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2K views18 pages

Winter 23 22619

Model answer of winter 23 22619

Uploaded by

dingraritika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

### Question 1: Attempt any FIVE of the following (10 Marks)

#### (a) List attributes of cookie.

**Marks: 2**

1. **Name**: The name of the cookie.

2. **Value**: The value of the cookie.

3. **Expiry**: The expiration date of the cookie.

4. **Path**: The path on the server where the cookie is available.

5. **Domain**: The domain that the cookie is available to.

6. **Secure**: If true, the cookie will only be transmitted over secure HTTPS connections.

7. **HttpOnly**: If true, the cookie is accessible only through the HTTP protocol and not through
client-side scripts.

#### (b) List different types of arrays.

**Marks: 2**

1. **Indexed Arrays**: Arrays with numeric index.

```php

$colors = array("Red", "Green", "Blue");

```

2. **Associative Arrays**: Arrays with named keys.

```php

$ages = array("Peter" => 35, "Ben" => 37, "Joe" => 43);

```

3. **Multidimensional Arrays**: Arrays containing one or more arrays.

```php

$cars = array(

array("Volvo", 22, 18),

array("BMW", 15, 13),

array("Saab", 5, 2)

);

```

#### (c) Explain cloning object.

**Marks: 2**
Cloning an object creates a shallow copy of the object. The `__clone()` method can be used to modify
the properties of the cloned object if needed.

Example:

```php

class Example {

public $var;

function __clone() {

$this->var = "Cloned object";

$obj1 = new Example();

$obj1->var = "Original object";

$obj2 = clone $obj1;

echo $obj2->var; // Outputs: Cloned object

```

#### (d) State any 2 differences between `for` and `foreach`.

**Marks: 2**

1. **Syntax and Usage**:

- `for`: Used for iterating over a range of values.

```php

for ($i = 0; $i < 10; $i++) {

echo $i;

```

- `foreach`: Specifically used for iterating over arrays.

```php

foreach ($array as $value) {

echo $value;

```
2. **Performance**:

- `for`: More versatile but can be less efficient for array traversal as it requires using an index.

- `foreach`: More efficient for array traversal as it directly accesses the elements without needing
an index.

#### (e) Explain class and object creation.

**Marks: 2**

A class is a blueprint for creating objects. Objects are instances of classes.

Example:

```php

class Car {

public $color;

function setColor($color) {

$this->color = $color;

function getColor() {

return $this->color;

$myCar = new Car();

$myCar->setColor("Red");

echo $myCar->getColor(); // Outputs: Red

```

#### (f) Explain functions. List its types.

**Marks: 2**

Functions are blocks of code that perform specific tasks and can be reused throughout a program.

Types:

1. **User-defined Functions**: Functions created by the user.

```php

function add($a, $b) {

return $a + $b;

}
2. **Built-in Functions**: Functions provided by PHP.

```php

echo strlen("Hello"); // Outputs: 5

```

#### (g) Define MySQL.

**Marks: 2**

MySQL is an open-source relational database management system (RDBMS) that uses Structured
Query Language (SQL) for accessing and managing data. It is widely used for web database
applications. And is the main part of the php programming.

---

### Question 2: Attempt any THREE of the following (12 Marks)

#### (a) Develop a simple program for sending and receiving plain text message.

**Marks: 4**

Sender:

```html

<form action="receive.php" method="post">

Message: <input type="text" name="message">

<input type="submit">

</form>

```

Receiver (`receive.php`):

```php

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$message = $_POST['message'];

echo "Received message: " . htmlspecialchars($message);

?>

```
#### (b) Explain the use of break and continue statement.

**Marks: 4**

- **break**: Exits the current loop or switch statement.

```php

for ($i = 0; $i < 10; $i++) {

if ($i == 5) {

break;

echo $i; // Outputs 0 1 2 3 4

```

- **continue**: Skips the current iteration of the loop and continues with the next iteration.

```php

for ($i = 0; $i < 10; $i++) {

if ($i == 5) {

continue;

echo $i; // Outputs 0 1 2 3 4 6 7 8 9

```

#### (c) Explain constructor and destructor in PHP.

**Marks: 4**

- **Constructor**: Initializes object properties when an object is created.

```php

class MyClass {

public $name;

function __construct($name) {

$this->name = $name;

}
$obj = new MyClass("John");

echo $obj->name; // Outputs: John

```

- **Destructor**: Called when an object is destroyed, used for cleanup tasks.

```php

class MyClass {

public $name;

function __construct($name) {

$this->name = $name;

function __destruct() {

echo "Destroying " . $this->name;

$obj = new MyClass("John");

// When the script ends or $obj is unset, the destructor is called.

```

#### (d) Explain update and delete operations on table data.

**Marks: 4**

- **Update**: Modifies existing records in a table.

Syntax: UPDATE table_name SET field_name=new_value WHERE field_name=existing_value;

```php

$conn = new mysqli("localhost", "username", "password", "database");

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {

echo "Record updated successfully";

} else {

echo "Error updating record: " . $conn->error;

$conn->close();

```
- **Delete**: Removes the specified row with the value and if not specified it deletes the whole
table.

Syntax: DELETE FROM table_name WHERE column_name=value;

```php

$conn = new mysqli("localhost", "username", "password", "database");

$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {

echo "Record deleted successfully";

} else {

echo "Error deleting record: " . $conn->error;

$conn->close();

---

### Question 3: Attempt any THREE of the following (12 Marks)

#### (a) Differentiate between session and cookies.

**Marks: 4**

Session Cookies

Stored on the server Stored on the client's browser

Lasts until the browser is closed or session expires Can be set to expire at a specific time or date

Can store large amounts of data Limited to 4KB per cookie

Less secure, data can be accessed and modified by the


More secure, data is not accessible to the client
client

Suitable for storing sensitive data and user sessions Suitable for storing non-sensitive data and preferences

Data is not sent with every HTTP request Data is sent with every HTTP request

#### (b) List loop control structures. Explain any one loop control structure.

**Marks: 4**

Loop control structures:

1. **for**

2. **while**

3. **do-while**
4. **foreach**

**Explanation of `while` loop**:

```php

$i = 1;

while ($i <= 10) {

echo $i;

$i++;

```

- The `while` loop executes a block of code as long as the specified condition is true. In this example,
it prints numbers from 1 to 10.

#### (c) Explain the operations on string: (i) `strrev()`, (ii) `strpos()`

**Marks: 4**

1. **strrev()**: Reverses a string.

```php

$string = "Hello";

echo strrev($string); // Outputs: olleH

```

2. **strpos()**: Finds the position of the first occurrence of a substring in a string.

```php

$string = "Hello, world!";

echo strpos($string, "world"); // Outputs: 7

```

#### (d) Explain the following: (i) `PDO::__construct()`, (ii) `mysqli_connect()`

**Marks: 4**

1. **PDO::__construct()**: The PDO::__construct() method in PHP is used to create a


new instance of the PDO (PHP Data Objects) class, which represents a connection
between PHP and a database server

```php

$dsn = 'mysql:host=localhost;dbname=testdb';

$username = 'root';

$password = '';
try {

$pdo = new PDO($dsn, $username, $password);

echo "Connected to the database.";

} catch (PDOException $e) {

echo 'Connection failed: ' . $e->getMessage();

```

2. **mysqli_connect()**: Opens a new connection to the MySQL server.

```php

$conn = mysqli_connect("localhost", "username", "password", "database");

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

echo "Connected successfully";

mysqli_close($conn);

```

---

### Question 4: Attempt any THREE of the following (12 Marks)

#### (a) Develop a program to connect PHP with MySQL.

**Marks: 4**

```php

<?php

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);


}

echo "Connected successfully";

$conn->close();

?>

```

#### (b) Develop a PHP program for overriding.

**Marks: 4**

```php

<?php

class ParentClass {

public function display() {

echo "Parent class display method";

class ChildClass extends ParentClass {

public function display() {

echo "Child class display method";

$obj = new ChildClass();

$obj->display(); // Outputs: Child class display method

?>

```

#### (c) Explain procedure to create PDF in PHP. Write example.

**Marks: 4**

To create a PDF in PHP, use the `FPDF` library:

1. Download and include the FPDF library.

2. Create an FPDF object.

3. Add a page.

4. Set the font.


5. Add content.

6. Output the PDF.

Example:

```php

<?php

require('fpdf.php');

$pdf = new FPDF();

$pdf->AddPage();

$pdf->SetFont('Arial', 'B', 16);

$pdf->Cell(40, 10, 'Hello World!');

$pdf->Output();

?>

```

#### (d) Design a web page using following form controls: (i) Radio Button, (ii) Checkbox

**Marks: 4**

```html

<!DOCTYPE html>

<html>

<body>

<form action="submit.php" method="post">

<p>Choose your gender:</p>

<input type="radio" name="gender" value="male"> Male<br>

<input type="radio" name="gender" value="female"> Female<br>

<p>Select your hobbies:</p>

<input type="checkbox" name="hobby" value="reading"> Reading<br>

<input type="checkbox" name="hobby" value="travelling"> Travelling<br>

<input type="submit" value="Submit">

</form>

</body>

</html>

```
#### (e) Explain the following terms: (i) Variables, (ii) Datatypes, (iii) Constants, (iv) Operators

**Marks: 4**

1. **Variables**: Containers for storing data values.

```php

$var = "Hello";

``

2. **Datatypes**: Define the type of data a variable can hold (e.g., Integer, String, Float, Boolean,
Array, Object).

```php

$int = 123; // Integer

$str = "Hello"; // String

```

3. **Constants**: Immutable values declared using the `define()` function.

```php

define("SITE_NAME", "MyWebsite");

echo SITE_NAME; // Outputs: MyWebsite

```

4. **Operators**: Symbols used to perform operations on variables and values (e.g., Arithmetic,
Assignment, Comparison, Logical).

```php

$a = 10;

$b = 5;

$sum = $a + $b; // Arithmetic operator

$isEqual = ($a == $b); // Comparison operator

```

---

### Question 5: Attempt any TWO of the following (12 Marks)

#### (a) Write a PHP program on Introspection.

**Marks: 6**
Introspection is the ability to examine the capabilities of an object at runtime.

```php

<?php

class MyClass {

public $prop1 = "I'm a class property!";

public function display() {

echo "Inside MyClass";

$obj = new MyClass();

// Get the class name

echo get_class($obj); // Outputs: MyClass

// Get the class methods

print_r(get_class_methods('MyClass'));

// Get the class properties

print_r(get_class_vars('MyClass'));

// Get the method's parameters

$reflect = new ReflectionMethod('MyClass', 'display');

print_r($reflect->getParameters());

?>

```

#### (b) List string functions in PHP. Explain any two.

**Marks: 6**

List of string functions:

1. `strlen()`

2. `strrev()`

3. `strpos()`

4. `str_replace()`

5. `substr()`

6. `strtoupper()`
7. `strtolower()`

8. `trim()`

9. `ltrim()`

10. `rtrim()`

Explanation of two functions:

1. **`str_replace()`**: Replaces all occurrences of a search string with a replacement string.

```php

$text = "Hello world!";

echo str_replace("world", "PHP", $text); // Outputs: Hello PHP!

```

2. **`substr()`**: Returns a part of a string.

```php

$text = "Hello world!";

echo substr($text, 6, 5); // Outputs: world

```

#### (c) Write a PHP program to demonstrate session management.

**Marks: 6**

Start a session and set a session variable:

```php

<?php

// Start the session

session_start();

// Set session variables

$_SESSION["username"] = "JohnDoe";

echo "Session variables are set.";

?>

```

Retrieve the session variable:


```php

<?php

// Start the session

session_start();

// Echo session variables that were set on previous page

echo "Username is " . $_SESSION["username"];

?>

```

---

### Question 6: Attempt any TWO of the following (12 Marks)

#### (a) Develop a PHP program to (i) Enter data into database (ii) Retrieve and present data from
database

**Marks: 6**

**(i) Enter data into database:**

```php

<?php

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "database";

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe',
'john@example.com')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";

} else {

echo "Error: " . $sql . "<br>" . $conn->error;

$conn->close();

?>

```

**(ii) Retrieve and present data from database:**

```php

<?php

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "database";

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

$sql = "SELECT id, firstname, lastname FROM MyGuests";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

// Output data of each row

while($row = $result->fetch_assoc()) {

echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";

} else {

echo "0 results";

}
$conn->close();

?>

``

#### (b) Develop a PHP program to create constructor to initialize object of class.

**Marks: 6**

```php

<?php

class MyClass {

public $name;

// Constructor

function __construct($name) {

$this->name = $name;

function getName() {

return $this->name;

$obj = new MyClass("John");

echo $obj->getName(); // Outputs: John

?>

```

#### (c) Develop a PHP program without using string functions: (i) To calculate length of string (ii) To
count the number of words in string

**Marks: 6**

**(i) To calculate length of string:**

```php

<?php

function custom_strlen($string) {

$length = 0;

while (isset($string[$length])) {
$length++;

return $length;

echo custom_strlen("Hello World!"); // Outputs: 12

?>

```

**(ii) To count the number of words in string:**

```php

<?php

function custom_word_count($string) {

$words = 0;

$in_word = false;

for ($i = 0; isset($string[$i]); $i++) {

if ($string[$i] != ' ' && !$in_word) {

$in_word = true;

$words++;

} elseif ($string[$i] == ' ') {

$in_word = false;

return $words;

echo custom_word_count("Hello world! Welcome to PHP."); // Outputs: 5

?>

```

You might also like