0% found this document useful (0 votes)
11 views

Practical Exam Questions

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
0% found this document useful (0 votes)
11 views

Practical Exam Questions

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/ 17

Practical exam Questions:

1. Write PHP program to print even numbers upto 10 and sum of them.
Ans:
<?php
$sum=0;
for($i=0; $i<=10;$i+=2){
echo"$i</br>";
$sum+=$i;
}
echo"Sum=$sum";
?>
------
2. Write a PHP program to print prime number upto n.
Ans:
<?php
$count = 0 ;
$number = 2 ;
while ($count <20 )
{
$div_count=0;
for ( $i=1;$i<=$number;$i++)
{
if (($number%$i)==0)
{
$div_count++;
}}
if ($div_count<3)
{
echo $number." , ";
$count=$count+1;
}
$number=$number+1;
}
?>
--------
3) Write PHP program to print reverse of number.
Ans:

<?php
$num = 123;

$revnum = 0;

while ($num> 1)

$rem = $num % 10;

$revnum = ($revnum * 10) + $rem;

$num = ($num / 10);

echo "Reverse number of 123 is: $revnum";

?>

------------------------------------------------

4) Write PHP program to based on multidimensional array.


Ans:

<?php

$array = array(

array(1, 2, 3),

array(4, 5, 6),

array(7, 8, 9)

);

for($i = 0; $i<count($array);$i++)

for($j = 0; $j<count($array[$i]); $j++)

echo $array[$i][$j] ."";

echo "\n";

?>
5) Write PHP program to sort associative and multidimensional array.
Ans:

<?php

// Associative array

$assoc_array = array("apple" => 5, "banana" => 3, "orange" => 7);

asort($assoc_array);

print_r($assoc_array);

// Multidimensional array

$multi_array = array(

array(3, 1, 4),

array(1, 5, 9),

array(2, 6, 5)

);

usort($multi_array, function($a, $b) {

return $a[0] - $b[0];

});

print_r($multi_array);

?>

------------------------------------------------

6) Write PHP program based on interface.


Ans:

<?php

// Interface definition

interface Animal {

public function makeSound();

// Class definitions
class Cat implements Animal {

public function makeSound() {

echo " Meow ";

class Dog implements Animal {

public function makeSound() {

echo " Bark ";

class Mouse implements Animal {

public function makeSound() {

echo " Squeak ";

// Create a list of animals

$cat = new Cat();

$dog = new Dog();

$mouse = new Mouse();

$animals = array($cat, $dog, $mouse);

// Tell the animals to make a sound

foreach($animals as $animal) {

$animal->makeSound();

?>
7) Write PHP program based on introspection.
Ans:

<?php

class Rectangle

var $dim1 = 2;

var $dim2 = 10;

function Rectangle($dim1,$dim2)

$this->dim1 = $dim1;

$this->dim2 = $dim2;

function area()

return $this->dim1*$this->dim2;

function display()

// any code to display info

$S = new Rectangle(4,2);

//get the class varibale i.e properties

$class_properties = get_class_vars("Rectangle");

//get object properties

$object_properties = get_object_vars($S);

//get class methods

$class_methods = get_class_methods("Rectangle");

//get class corresponding to an object


$object_class = get_class($S);

print_r($class_properties);

print_r($object_properties);

print_r($class_methods);

print_r($object_class);

?>

--------------------------------------------

8) Write PHP program based on inheritance.


Ans:

<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

// Strawberry is inherited from Fruit


class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
---------------------------------------

9) Write PHP program based on session variables ,start ,stop.


Ans:

<?php
session_start();

$_SESSION['username'] = 'john_doe';
$_SESSION['email'] = 'john.doe@example.com';

echo "Session started. Variables set.\n";

session_destroy();
echo "Session destroyed.";
?>

10) Write PHP program based on cookies.(isset,name,destroy)


Ans:
<?php
// Setting a cookie
setcookie('username', 'john_doe', time() + 3600);

// Checking if the cookie is set


if(isset($_COOKIE['username'])) {
echo "Cookie 'username' is set to " . $_COOKIE['username'] . "\n";
} else {
echo "Cookie 'username' is not set.\n";
}

// Deleting the cookie


setcookie('username', '', time() - 3600);
echo "Cookie 'username' has been destroyed.";
?>
------------------------------------------------

11) Write PHP program based on create database.


Ans:

<?php
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "CREATE TABLE staff (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50)
)";
if ($conn->query($sql) === TRUE) {
echo "Table staff created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
}
?>

12) Write PHP program based on select a table from database.


Ans:
<?php
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM staff";
$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();
}
?>

13) Write PHP program based to insert data in a table.


<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="insert into staff
values('Aryan','Naik','aryan.naik1905@gmail.com')";
if($conn->query($sql)==true)
{
echo " Value Inserted";
}
else{
echo "value not inserted";
}

?>

14) Write PHP program based to update data from a table.


Ans:
<?php
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE staff SET lastname='technology' WHERE id=1";


if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
?>

15) Write PHP program based to delete data from a table.


Ans;
<?php
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "clg";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "DELETE FROM staff WHERE id=1";


if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
}
?>

16) Write PHP program based on string functions (Any four)


ANS:
<?php
$str="BE KIND";
$str=strtolower($str);
echo $str;
?>
<?php
$str="BE KIND";
$str=strtoupper($str);
echo $str;
?>
<?php
$str="BE KIND";
$str=strrev($str);
echo $str;
?>
<?php
$str="BE KIND";
$str=strlen($str);
echo $str;
?>
--------------------------------------------------------------
17) Write PHP program based on maths functions (Any four)
ANS:
abs() function=
<?php
echo (abs(-7)."<br/>"); // 7 (integer)
?>
ceil() function=
<?php
echo (ceil(3.3)."<br/>");// 4
?>
floor() function=
<?php
echo (floor(3.3)."<br/>");// 3
?>
sqrt() function=
<?php
echo (sqrt(16)."<br/>");// 4
?>
--------------------
18) Write PHP program based on date functions (Any four)
ANS:
<?php
$date = "2023-04-09";

// date()
echo "Current date: " . date("Y-m-d") . "\n";

// strtotime()
echo "Timestamp of $date: " . strtotime($date) . "\n";

// date_create()
$date_obj = date_create($date);
echo "Date object: " . date_format($date_obj, "Y-m-d") . "\n";

// date_diff()
$date1 = date_create("2023-04-09");
$date2 = date_create("2023-05-01");
$diff = date_diff($date1, $date2);
echo "Difference in days: " . $diff->format("%a") . "\n";
?>

1. State the difference between session and cookies.


ANS:
COOKIE SESSION
Cookie are stored in browser as text file Session are stored in server side.
format

The cookie is a clinet side resources. The session is a server side resources.

It is stored limit amount of data. It is stored unlimited amount of data.

It os not holding the variable in cookie. It is holding the multiple variable in session.

Specific identifier links to server. Specific identifier links to user.

2. State the difference between get and post.


GET Method POST Method

GET has limits on the amount of information POST has no limits on the amount of
to send. The limitation is about 2048 information to send.
characters
Can be bookmarked Cannot be bookmarked.

Can be cached Not cached

Parameter remains in browser history. Parameter are not saved in browser history.

Only ASCII characters are allowed. No restrictions Binary data is also allowed.
3. State the difference between for and for each loop.
ANS:
For loop For each loop

The iteration is clearly visible. The block of The iteration is hidden. The block of code is
code is repeated as long as the condition is repeated until iterating over the array is
met or the counter meets a specific value. completed.

Good performance. Better performance.

The stop condition is specified easily. The stop condition has to be explicitly
specified.

Upon working with collections, it needs the It can simply work without the usage of the
usage of the count() function. count() method.

4. Differentiate between implode and explode function.


Ans:
GET Method POST Method

It joins an array of elements into strings. It splits the array based on the separator.

The output type is a string. The output type is an array.

The syntax of implode() function is The syntax of explode() function is


implode($delimiter, $array) explode($delimiter, $string, $limit)

The output example is ‘“ Car”,” Truck”,” Bus”’. The output example is ‘Array ( [0] => Car [1]
=> Truck [2] => Bus )
5. State user defined function and explain with example.
ANS:
 Definition: -
i. A function is a block of code written in a program to perform some specific task.
ii. They take information as parameters, execute a block of statements or perform
operations on these parameters and return the result.
iii. A function will be executed by a call to the function.

 Define User Defined Function in PHP:


A user-defined function declaration starts with the keyword function.
 Syntax
function functionName() {
code to be executed;
}
 Example
<?php
function writeMsg() {
echo "Welcome to PHP world!";
}
writeMsg(); // call the function
?>

6. Explain cloning in php with example.


ANS:
Object Cloning os the process to create a copy of an object.An Object copy is created by
using the magic method.
<!DOCTYPE html>
<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>

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

7. Explain serialization in php with example.

Ans:
i. Serialization is a technique used by programmers to preserve their working
data in format that can later be restored to its previous form.
ii. Serializaling an object means converting it to a byte stream representation
that can be stored in a file.
iii. Serialization in php is mostly automatic, it requires little extra work from
you,beyond calling the serialize() & unserialize functions.

Syntax: Serialize(value1);

Example:
<?php
$s_data= serialize(array('Welcome', 'to', 'PHP'));
print_r($s_data . "<br>");
$us_data=unserialize($s_data);
print_r($us_data);
?>
8. How do you validate user inputs in PHP?
ANS: There are several ways to validate user inputs in PHP:

1. Using built-in PHP functions:


PHP provides several built-in functions for validating user inputs, such as
`filter_var()`, `is_numeric()`, `is_email()`, etc.

2. Using regular expressions:


Regular expressions can be used to validate complex patterns in user inputs, such as
phone numbers, zip codes, or custom formats.

3. Implementing custom validation logic:


You can write your own validation logic to ensure that user inputs meet specific
criteria, such as length, format, or range.

4. Using input sanitization:


Sanitizing user inputs to remove or escape potentially malicious content is an
important part of input validation.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy