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

PHP Practical PDF

The document contains practical PHP exam questions that cover various programming concepts including arithmetic, assignment, comparison, increment, decrement, logical, string, and array operators. It also includes examples of decision-making control structures (if, else, switch) and looping structures (while, do-while, for, foreach), as well as array manipulation and object-oriented programming. Additionally, it provides HTML form examples and data validation techniques.

Uploaded by

dsawant829
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)
2 views

PHP Practical PDF

The document contains practical PHP exam questions that cover various programming concepts including arithmetic, assignment, comparison, increment, decrement, logical, string, and array operators. It also includes examples of decision-making control structures (if, else, switch) and looping structures (while, do-while, for, foreach), as well as array manipulation and object-oriented programming. Additionally, it provides HTML form examples and data validation techniques.

Uploaded by

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

PRACTICAL EXAM QUESTION OF PHP

1) Write a simple PHP program using expressions and using Arithmetic


operators.
<?php
// Simple PHP program using arithmetic operators with
short variable names

$a = 20;
$b = 6;

$sum = $a + $b;
$diff = $a - $b;
$prod = $a * $b;
$quot = $a / $b;
$rem = $a % $b;

echo "a = $a <br>";


echo "b = $b <br>";
echo "Sum = $sum <br>";
echo "Difference = $diff <br>";
echo "Product = $prod <br>";
echo "Quotient = $quot <br>";
echo "Remainder = $rem <br>";
?>
2) Write a simple PHP program using expressions and using Assignment
operators.
<?php
// Simple PHP program using assignment operators

$x = 10;
echo "Initial value of x: $x <br>"; // Output:
10

$x += 5;
echo "After x += 5: $x <br>"; // Output:
15

$x -= 3;
echo "After x -= 3: $x <br>"; // Output:
12

$x *= 2;
echo "After x *= 2: $x <br>"; // Output:
24
$x /= 4;
echo "After x /= 4: $x <br>"; // Output: 6

$x %= 3;
echo "After x %= 3: $x <br>"; // Output: 0
?>
3) Write a simple PHP program using expressions and using Comparison
operators.
<?php
// Using Comparison Operators

$a = 10;
$b = 20;

echo "a = $a, b = $b <br>";


echo "a == b: " . ($a == $b ? "true" : "false") .
"<br>"; // false
echo "a != b: " . ($a != $b ? "true" : "false") .
"<br>"; // true
echo "a > b: " . ($a > $b ? "true" : "false") .
"<br>"; // false
echo "a < b: " . ($a < $b ? "true" : "false") .
"<br>"; // true
echo "a >= b: " . ($a >= $b ? "true" : "false") .
"<br>"; // false
echo "a <= b: " . ($a <= $b ? "true" : "false") .
"<br>"; // true
?>
4) Write a simple PHP program using expressions and using Increment
operators.
<?php
// Using Increment Operators

$x = 5;
echo "Original x: $x <br>"; // 5

echo "Post-increment: " . $x++ . "<br>"; // 5 (then x


becomes 6)
echo "After post-increment x: $x <br>"; // 6

echo "Pre-increment: " . ++$x . "<br>"; // 7


echo "After pre-increment x: $x <br>"; // 7
?>
5) Write a simple PHP program using expressions and using Decrement
operators.
<?php
// Using Decrement Operators

$y = 5;
echo "Original y: $y <br>"; // 5

echo "Post-decrement: " . $y-- . "<br>"; // 5 (then y


becomes 4)
echo "After post-decrement y: $y <br>"; // 4

echo "Pre-decrement: " . --$y . "<br>"; // 3


echo "After pre-decrement y: $y <br>"; // 3
?>
6) Write a simple PHP program using expressions and using Logical operators.
<?php
// Using Logical Operators

$a = true;
$b = false;

echo "a = true, b = false <br>";


echo "a && b: " . ($a && $b ? "true" : "false") .
"<br>"; // false
echo "a || b: " . ($a || $b ? "true" : "false") .
"<br>"; // true
echo "!a: " . (!$a ? "true" : "false") . "<br>";
// false
?>
7) Write a simple PHP program using expressions and using String operators.
<?php
// Using String Operators

$first = "Hello";
$second = "World";

$result = $first . " " . $second; // Concatenation


echo "Concatenated string: $result <br>"; // Output:
Hello World

$first .= " Everyone!";


echo "After .= operator: $first <br>"; // Output:
Hello Everyone!
?>
8) Write a simple PHP program using expressions and using Array operators.
<?php
$arr1 = array("a" => 1, "b" => 2);
$arr2 = array("b" => 2, "a" => 1);
$arr3 = array("a" => "1", "b" => 2);

// Union
$union = $arr1 + $arr2;
echo "Union: ";
print_r($union); // Output: a => 1, b => 2

// Equality
echo "<br>arr1 == arr2: " . ($arr1 == $arr2 ? "true" :
"false") . "<br>"; // true

// Identity
echo "arr1 === arr2: " . ($arr1 === $arr2 ? "true" :
"false") . "<br>"; // false

// Inequality
echo "arr1 != arr3: " . ($arr1 != $arr3 ? "true" :
"false") . "<br>"; // false

// Non-identity
echo "arr1 !== arr3: " . ($arr1 !== $arr3 ? "true" :
"false") . "<br>"; // true
?>
9) Write a PHP program to demonstrate the use of Decision making control
structures using-If statement
<?php
// Using If statement

$number = 10;

if ($number > 0) {
echo "The number is positive.";
}
?>
10) Write a PHP program to demonstrate the use of Decision making control
structures using-If else statement
<?php
// Using If-Else statement
$number = -5;

if ($number > 0) {
echo "The number is positive.";
} else {
echo "The number is negative.";
}
?>
11) Write a PHP program to demonstrate the use of Decision making control
structures using-else if statement
<?php
// Using Else-If statement

$number = 0;

if ($number > 0) {
echo "The number is positive.";
} elseif ($number < 0) {
echo "The number is negative.";
} else {
echo "The number is zero.";
}
?>
12) Write a PHP program to demonstrate the use of Decision making control
structures using-switch statement
<?php
// Using Switch statement

$day = 3;

switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
case 6:
echo "Saturday";
break;
case 7:
echo "Sunday";
break;
default:
echo "Invalid day";
}
?>
13) Write a PHP program to demonstrate the use of Looping structures using-
while statement
<?php
// Using While loop

$count = 1;

while ($count <= 5) {


echo "Count: $count <br>";
$count++;
}
?>
14) Write a PHP program to demonstrate the use of Looping structures using-
do while statement
<?php
// Using Do-While loop

$count = 1;

do {
echo "Count: $count <br>";
$count++;
} while ($count <= 5);
?>
15) Write a PHP program to demonstrate the use of Looping structures using-
for statement
<?php
// Using For loop

for ($i = 1; $i <= 5; $i++) {


echo "Number: $i <br>";
}
?>
16) Write a PHP program to demonstrate the use of Looping structures using-
for each statement
<?php
// Using For-Each loop

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

foreach ($colors as $color) {


echo "Color: $color <br>";
}
?>
17) Write a PHP program for creating and manipulating-Indexed array
<?php
// Creating an indexed array
$fruits = array("Apple", "Banana", "Cherry");

// Accessing elements
echo "First fruit: " . $fruits[0] . "<br>"; // Apple
echo "Second fruit: " . $fruits[1] . "<br>"; // Banana

// Adding a new element


$fruits[] = "Orange"; // Appends Orange to the array
echo "New fruit: " . $fruits[3] . "<br>"; // Orange

// Removing an element
unset($fruits[1]); // Removes Banana
echo "After removal: ";
print_r($fruits); // Array ( [0] => Apple [2] => Cherry
[3] => Orange )
?>
18) Write a PHP program for creating and manipulating-Associative array
<?php
// Creating an associative array
$person = array("name" => "John", "age" => 25, "city"
=> "New York");

// Accessing elements
echo "Name: " . $person["name"] . "<br>"; // John
echo "Age: " . $person["age"] . "<br>"; // 25

// Adding a new key-value pair


$person["country"] = "USA";
echo "Country: " . $person["country"] . "<br>"; // USA
// Removing an element
unset($person["city"]);
echo "After removal: ";
print_r($person); // Array ( [name] => John [age] => 25
[country] => USA )
?>
19) Write a PHP program for creating and manipulating- Multidimensional
array
<?php
// Creating a multidimensional array
$students = array(
"John" => array("age" => 18, "grade" => "A"),
"Jane" => array("age" => 19, "grade" => "B"),
"Doe" => array("age" => 20, "grade" => "A")
);

// Accessing nested array elements


echo "John's age: " . $students["John"]["age"] .
"<br>"; // 18
echo "Jane's grade: " . $students["Jane"]["grade"] .
"<br>"; // B

// Adding a new student


$students["Alice"] = array("age" => 22, "grade" =>
"A");
echo "Alice's age: " . $students["Alice"]["age"] .
"<br>"; // 22
?>
20) Write a PHP program to-Calculate length of string.
<?php
// Calculating length of string
$str = "Hello, World!";
$length = strlen($str);
echo "Length of string: $length <br>"; // 13
?>
21) Write a PHP program to Count the number of words in string without using
string functions.
<?php
// Counting words in a string without using string
functions
$str = "PHP is a popular scripting language";
$words = 0;
$inWord = false;
for ($i = 0; $i < strlen($str); $i++) {
if ($str[$i] != ' ' && !$inWord) {
$words++;
$inWord = true;
} elseif ($str[$i] == ' ') {
$inWord = false;
}
}

echo "Number of words: $words <br>"; // 5


?>
22) Write a PHP program to Inherit members of super class in subclass.
<?php
// Superclass
class Animal {
public $name;
public $age;

public function __construct($name, $age) {


$this->name = $name;
$this->age = $age;
}

public function speak() {


echo "$this->name makes a sound<br>";
}
}

// Subclass
class Dog extends Animal {
public function speak() {
echo "$this->name barks<br>";
}
}

$dog = new Dog("Buddy", 3);


$dog->speak(); // Buddy barks
?>
23) Write a PHP program Create constructor to initialize object of class by
using object oriented concepts.
<?php
// Class with constructor
class Person {
public $name;
public $age;

// Constructor to initialize properties


public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}

// Method to display person details


public function display() {
echo "Name: $this->name, Age: $this->age<br>";
}
}

// Creating object and initializing with constructor


$person1 = new Person("Alice", 30);
$person1->display(); // Name: Alice, Age: 30

$person2 = new Person("Bob", 25);


$person2->display(); // Name: Bob, Age: 25
?>
24) Design a web page using following form controls: a. Text box, b. Radio
button, c. Check box, d. Buttons.
index.html
<html>
<head>
<title>Form Controls Example</title>
</head>
<body>
<h2>User Information Form</h2>
<form method="POST" action="process_form.php">
<!-- Text Box -->
Name: <input type="text" name="name"
placeholder="Enter your name"><br><br>

<!-- Radio Buttons -->


Gender:
<input type="radio" name="gender" value="male">
Male
<input type="radio" name="gender"
value="female"> Female<br><br>

<!-- Checkboxes -->


Hobbies:
<input type="checkbox" name="hobbies[]"
value="Reading"> Reading
<input type="checkbox" name="hobbies[]"
value="Travelling"> Travelling
<input type="checkbox" name="hobbies[]"
value="Coding"> Coding<br><br>

<!-- Buttons -->


<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
</body>
</html>

process_form.php
<?php
// process_form.php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect form data
$name = $_POST['name'];
$gender = $_POST['gender'];
$hobbies = isset($_POST['hobbies']) ?
$_POST['hobbies'] : array();

// Displaying the data


echo "<h3>Submitted Data:</h3>";
echo "Name: $name<br>";
echo "Gender: $gender<br>";

// Display hobbies without using implode


echo "Hobbies: ";
if (count($hobbies) > 0) {
foreach ($hobbies as $hobby) {
echo $hobby . " ";
}
} else {
echo "None";
}
echo "<br>";
}
?>
25) Develop web page with data validation.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Form with Data Validation</title>
</head>
<body>
<h2>User Information Form</h2>
<form method="POST" action="process_form.php">
Name: <input type="text" name="name"
required><br><br>
Email: <input type="email" name="email"
required><br><br>
Phone Number: <input type="tel" name="phone"
required><br><br>
Gender:
<input type="radio" name="gender" value="male"
required> Male
<input type="radio" name="gender"
value="female" required> Female<br><br>
Hobbies:
<input type="checkbox" name="hobbies[]"
value="Reading"> Reading
<input type="checkbox" name="hobbies[]"
value="Travelling"> Travelling
<input type="checkbox" name="hobbies[]"
value="Coding"> Coding<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

process_form.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect form data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$gender = $_POST['gender'];
$hobbies = isset($_POST['hobbies']) ?
$_POST['hobbies'] : [];

// Simple validation and displaying data


if (empty($name) || empty($email) || empty($phone)
|| empty($gender) || empty($hobbies)) {
echo "Please fill all the required
fields.<br>";
} else {
echo "<h3>Submitted Data:</h3>";
echo "Name: $name<br>";
echo "Email: $email<br>";
echo "Phone Number: $phone<br>";
echo "Gender: $gender<br>";
echo "Hobbies: " . implode(", ", $hobbies) .
"<br>";
}
}
?>
26) Write simple PHP program to Set cookies and read it.
set_cookie.php
<?php
// Set a cookie for the user
$name = "user";
$value = "John Doe";
$expireTime = time() + (86400 * 30); // Cookie will
expire in 30 days
$path = "/"; // Available across the entire site

setcookie($name, $value, $expireTime, $path);

if (isset($_COOKIE[$name])) {
echo "Cookie '$name' is already set!<br>";
} else {
echo "Cookie '$name' is not set yet.<br>";
}
?>

<!-- Link to read the cookie -->


<a href="read_cookie.php">Click here to read the
cookie</a>

read_cookie.php
<?php
// Check if the cookie is set
if (isset($_COOKIE["user"])) {
echo "Hello, " . $_COOKIE["user"] . "!<br>";
} else {
echo "Cookie 'user' is not set.<br>";
}
?>

<!-- Link to set the cookie -->


<a href="set_cookie.php">Click here to set the
cookie</a>
27) Develop a simple application to Enter data into database
SQL to Create Database and Table:
CREATE DATABASE userDB;

USE userDB;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
phone VARCHAR(20) NOT NULL
);

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-
width, initial-scale=1.0">
<title>Enter Data into Database</title>
</head>
<body>
<h2>Enter Your Information</h2>
<form method="POST" action="insert_data.php">
Name: <input type="text" name="name"
required><br><br>
Email: <input type="email" name="email"
required><br><br>
Phone: <input type="text" name="phone"
required><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

insert_data.php
<?php
// Database connection details
$servername = "localhost"; // MySQL server (use
'localhost' if it's on the same machine)
$username = "root"; // Database username (default
is 'root' for local servers)
$password = ""; // Database password (default is
empty for local servers)
$dbname = "userDB"; // Database name

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

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn-
>connect_error);
}

// Check if form is submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get form data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];

// Prepare SQL query to insert data into the


users table
$sql = "INSERT INTO users (name, email, phone)
VALUES ('$name', '$email', '$phone')";

// Execute the query


if ($conn->query($sql) === TRUE) {
echo "New record created successfully!";
} else {
echo "Error: " . $sql . "<br>" . $conn-
>error;
}
}

// Close the connection


$conn->close();
?>
28) Develop a simple application to retrieve and present data from database.
SQL to Create Database and Table:
CREATE DATABASE userDB;
USE userDB;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
phone VARCHAR(20) NOT NULL
);

INSERT INTO users (name, email, phone)


VALUES
('John Doe', '[email protected]', '1234567890'),
('Jane Smith', '[email protected]', '9876543210');

view_data.php
<?php
// Database connection details
$servername = "localhost"; // MySQL server (use
'localhost' for local server)
$username = "root"; // Database username (default is
'root' for local servers)
$password = ""; // Database password (default is
empty for local servers)
$dbname = "userDB"; // Database name

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

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn-
>connect_error);
}

// SQL query to retrieve data from users table


$sql = "SELECT id, name, email, phone FROM users";
$result = $conn->query($sql);

// Check if there are results


if ($result->num_rows > 0) {
// Output data of each row
echo "<h2>User Information</h2>";
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>";

while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $row["id"] . "</td>
<td>" . $row["name"] . "</td>
<td>" . $row["email"] . "</td>
<td>" . $row["phone"] . "</td>
</tr>";
}
echo "</table>";
} else {
echo "No data found!";
}

// Close the connection


$conn->close();
?>

You might also like