Skip to main

AK#Notes

PHP

1. Expressions and Control Statements in PHP

1. What is web application?

3. What is PHP?

4. Enlist features of PHP.

5. What is variable? How to declare it? Explain with example.

6. Explain constants in PHP with example.

7. What are the decision statements used by PHP?

if statement

.php
<?php
$x = -12;

if ($x > 0) {
  echo "The number is positive";
}

else{
  echo "The number is negative";
}
?>

O/P

The number is negative

if else statement

.php
<?php
$x = "August";

if ($x == "January") {
  echo "Happy Republic Day";
} elseif ($x == "August") {
  echo "Happy Independence Day!!!";
} else {
  echo "Nothing to show";
}
?>

O/P

Happy Independence Day!!!

Nested if statement

.php
<?php
$a = 10;
$b = 20;

if ($a == 10) {
  if ($b == $20) {
      echo "The addiotion is: ".($a + b);
  }
}
?>

O/P

The addition is 30

switch case statement

.php
<?php
$n = "Monday";

switch($n) {
  case "Monday":
    echo "Its Monday";
    break;
  case "Tuesday":
    echo "Its Tuesday";
    break;
  case "Wednesday":
    echo "Its Wednesday";
    break;
  case "Thuesday":
    echo "Its Thuesday";
    break;
  case "Friday":
    echo "Its Friday";
    break;
  case "Saturday":
    echo "Its Saturday";
    break;
  case "Sunday":
    echo "Its Suday";
    break;
  default:
    echo "Doesn't exist";
}
?>

O/P

Its Monday

8. Describe loops in PHP.

while statement

.php
<?php
$num = 0;

while ($num <= 10) {
  echo $num;
  $num++;
}
?>

O/P

012345678910

do while statement

.php
<?php
$x = 1;

do {
  echo "The number is: $x <br>";
  $x++;
} while ($x <= 5);
?>

O/P

The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

for loop

.php
<?php
for ($i = 1; $i <= 10; $i++) {
  echo $i." ";
}
?>

O/P

1 2 3 4 5 6 7 8 9 10

10. Define the term expressions with example.

11. Describe data types in PHP in detail.

12. Explain variable scope in PHP.

13. Write the difference between break and continue statement of PHP with example.

break

continue

16. Find output:

.php
<?php
  $a= "9 Lives." -1;
  var_dump($a);
?>

17. Find the output.

.php
<?php
  $str = "welcome";
  echo "You are $str";
?>

O/P

You are welcome

18. Write program to find a area of rectangle.

.php
<?php
 $length = 14;
 $width = 12;
 echo "area of rectangle is $length * $width= " . ($length * $width) . "<br />";
?>

O/P

area of rectangle is 14 * 12= 168

2. Arrays, Function and Graphics

2. How to create an array? Explain with example.

3. What is string?

4. What is function?

5. How to extract data from array? Explain with example.

6. Enlist types of arrays. Describe with example.

Indexed array

Indexed Arrays are arrays in which the elements are ordered based on index.

.php
<?php
$a = array("Red", "Blue", "Green");
echo "My fav color is: ".$a[0];

O/P

My fav color is: Red

Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.

.php
<?php
$a = array("Red"=>1, "Blue"=>2, "Green"=>3);
echo $a["Red"].$a["Blue"],$a["Green"];

O/P

123

Multidimensional array

A multidimensional array is an array containing one or more arrays.

.php
<?php
$a = array(array("Red", "Blue", "Green"));
echo "My fav color is: ".$a[0][1];

O/P

My fav color is: Blue

8. How to add image in PHP? Explain with example.

.php
<?php
$image = imagecreatetruecolor(500, 300);
imagefilledrectangle($image, 20, 20, 480, 280);
header("Content-type: image/png");
imagepng($image);
?>

14. With the help of example describe traversing of array.

Traversing an array means to visit each and every element of array using a looping structure and iterator functions.

.php
<?php
$a = array(1, 2, 3, 4, 5);
foreach ($a as $n) {
  echo $n;
}

O/P

12345

16. Which operations performed on string in PHP?

18. Explain the following types of functions with example:

(i) User defined functions

A function is a block of statements that can be used repeatedly in a program.

.php
<?php
function func() {
  echo "Hello World";
}

O/P

Hello World

(ii) Variable function

If a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates

.php
<?php
function func() {
  echo "Hello World";
}

$f = "func";
$f();

O/P

Hello World

(iii) Anonymous function.

Anonymous function is a function without any user defined name.

.php
<?php
$func = function () { echo "Hello World"; };
$func();

O/P

Hello World

18. How to create PDF in PHP? Describe with example.

.php
<?php
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(40, 10, "Hello World");
$pdf->Output();
?>

19. How to scaling an image in PHP?

.php
<?php
$image = imagecreatefrompng("image.png");
$img = imagescale($image, 500, 500);
header("Content-type: image/png");
imagepng($img);

20. Explain array_flip() function with example.

3. Apply Object Oriented Concepts in PHP

1. What is OOP?

2. What is object?

5. What is inheritance?

O/P

Hello World
Bye World

6. Describe method overloading with example.

If the derived class is having the same method name as the base class then the method in the derived class takes precedence over or overrides the base class method.

.php
<?php
class First {
  function func() {
    echo "Hello World";
  }
}

class Second extends First {
  function func() {
    echo "Bye World";
  }
}

$o = new Second;
$o->func();

7. Explain sleep and wakeup functions?

__sleep()

__wakeup()

O/P

Obj is serialize()
Obj is unserialize()

__call

O/P

hello
Array ( [0] => "World" )

8. What serialization in PHP?

10. Define method overriding.

O/P

Hello World
Bye World

12. What is object cloning? Describe with example.

13. Define the terms:

(i) Object

Objects are the things you create out of a class.

(ii) Class

A class is what you use to define the properties, methods and behavior of objects.

(iii) Inheritance

(iv) Constructor.

16. Differentiate between constructor and destructor.

O/P

Class Created
Class Destroyed

17. Compare object and class.

18. How to examine classes in introspection? Explain with example.

O/P

class exists
Is object
Obj2
Array ( [0] => func )
Array ( [hello] => world )
Obj

Examining an Object

O/P

1
Obj
1
1

4. Creating and Validating forms

1. What is form? How to create it?

What is form?

How to create it?

2. What is form control?

3. Write short note on: Server role.

5. When to use GET and POST method.

GET

POST

7. What is cookie? How to create it? Explain with example.

What is cookie?

How to create it?

Example

.php
<?php
setcookie("name", "Jonney", time() + (86400 * 30), "/");
if (isset($_COOKIE["name"])) {
  echo "Name: ".$_COOKIE["name"];
}

O/P

Name: Jonney

8. What is session? Explain with example.

9. How we can get the cookie values and destroy the cookies?

To get cookie value.

.php
<?php
setcookie("name", "Jonney", time() + (83400 * 30), "/");

if ( isset($_COOKIE["name"]) ) {
  echo "Name: ".$_COOKIE["name"];
}
?>

To destroy the cookie.

.php
<?php
setcookie("name", "", time() - 3600, "/");
?>

11. What is form validation? Explain with suitable example.

14. How to send e-mail? Describe with example.

O/P

Message is sent.

5. Database Operations

1. What is database?

2. What is DBMS?

3. What is MySQL? How it is used in PHP?

4. How to create and delete a database in MySQL?

O/P

  Created database

5. Explain mysqli_connect() function with example.

7. Write a program to create an employee table to perform insert, delete and update operations.

.php
<?php
// Connect MySQL
$conn = mysqli_connect("localhost", "root", "", "test");
if (!$conn) {
  echo "Error: ".mysqli_error($conn);
}

// Create table
$table = "CREATE TABLE employee(id INT(4), name VARCHAR(22), salary INT(4))";
if (!mysqli_query($conn, $table)) {
  echo "Can't create table.";
}
echo "Created table<br/>";

// Insert data
$insert = "INSERT INTO employee(id, name, salary) VALUES (1, 'Sam', 3200), (2, 'Jonney', 4500), (3, 'Jone', 2000)";
if (!mysqli_query($conn, $insert)) {
  echo "Can't insert data.";
}

// Dalete data
$delete = "DELETE FROM employee WHERE id=2";
if (!mysqli_query($conn, $delete)) {
  echo "Can't delete data.";
}

// Retrive data
$retrive = "SELECT * FROM employee";
$result = mysqli_query($conn, $retrive);

if (mysqli_num_rows($result)) {
  while ($row = mysqli_fetch_assoc($result)) {
    echo "Name: ".$row['name'].", Salary: ".$row['salary'].", ID: ".$row['id']."</br>";
  }
}
?>

PHP

Attempt any FIVE :

(a) Describe advantage of PHP.

(b) What is array ? How to store data in array ?

(c) List types of inheritance.

(d) How can we destroy cookies ?

(e) List any four data types in MySQL.

(f) Write syntax of PHP.

.php
<?php
$hello = "Hello World";
?>

(g) How to create session variable in PHP ?

A session is a way to store information in variables to be used across multiple pages.

.php
<?php
session_start();

$_SESSION["color"] = "Red";
$_SESSION["animal"] = "Cat";
echo $_SESSION["color"]." ".$_SESSION["animal"];
?>

2. Attempt any THREE :

(a) Write down rules for declaring PHP variable.

(b) Write a program to create associative array in PHP.

Associative arrays are arrays that use named keys that you assign to them.

.php
<?php
$a = array("Red"=>1, "Blue"=>2, "Green"=>3);
echo $a["Red"].$a["Blue"],$a["Green"];

O/P

123

(c) Define Introspection and explain it with suitable example.

O/P

class exists
Is object
Obj2
Array ( [0] => func )
Array ( [hello] => world )
Obj

(d) Write difference between get( ) & post( ) method of form (Any four points).

GET

POST

3. Attempt any THREE :

(a) Define function. How to define user defined function in PHP ? Give example.

A function is a block of statements that can be used repeatedly in a program.

.php
<?php
function func() {
  echo "Hello World";
}

O/P

Hello World

(b) Explain method overloading with example.

If the derived class is having the same method name as the base class then the method in the derived class takes precedence over or overrides the base class method.

.php
<?php
class First {
  function func() {
    echo "Hello World";
  }
}

class Second extends First {
  function func() {
    echo "Bye World";
  }
}

$o = new Second;
$o->func();

(c) Define session & cookie. Explain use of session start.

What is cookie?

How to create it?

Example

.php
<?php
setcookie("name", "Jonney", time() + (86400 * 30), "/");
if (isset($_COOKIE["name"])) {
  echo "Name: ".$_COOKIE["name"];
}

O/P

Name: Jonney

Session

(d) Explain delete operation of PHP on table data.

O/P

  Created database

4. Attempt any THREE :

(a) Write PHP script to sort any five numbers using array function.

.php
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>

Output:

BMW
Toyota
Volvo

(b) Write PHP program for cloning of an object.

.php
<?php
class Obj {
  public $name;
}

$o = new Obj;
$c = clone $o;

$o->name = "Jonney";
$c->name = "Jone";

echo "Origenal: ".$o->name.", Clone: ".$c->name;
?>

Output:

Origenal: Jonney, Clone: JOne

(c) Create customer form like customer name, address, mobile no, date of birth using different form of input elements & display user inserted values in new PHP form.

.php
<form action="<?php 1_SELF_PHP ?>" method="post">
  Name:
  <input type="text" name="name">
  Sex:
  <input type="radio" name="sex" value="male">Male</input>
  <input type="radio" name="sex" value="female">Female</input>
  Vehical:
  <input type="checkbox" name="vehicle[]" value="bike">Bike</input>
  <input type="checkbox" name="vehicle[]" value="car">Car</input>
  <input type="checkbox" name="vehicle[]" value="scooter">Scooter</input>
  <button name="submit">Submit</button>
</form>

<?php
if ( isset($_POST["submit"]) ) {
  echo $_POST["name"]." is ".$_POST["sex"]." will travel by ";
  foreach ($_POST["vehicle"] as $selected) {
    echo $selected." ";
  }
}
?>

(d) Inserting and retrieving the query result operations.

.php
<?php
$server= "localhost";
$user = "root";
$password = "";
$db = "feedback";
// Create connection
$conn = new mysqli($server, $user, $password, $db);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = INSERT INTO data VALUES('ashok','you are awesome bro');
[if](if) ($conn->query($sql) === TRUE)
{
echo "feedback sucessfully submitted";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

(e) How do you validate user inputs in PHP ?

.php
<form action="<?php $_PHP_SELF ?>" method="post">
  Name:<input type="text" name="name" required>
  <input type="submit">
</form>

<?php
  if (!preg_match("/^[a-zA-Z_ ]*$/", $_POST["name"])) {
    echo "Only letter and whitespace is allowed";
  }
?>

5. Attempt any TWO :

(a) Explain different loops in PHP with example.

while statement

.php
<?php
$num = 0;

while ($num <= 10) {
  echo $num;
  $num++;
}
?>

O/P

012345678910

do while statement

.php
<?php
$x = 1;

do {
  echo "The number is: $x <br>";
  $x++;
} while ($x <= 5);
?>

O/P

The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

for loop

.php
<?php
for ($i = 1; $i <= 10; $i++) {
  echo $i." ";
}
?>

O/P

1 2 3 4 5 6 7 8 9 10

(b) How do you connect MySQL database with PHP.

.php
<?php
  // Creating connection
  $conn = mysqli_connect("localhost", "root", "", "test");

  // Checking connection
  if (!$conn) {
      die("Connection failed.");
  }
  echo "Connected successfully";
?>

(c) Create a class as "Percentage" with two properties length & width. Calculate area of rectangle for two objects.

.php
<?php
class Rectangle {
  public $width = 0;
  public $height = 0;

  function setSize($w = 0, $h = 0) {
    $this->width = $w;
    $this->height = $h;
  }

  function getArea() {
    return ($this->width * $this->height);
  }

  function getPerimeter() {
    return ( ($this->width + $this->height) * 2 );
  }

  function isSquare() {
    if ($this->width == $this->height) {
       return true;
     } else {
        return false;
     }
  }

}

6. Attempt any TWO :

(a) Write a PHP program to demonstrate use of cookies.

How to create it?

Example

.php
<?php
setcookie("name", "Jonney", time() + (86400 * 30), "/");
if (isset($_COOKIE["name"])) {
  echo "Name: ".$_COOKIE["name"];
}

O/P

Name: Jonney

(b) Explain any four string functions in PHP with example.

(c) What is inheritance?

O/P

Hello World
Bye World

(ii) Write update operation on table data.

.php
<?php
// Connect MySQL
$conn = mysqli_connect("localhost", "root", "", "test");
if (!$conn) {
  echo "Error: ".mysqli_error($conn);
}

// Create table
$table = "CREATE TABLE employee(id INT(4), name VARCHAR(22), salary INT(4))";
if (!mysqli_query($conn, $table)) {
  echo "Can't create table.";
}
echo "Created table<br/>";

// Insert data
$insert = "INSERT INTO employee(id, name, salary) VALUES (1, 'Sam', 3200), (2, 'Jonney', 4500), (3, 'Jone', 2000)";
if (!mysqli_query($conn, $insert)) {
  echo "Can't insert data.";
}

// Dalete data
$delete = "DELETE FROM employee WHERE id=2";
if (!mysqli_query($conn, $delete)) {
  echo "Can't delete data.";
}

// Retrive data
$retrive = "SELECT * FROM employee";
$result = mysqli_query($conn, $retrive);

if (mysqli_num_rows($result)) {
  while ($row = mysqli_fetch_assoc($result)) {
    echo "Name: ".$row['name'].", Salary: ".$row['salary'].", ID: ".$row['id']."</br>";
  }
}
?>

1. Write a PHP program using expressions and operator (ternary operator, arithmetic operators and comparison operators)

.php
<?php
  echo 1 > 2 ? 1 : 2;
  echo "<br>";
  echo 1 + 2;
?>

O/P

2
3

2. Write a PHP program to the use of decision making and control structures using:

if statement

.php
<?php
$x = 1;
if ($x > 0) {
  echo "The number is positive";
}

O/P

The number is positive

if else statement

.php
<?php
$x = "August";

if ($x > 0) {
  echo "The number is positive";
} else {
  echo "The number is negative";
}
?>

O/P

Happy Independence Day!!!

if elseif if statement

.php
<?php
$x = "August";

if ($x > 0) {
  echo "The number is positive";
} elseif ( $x < 0 ) {
  echo "The number is negative";
} else {
  echo "The value is not number";
}
?>

O/P

The number is positive

switch case statement

.php
<?php
$n = "Monday";

switch($n) {
  case "Monday":
    echo "Its Monday";
    break;
  case "Tuesday":
    echo "Its Tuesday";
    break;
  case "Wednesday":
    echo "Its Wednesday";
    break;
  case "Thuesday":
    echo "Its Thuesday";
    break;
  case "Friday":
    echo "Its Friday";
    break;
  case "Saturday":
    echo "Its Saturday";
    break;
  case "Sunday":
    echo "Its Suday";
    break;
  default:
    echo "Doesn't exist";
}
?>

O/P

Its Monday

3. Write a PHP program to the use of looping structure using:

while statement

.php
<?php
$num = 0;

while ($num <= 10) {
  echo $num;
  $num++;
}
?>

O/P

012345678910

do while statement

.php
<?php
$x = 1;
do {
  echo $x;
  $x++;
} while ($x <= 5);
?>

O/P

12345

for statement

.php
<?php
for ($i = 1; $i <= 10; $i++) {
  echo $i;
}
?>

O/P

12345678910

4. Write a PHP program to the use of looping structure using for statement, for each statement.

for statement

.php
<?php
for ($x = 0; $x <= 5; $x++) {
  echo $x;
}
?>

O/P

012345

foreach statement

.php
<?php
$a = array("Hello", "World");

foreach ($a as $b) {
  echo $b." ";
}
?>

O/P

Hello World

5. Write a PHP program for creating and manipulating , associative array and multidimensional array.

Indexed array

.php
<?php
$a = array("Red", "Blue", "Green");
echo "My fav color is: ".$a[0];
?>

O/P

My fav color is: Red

Associative arrays

.php
<?php
$a = array("Red"=>1, "Blue"=>2, "Green"=>3);
echo $a["Red"].$a["Blue"],$a["Green"];
?>

O/P

123

Multidimensional array

.php
<?php
$a = array(array("Red", "Blue", "Green"));
echo "My fav color is: ".$a[0][1];
?>

O/P

My fav color is: Blue

6. Write a PHP program to calculate

Length of string

.php
<?php
  echo strlen("Hello world!");
?>

O/P

12

Count the no of words in string

.php
<?php
  echo str_word_count("Hello world!");
?>

O/P

2

Compare two string using string function.

.php
<?php
  echo strcmp("Hello world!", "Hello world");
?>

O/P

0

7. Write a PHP program using following string function:

8. Write a PHP program to use: and anonymous function.

User define function

.php
<?php
  function writeMessage() {
    echo "Welcome to PHP world";
  }
  writeMessage();
?>

O/P

Welcome to PHP world

Variable function

.php
<?php
  function writeMessage() {
    echo "Welcome to PHP world";
  }

  $w = "writeMessage";
  $w();
?>

O/P

Welcome to PHP world

Anonymous function

.php
<?php
  $a=function() { echo "Anonymous function"; };
  $a();
?>

O/P

Anonymous function

9. Write a PHP program to create PDF document by using graphics concept.

.php
<?php
  require('fpdf.php');
  $pdf = new FPDF();
  $pdf->AddPage();
  $pdf->SetFont('Arial','B',16);
  $pdf->Cell(40,10,'Hello World!');
  $pdf->Output();
?>

O/P

Hello World

10. Write a PHP program

a) To inherit member of superclass in subclass

.php
<?php
class Class1 {
  function func() {
    echo "Hello World";
  }
}

class Class2 extends Class1 {
  function echo() {
    echo "Bye World";
  }
}

$o = new Class2;
$o->func();
$o->echo();
?>

O/P

Hello World
Bye World

b) Create constructor to initialize object of class by using object oriented concept.

.php
<?php
class Obj {
  public function __construct($name, $surname) {
    $this->name=$name;
    $this->surname=$surname;
  }
  public function showName() {
    echo "My name is ".$this->name." ".$this->surname;
  }
}

$sid=new Obj("Aman","Varma");
$sid->showName();
?>

O/P

My name is Aman Varma

11. Write a PHP program on

Introspection

.php
<?php
if (!class_exists("Obj")) {
  echo "Class don't exists."
}
?>

O/P

Class don't exists

Serialization.

.php
<?php
echo serialize(array("Red"));
?>

O/P

a:1:{i:0;s:3:"Red";}

12. Design a web page using following form controls:

13. Design a web page using following form controls:

14. Develop a web page with data validation.

.php
<form action="<?php $_PHP_SELF ?>" method="post">
  Name:<input type="text" name="name" required>
  <input type="submit">
</form>

<?php
  if (!preg_match("/^[a-zA-Z_ ]*$/", $_POST["name"])) {
    echo "Only letter and whitespace is allowed";
  }
?>

15. Write a PHP program to:

Create cookies

.php
<?php
setcookie("name", "Jone", time() + (86400 * 30), "/");
?>
<?php
if (isset($_COOKIE["name"])) {
  echo "Name: ".$_COOKIE["name"];
}
?>

O/P

Name: Jone

16. Write a PHP program to:

O/P

Red Lion

17. Write a PHP program for sending and receiving plain text message (sending email).

.php
<?php
  $status = mail("AnzenKodo@altmail.com", "Title", "Hello World");
  if ($status) {
    echo "Mail is sent.";
  } else {
    echo "Mail can't be sent";
  }
?>

18. Write a PHP program to

Create database

.php
<?php
// Create connection
$conn = mysqli_connect("localhost", "root", "", "test");
// Check connection
if ($conn->connect_error) {
  die("Connection failed.");
}

// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
  echo "Database created successfully";
} else {
  echo "Error creating database";
}

mysqli_close($conn);
?>

Creation of table.

.php
<?php
// Create connection
$conn = mysqli_connect("localhost", "root", "", "test");
// Check connection
if (!$conn) {
  die("Connection failed");
}

// sql to create table
$sql = "CREATE TABLE MyGuests(id INT(6))";

if (mysqli_query($conn, $sql)) {
  echo "Table MyGuests created successfully";
} else {
  echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

19. Write a PHP program to Inserting and retrieving the query result operations and Update ,Delete operations on table data.

.php
<?php
// Connecting to MySQL
$conn = mysqli_connect("localhost", "root", "", "test");
if (!$conn) {
  die("Error: ".mysqli_error($conn));
}

// Inserting data
$sql = "INSERT INTO my_table(id, name) VALUES (1, 'Jone'), (2, 'Jonney)";
if (!mysqli_query($conn, $sql)) {
  die("Error");
}

// Retrieving data
$sql = "SELECT * FROM my_table";
if ($result = mysqli_query($conn, $sql)) {
  if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_array($result)) {
      echo "ID: ".$row["id"].", Name: ".$row["name"];
    }
  } else {
    echo "Rows can't be zero";
  }
} else {
  die("Error: ".mysqli_error($conn));
}

// Update data
$sql = "UPDATE my_table SET name='tim' WHERE id=2";
if (!mysqli_query($conn, $sql) {
  die("Error");
}

// Delete data
$sql = "DELETE FROM my_table WHERE id=1";
if (!mysqli_query($conn, $sql) {
  die("Error"));
}

mysqli_close();
?>

22619 - Web Based Application development with PHP

Q.1) Attempt any FIVE of the following. (10 Marks)

a) List any four advantages of PHP?

  1. PHP is open source and free from cost.
  2. It is platform independent.
  3. PHP based application can run on any OS like UNIX, Linux and Windows, etc
  4. Easy to learn.
  5. Has built-in database connection modules.

b) State the use of str_word_count along with its syntax.

c) Define serialization.

d) Write the syntax for creating Cookie.

e) Write syntax of Connecting PHP Webpage with MySQL.

f) Define GET and POST methods.

GET

POST

g) State the use of $ sign in PHP.

Q.2) Attempt any THREE of the following. (12 Marks)

a) Write a program using foreach loop.

.php
<?php
  //declare array
  $season = array ("Summer", "Winter", "Autumn", "Rainy");
  //access array elements using foreach loop
  foreach ($season as $element) {
    echo "$element";
    echo "</br>";
  }
?>

Output:

Summer
Winter
Autumn
Rainy

b) Explain Indexed and Associative arrays with suitable example.

Indexed arrays

Indexed array: An array having only integer keys is typically referred to as an indexed array and index arrays can store numbers, drinks and any object but their index will be represented by number.

Example:

.php
<?php
  // Define an indexed array
  $colors = array("Red", "Green", "Blue");
  // Printing array structure
  print_r($colors);
?>

Output:

Array ( [0] => Red [1] => Green [2] => Blue )

Associative arrays

The associative arrays are very similar to numeric arrays in terms of functionality but they are different in terms of their index. Associative arrays will have their index as string so that you can establish a strong association between key and values.

.php
<?php
  // Define an associative array
  $ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
  // Printing array structure
  print_r($ages);
?>

Output:

Array ( [Peter] => 22 [Clark] => 32 [John] => 28 )

c) Define Introspection and explain it with suitable example.

PHP Introspection is the ability of a program to examine an object's characteristics such as its name, parent class (if any), properties and methods.

Introspection in PHP offers a useful Ability to examine classes' interfaces properties methods. With introspection we can write code that operates on any object or class.

Example:

.php
<?php
  if (class_exists('MyClass')) {
    $myclass = new MyClass();
  }
?>

d) Differentiate between Session and Cookies.

SESSION COOKIES
Session are stored in server side Cookies are stored in client browser.
Session is server resource. Cookies are client-side resource.
It stores unlimeted data. It stores limited data.
It holds multiple variables. It doen't hold multiple variables.
Session values can't accessed easily. Cookies values can accessed easily.
It is more secure. It is less secure.

Q.3) Attempt any THREE of the following. (12 Marks)

a) Differentiate between implode and explode functions.

No. Implode Explode
1 The implode() function returns a string from the elements of an array. explode function breaks a string into smaller parts and stores it as an array.
2 The implode() function accepts its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments. The explode() function splits these strings based on a specific delimiter and returns an array that contains elements which are sustained by the splitting operation.
3 syntax :-string implode (pieces) array explode (delimiter, string, limit)
4 Example: php <?php $arr = array("I", "love", "PHP."); $pole = implode(" ", $arr); \ echo "$pole"; ?> Output: I love PHP. Example: <?php $string = "I love php."; $pole = explode(" ", $string); \ \ print_r($pole); ?> Output: Array ( [0] => I [1] => love [2] => php. )

b) Write a program for cloning of an object.

.php
<?php
class Obj {
  public $name;
}

$o = new Obj;
$c = clone $o;

$o->name = "Jonney";
$c->name = "Jone";

echo "Origenal: ".$o->name.", Clone: ".$c->name;
?>

Output:

Origenal: Jonney, Clone: JOne

c) Define session and explain how it works.

d) Write Update and Delete operations on table data.

Q.4) Attempt any THREE of the following. (12 Marks)

a) State the variable function.Explain it with example.

PHP supports the concept of variable function means that we can call a function based on a value of a variable if a variable name has a round parentheses appended to it PHP will look for a function with the same name as a whatever variable Evaluates to and will attempt to execute it.

Example:

.php
<?php
  function add($x, $y){
    echo $x + $y;
  }
  $var =  "add";
  $var(10,20);
?>

Output:

30

b) Explain the concept of Serialization with example.

A string representation of any object in the form of byte-stream is obtained by serialize() function in PHP. All property variables of the object are contained in the string and methods are not saved. This string can be stored in any file.

Example:

.php
<?php
echo serialize(array("Red"));
?>

O/P

a:1:{i:0;s:3:"Red";}

c) Answer the following:

i) Get session variables

ii) Destroy session.

Q.5) Attempt any TWO of the following. (12 Marks)

a) Explain any three data types used in PHP.

  1. Integer: integer data type used to specify a numeric value without a fractional component the range of integers.
  2. Strings: a string is a sequence of characters where characters are the same as a byte.
  3. Boolean: boolean value can be either true or false both are case-insensitive.

b) Write a program to connect PHP with MySQL.

.php
<?php
$conn = mysqli_connect("mydb", "root", "root");
if ($conn) {
	echo "Connection Successful";
} else {
	echo "Connection Unsuccessful";
}

O/P

Connction Successful

c) Explain the concept of overriding in detail.

In function overriding, both parent and child classes should have the same function name with and number of arguments. It is used to replace the parent method in child class.

.php
<?php
class ParentClass {
  function helloWorld() {
    echo "Parent";
  }
}
class ChildClass extends ParentClass {
  function helloWorld() {
    echo "Child";
  }
}
$p = new ParentClass;
$c = new ChildClass;
$p->helloWorld();
$c->helloWorld();
?>

Output:

Parent
Child

Q.6) Attempt any TWO of the following. (12 Marks)

a) Explain web page validation with example.

b) Write a program to create PDF document in PHP.

.php
<?php
  require('fpdf.php');
  $pdf = new FPDF();
  $pdf->AddPage();
  $pdf->SetFont('Arial','B',16);
  $pdf->Cell(40,10,'Hello World!');
  $pdf->Output();
?>

c) Elaborate the following:

i) __call()

ii) mysqli_connect()

Table of Content