PHP & MYSQL 2023/2024 (Regular) Solved Question Paper
Time: 2 Hrs | Max. Marks: 60
Section - A
I. Answer any TEN questions of the following. (2x10=20)
1. Write a simple PHP script to display 'Hello World'.
<?php
echo "Hello World";
?>
(Outputs “Hello World”)
2. What is the difference between '= =' and '= = =' operators in PHP.
==
(Loose comparison): Checks only value equality
Example:5 == "5"
→true
===
(Strict comparison): Checks value AND type
Example:5 === "5"
→false
3. How do you check the datatype in PHP? Give example.
Use gettype()
or is_*() or var_dump()
function.
$var = "Hello"; echo gettype($var); // Outputs "string" var_dump(is_int($var)); // Outputs bool(false)
4. Explain for each loop in PHP with syntax and suitable example.
Syntax:
foreach ($array as $value) {
// code
}
Example:
$colors = ["Red", "Green", "Blue"]; foreach ($colors as $color) { echo $color . "<br>"; }
5. Define 'echo' and 'print' in PHР.
echo
: Outputs one or more strings; faster; no return value.print
: Outputs a string; returns1
; slightly slower.
echo
: Can output multiple strings, no return value
Example:echo "Hello", " World";
print
: Outputs single string, returns 1
Example:print "Hello";
6. Define associative array with example.
An array with named keys.
$student = [ "name" => "John", "age" => 20, "grade" => "A" ]; echo $student["name"]; // Outputs "John"
7. Mention any two date and time functions.
date()
: Formats timestamp
Example:echo date("Y-m-d");
strtotime()
: Converts string to timestamp
Example:echo strtotime("next Monday");
8. Define function in PHP.
A reusable block of code defined using the function
keyword.
function greet() {
echo "Hello!";
}
9. How do you pass arguments by reference in PHP functions?
Use &
before the parameter name.
function addOne(&$num) {
$num++;
}
10. List the statements that are used to connect PHP with MYSQL with example.
mysqli_connect()
– To establish a connection.mysqli_connect_error()
– To check for connection errors.mysqli_close()
– To close the connection.
Example:
<?php
// Connection variables
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
// Close connection
mysqli_close($conn);
?>
11. List any two advantages of Laravel.
Built-in authentication and authorization.
Uses MVC architecture, making code more organized.
Eloquent ORM – Simplifies database operations
Blade Templating – Clean separation of PHP/HTML
12. What is composer in Laravel?
Composer is a dependency manager for PHP used to install Laravel and manage its packages.
Dependency management tool
Handles package installation/autoloading
Manages Laravel framework itself
Section - B
II. Answer any FOUR from the following questions, each carries 5 marks (4x5=20)
13. Write a PHP script that demonstrates the use of comparison and logical operators. Include comments to explain each operation.
<?php
$a = 10;
$b = 5;
// Equal (==) - Checks if values are equal (type may differ due to loose comparison)
var_dump($a == $b); // bool(false), because 10 != 5
// Identical (===) - Checks if values and types are the same
var_dump($a === $b); // bool(false), because types match but values differ
// Not Equal (!= or <>) - Checks if values are different
var_dump($a != $b); // bool(true), because 10 is not equal to 5
// Not Identical (!==) - Checks if values or types differ
var_dump($a !== $b); // bool(true), because values are different
// Greater Than (>) - Checks if left value is greater than right
var_dump($a > $b); // bool(true), because 10 > 5
// Less Than (<) - Checks if left value is smaller than right
var_dump($a < $b); // bool(false), because 10 is not less than 5
// Greater Than or Equal (>=)
var_dump($a >= $b); // bool(true), because 10 >= 5
// Less Than or Equal (<=)
var_dump($a <= $b); // bool(false), because 10 is not <= 5
// Logical Operators Example
$x = true;
$y = false;
// Logical AND (&& or "and") - True only if both operands are true
var_dump($x && $y); // bool(false), because $y is false
// Logical OR (|| or "or") - True if at least one operand is true
var_dump($x || $y); // bool(true), because $x is true
// Logical NOT (!) - Inverts the boolean value
var_dump(!$x); // bool(false), because $x is true (NOT true = false)
// XOR (Exclusive OR) - True only if one operand is true (not both)
var_dump($x xor $y); // bool(true), because only $x is true
?>
Explanation of Operations:
Comparison Operators:
==
(Equal) → Checks value equality (ignores data type if loosely compared).===
(Identical) → Checks value + type equality.!=
/<>
(Not Equal) → True if values are different.!==
(Not Identical) → True if values or types differ.>
,<
,>=
,<=
→ Numeric comparisons.
Logical Operators:
&&
/and
→ True only if both conditions are true.||
/or
→ True if at least one condition is true.!
→ Inverts the boolean (true → false, false → true).xor
→ True only if one condition is true (but not both).
14. What are string functions in PHP? Describe four common functions with examples.
String functions in PHP are built-in functions used to perform operations on string values, such as modifying, analyzing, or formatting them. PHP provides a wide variety of string functions for tasks like measuring string length, converting case, replacing text, searching substrings, and more.
$str = "Hello World";
echo strlen($str); // Output: 11
$text = "Welcome to PHP"; echo substr($text, 0, 7); // Output: "Welcome" echo substr($text, 8); // Output: "to PHP"
$str = "HELLO PHP";
echo strtolower($str); // Output: hello php
$str = "php is fun";
echo strtoupper($str); // Output: PHP IS FUN
$str = "I love Java";
echo str_replace("Java", "PHP", $str); // Output: I love PHP
15. Explain any five array functions with suitable examples.
PHP provides a wide range of array functions to create, modify, and retrieve information from arrays.
$fruits = array("Apple", "Banana", "Mango"); $user = array("name" => "John", "age" => 25); print_r($fruits); /* Output: Array ( [0] => Apple [1] => Banana [2] => Mango ) */
$colors = ["Red", "Green", "Blue"]; echo count($colors); // Output: 3
$stack = ["A", "B"]; array_push($stack, "C", "D"); print_r($stack);
Output: Array ( [0] => A [1] => B [2] => C [3] => D )
$colors = ["red", "green", "blue"];
array_pop($colors);
print_r($colors);
Output: Array ( [0] => red [1] => green )
$arr1 = ["a", "b"]; $arr2 = ["c", "d"]; $result = array_merge($arr1, $arr2); print_r($result);
Output: Array ( [0] => a [1] => b [2] => c [3] => d )
$userIds = [101 => "Alice", 102 => "Bob", 103 => "Charlie"]; $key = array_search("Bob", $userIds); echo $key;
Output: 102
$animals = ["cat", "dog", "elephant"];
echo in_array("dog", $animals) ? "Found" : "Not found";
Output: Found
$person = ["name" => "John", "age" => 30, "city" => "New York"];
$keys = array_keys($person);
print_r($keys);
Output: Array ( [0] => name [1] => age [2] => city )
16. How would you fetch and display all records from a 'user' table in PHP? Explain with suitable examples. (Hint: include connection statements).
To fetch and display records from a database table in PHP.
- Establish a database connection
Prepare and execute a SQL query
Fetch the results
Display them in your preferred format
Example:
<?php
// 1. Database Connection
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// 2. SQL Query to fetch all records from 'user' table
$sql = "SELECT * FROM user";
$result = $conn->query($sql);
// 3. Check if records exist and display them
if ($result->num_rows > 0)
{
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Registration Date</th>
</tr>";
// 4. Fetch and display each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["id"]."</td>
<td>".$row["name"]."</td>
<td>".$row["email"]."</td>
<td>".$row["reg_date"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "0 results found";
}
// Close connection
$conn->close();
?>
17. Describe five key features of the Laravel framework that make it popular among developers.
Laravel is a powerful and elegant PHP framework designed for web application development. It follows the MVC (Model-View-Controller) architecture and offers a clean, readable syntax.
Laravel is one of the most popular PHP frameworks due to its elegant syntax, robust features, and developer-friendly tools.
1. Eloquent ORM (Object-Relational Mapping)
Laravel’s Eloquent ORM provides an intuitive, ActiveRecord-based way to interact with databases.
Allows developers to work with database records as objects, simplifying CRUD operations.
Supports relationships (e.g., one-to-many, many-to-many) and advanced querying with minimal SQL code.
2. Blade Templating Engine
Blade is a lightweight yet powerful templating engine that enables dynamic content rendering.
Supports template inheritance, components, and directives for cleaner, reusable views.
Compiled into plain PHP for optimal performance.
3. Artisan CLI (Command-Line Interface)
Laravel includes a built-in command-line tool called Artisan for automating repetitive tasks.
Can generate boilerplate code (controllers, models, migrations), run migrations, and clear caches.
Supports custom command creation for project-specific tasks.
4. Built-in Authentication & Authorization
Laravel provides a simple, out-of-the-box authentication system (login, registration, password reset).
Authorization policies and gates allow fine-grained control over user permissions.
Reduces the need for manual security implementations.
5. Robust Ecosystem (Laravel Forge, Vapor, Nova, etc.)
Laravel offers tools like Forge (server management), Vapor (serverless deployment), and Nova (admin panel).
Includes Laravel Sail for Docker-based local development and Laravel Horizon for Redis queue management.
Section - C
III. Answer any TWO from the following questions, each carries 10 marks (2x10=20)
18. a) Write a PHP program to implement simple calculator operation.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Simple Calculator in PHP</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } .calculator { max-width: 300px; padding: 20px; border: 1px solid #ccc; border-radius: 5px; } input, select, button { margin: 5px 0; padding: 8px; width: 100%; } button { background-color: #4CAF50; color: white; border: none; cursor: pointer; } button:hover { background-color: #45a049; } .result { margin-top: 10px; font-weight: bold; } </style> </head> <body> <div class="calculator"> <h2>Simple Calculator</h2> <form method="post"> <input type="number" name="num1" placeholder="Enter first number" required> <select name="operation" required> <option value="">Select operation</option> <option value="add">Addition (+)</option> <option value="subtract">Subtraction (-)</option> <option value="multiply">Multiplication (*)</option> <option value="divide">Division (/)</option> </select> <input type="number" name="num2" placeholder="Enter second number" required> <button type="submit" name="calculate">Calculate</button> </form> <?php if (isset($_POST['calculate'])) { $num1 = $_POST['num1']; $num2 = $_POST['num2']; $operation = $_POST['operation']; $result = 0; switch ($operation) { case 'add': $result = $num1 + $num2; break; case 'subtract': $result = $num1 - $num2; break; case 'multiply': $result = $num1 * $num2; break; case 'divide': if ($num2 != 0) { $result = $num1 / $num2; } else { echo "<div class='result'>Error: Division by zero!</div>"; break; } break; default: echo "<div class='result'>Please select an operation</div>"; break; } if ($operation && ($operation != 'divide' || $num2 != 0)) { echo "<div class='result'>Result: $result</div>"; } } ?> </div> </body> </html>
18. b) Describe the concept of nested conditional statements and provide a PHP example to demonstrate how they are used.
Nested conditional statements involve placing one conditional statement (e.g., if
, else if
, else
, switch
) inside another. They allow for more complex decision-making by evaluating multiple conditions in a hierarchical manner.
Why Use Nested Conditions?
To handle complex decision-making.
When the outcome of one condition depends on the result of another.
For multi-level logic, such as grading, access control, pricing, etc.
Example:
<?php
$score = 85;
if ($score >= 0 && $score <= 100) {
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B"; // This will be the output
} elseif ($score >= 70) {
echo "Grade: C";
} elseif ($score >= 60) {
echo "Grade: D";
} else {
echo "Grade: F";
}
} else {
echo "Invalid score. Please enter a value between 0 and 100.";
}
19. a) Explain PHP arrays with examples.
Arrays in PHP are used to store multiple values in a single variable. They can hold different data types (integers, strings, objects, etc.) and are flexible in size. PHP supports three types of arrays:
Indexed Arrays – Numeric keys (starting from
0
).Associative Arrays – Named keys (key-value pairs).
Multidimensional Arrays – Arrays containing other arrays.
<?php
$fruits = array("Apple", "Banana", "Orange");
// OR
$fruits = ["Apple", "Banana", "Orange"]; // Short syntax (PHP 5.4+)
// Accessing elements
echo $fruits[0]; // Output: Apple
echo $fruits[1]; // Output: Banana
// Adding a new element
$fruits[] = "Mango"; // Adds at the end
print_r($fruits); // Prints the entire array
?>
Output:
Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Mango )
<?php $student = [ "name" => "John Doe", "age" => 20, "grade" => "A" ]; // Accessing values by key echo $student["name"]; // Output: John Doe // Modifying a value $student["grade"] = "A+"; // Adding a new key-value pair $student["email"] = "john@example.com"; print_r($student); ?>
Output:
Array ( [name] => John Doe [age] => 20 [grade] => A+ [email] => john@example.com )
<?php $employees = [ ["name" => "Alice", "role" => "Developer"], ["name" => "Bob", "role" => "Designer"], ["name" => "Charlie", "role" => "Manager"] ]; // Accessing nested elements echo $employees[1]["name"]; // Output: Bob // Adding a new employee $employees[] = ["name" => "David", "role" => "Tester"]; print_r($employees); ?>
Output:
Array ( [0] => Array ( [name] => Alice [role] => Developer ) [1] => Array ( [name] => Bob [role] => Designer ) [2] => Array ( [name] => Charlie [role] => Manager ) [3] => Array ( [name] => David [role] => Tester ) )
19. b) Write a PHP program to demonstrate constructors and destructors.
Constructor (__construct
)
Automatically called when an object is created.
Used to initialize properties.
Destructor (__destruct
)
Automatically called when an object is destroyed.
Used for cleanup (e.g., closing database connections).
Example:
<?php class User { public $name; public $email; // Constructor public function __construct($name, $email) { $this->name = $name; $this->email = $email; echo "User '$name' created!<br>"; } // Destructor public function __destruct() { echo "User '$this->name' destroyed!<br>"; } // Method public function greet() { echo "Hello, $this->name!<br>"; } } // Create an object (triggers __construct) $user1 = new User("Alice", "alice@example.com"); $user1->greet(); // Object is destroyed at script end (triggers __destruct) ?>
output:
User 'Alice' created! Hello, Alice! User 'Alice' destroyed!
20. a) Describe the structure of a typical Laravel application. Focus on the purpose of the following directories: app. config, database, public and routes.
1. App: It is the application folder and includes the entire source code of the project. The app folder comprises various sub folders as explained below.
- Console: Console includesthe artisan commands necessary for Laravel. It includes a directory named Commands, where all the commands are declared with the appropriate signature. The file Kernal.php calls the commands declared in Inspire.php
- Events: This folder includes all the events for the project.
- Exceptions: Thisfolder contains all the methods needed to handle exceptions.
- Http: The Http folder hassub-foldersfor controllers, middleware and application requests.
2. Bootstrap: This folder encloses all the application bootstrap scripts. It contains a sub-folder namely cache, which includes all the files associated for caching a web application.
3. Config: The config folder includes various configurations and associated parametersrequired for the smooth functioning of a Laravel application.
4. Database: As the name suggests, this directory includes various parameters for database functionalities. It includes three sub-directories as given below.
- Seeds − This contains the classes used for unit testing database.
- Migrations − This folder helps in queries for migrating the database used in the web
application. - Factories − This folder is used to generate large number of data records.
5. Public: It is the root folder which helps in initializing the Laravel application. It includes the following files and folders
- .htaccess − This file gives the server configuration.
- javascript and css − These files are considered as assets.
- index.php − This file is required for the initialization of a web application.
6. Routes: Defines all application routes, mapping URLs to controllers or closure functions.
web.php
→ Routes for web interface (HTML pages)api.php
→ Routes for APIs (typically return JSON)console.php
,channels.php
→ CLI & broadcasting routes
20. b) Create a table to store the following student details: Roll number (primary Key), First name, Last name and email. Also fetch and display all records from the table whose last name is 'Doe'.
1. SQL Query to Create the Table
CREATE TABLE students (
roll_no INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100)
);
2. SQL Query to Fetch Students with Last Name ‘Doe’
SELECT * FROM students
WHERE last_name = 'Doe';
3. PHP Code to Fetch and Display Records with last_name = 'Doe'
<?php
// Database connection setup
$host = "localhost";
$username = "root";
$password = "";
$database = "school";
// Create connection
$conn = new mysqli($host, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to fetch students with last name 'Doe'
$sql = "SELECT * FROM students WHERE last_name = 'Doe'";
$result = $conn->query($sql);
// Display results
if ($result->num_rows > 0) {
echo "<h3>Students with Last Name 'Doe':</h3>";
echo "<table border='1'>
<tr><th>Roll No</th><th>First Name</th><th>Last Name</th><th>Email</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>
<td>{$row['roll_no']}</td>
<td>{$row['first_name']}</td>
<td>{$row['last_name']}</td>
<td>{$row['email']}</td>
</tr>";
}
echo "</table>";
} else {
echo "No students found with last name 'Doe'.";
}
// Close connection
$conn->close();
?>