Chapter 5
Scripting Language
TU BCA past exam questions
Past questions and answers
71 questions set from this chapter, 8 of them more than once. Most repeated first.
- Asked 2 times
- 2021 · 5 marks
- 2022 · 5 marks
Explain features of JavaScript?
Answer
Features of JavaScript.
- Lightweight and interpreted: code is executed line by line by the browser's engine; no separate compilation step.
- Client-side scripting: runs in the user's browser, reducing server load and giving fast response.
- Dynamically typed: variables need no type declaration; a variable can hold any type (
var x = 5; x = "text";). - Object-based and prototype-based: supports objects, prototypes, and (with ES6) classes; functions are first-class objects.
- Event-driven: responds to user events such as clicks, key presses and form submission.
- Platform independent and cross-browser: the same code runs on any operating system with a browser.
- Supports DOM manipulation: can add, remove and change HTML elements and CSS dynamically.
- Form validation: checks user input before it is sent to the server.
- Asynchronous programming: callbacks, promises,
async/awaitand AJAX allow background requests. - Rich built-in objects and libraries/frameworks:
Date,Math,Array,JSON, plus jQuery, React, Angular, Vue and Node.js for server-side use. - Case-sensitive, with C-like syntax: easy to learn for programmers who know C/Java.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- Asked 2 times
- 2021 · 5 marks
- 2022 · 5 marks
What is NaN in JavaScript? Write JavaScript code to change background color of web page every second.
Answer
NaN stands for "Not-a-Number". It is a special value of the Number type that results when a numeric operation cannot produce a valid number, for example 0/0, parseInt("abc") or Math.sqrt(-1). NaN is not equal to anything, even itself (NaN === NaN is false), so use isNaN(x) or Number.isNaN(x) to test for it. typeof NaN is "number".
Changing the background colour every second:
<!DOCTYPE html>
<html>
<head><title>Colour changer</title></head>
<body>
<h2>Background changes every second</h2>
<script>
const colors = ["red", "green", "blue", "yellow", "orange", "pink", "violet"];
let i = 0;
setInterval(function () {
document.body.style.backgroundColor = colors[i];
i = (i + 1) % colors.length;
}, 1000);
</script>
</body>
</html>
setInterval() calls the function repeatedly every 1000 ms, and each call sets document.body.style.backgroundColor to the next colour in the array.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- Asked 2 times
- 2021 · 5 marks
- 2022 · 5 marks
What is arrow function? Write JavaScript code to calculate factorial of given number using arrow function.
Answer
An arrow function is a shorter syntax for writing function expressions, introduced in ES6. It uses the => operator instead of the function keyword.
const add = (a, b) => a + b;
Features:
- Concise syntax; a single expression is returned implicitly without
returnor braces. - Parentheses may be omitted for a single parameter (
x => x * 2). - It does not have its own
this; it inheritsthisfrom the enclosing scope. - It cannot be used as a constructor and has no
argumentsobject.
Factorial using an arrow function:
<script>
const factorial = n => (n <= 1 ? 1 : n * factorial(n - 1));
const num = parseInt(prompt("Enter a number:"));
if (isNaN(num) || num < 0) {
alert("Please enter a non-negative integer");
} else {
alert("Factorial of " + num + " is " + factorial(num));
}
</script>
For example, factorial(5) gives .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- Asked 2 times
- 2021 · 5 marks
- 2022 · 5 marks
Write a program to create Chess board in PHP using loop.
Answer
A chess board is an grid of alternating black and white squares. Nested loops generate the rows and columns, and the sum of the row and column index decides the colour.
<?php
echo "<table border='1' cellspacing='0' cellpadding='0'>";
for ($row = 0; $row < 8; $row++) {
echo "<tr>";
for ($col = 0; $col < 8; $col++) {
$color = (($row + $col) % 2 == 0) ? "white" : "black";
echo "<td style='width:50px;height:50px;background-color:$color;'></td>";
}
echo "</tr>";
}
echo "</table>";
?>
The outer loop creates 8 table rows and the inner loop creates 8 cells in each row. When $row + $col is even the cell is white; otherwise it is black, which gives the alternating pattern.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- Asked 2 times
- 2021 · 5 marks
- 2022 · 5 marks
Write jQuery code to include date picker controls in HTML text box.
Answer
The jQuery UI library provides a datepicker() widget that attaches a calendar pop-up to a text box.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<script>
$(document).ready(function () {
$("#dob").datepicker({
dateFormat: "yy-mm-dd",
changeMonth: true,
changeYear: true
});
});
</script>
</head>
<body>
<label for="dob">Date: </label>
<input type="text" id="dob">
</body>
</html>
When the user clicks the text box with id dob, a calendar appears and the chosen date is written into the box in yyyy-mm-dd format. The options changeMonth and changeYear add drop-downs for quick navigation.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- Asked 2 times
- 2021 · 5 marks
- 2022 · 5 marks
Write a JavaScript program to retrieve any value from server-side script using Ajax.
Answer
Ajax (Asynchronous JavaScript and XML) lets a page request data from the server through XMLHttpRequest without reloading the page.
Client side (index.html):
<!DOCTYPE html>
<html>
<body>
<button onclick="loadValue()">Get server time</button>
<p id="result"></p>
<script>
function loadValue() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.open("GET", "getvalue.php", true);
xhr.send();
}
</script>
</body>
</html>
Server side (getvalue.php):
<?php
echo "Server time is " . date("Y-m-d H:i:s");
?>
When the button is clicked, the request is sent asynchronously to getvalue.php. When readyState is 4 (done) and status is 200 (OK), the returned text is inserted into the paragraph without refreshing the page.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- Asked 2 times
- 2021 · 5 marks
- 2022 · 5 marks
What is constructor? How you implement constructor in php?
Answer
A constructor is a special method of a class that is called automatically when an object is created. It is used to initialise the properties of the object.
In PHP, the constructor is declared with the name __construct(). (Older PHP versions also allowed a method with the same name as the class.) A class may have only one constructor, and it can take parameters. __destruct() is the corresponding method called when the object is destroyed.
<?php
class Student {
public $name;
public $roll;
public function __construct($name, $roll) {
$this->name = $name;
$this->roll = $roll;
echo "Object created for $name<br>";
}
public function display() {
echo "Name: $this->name, Roll: $this->roll<br>";
}
public function __destruct() {
echo "Object destroyed<br>";
}
}
$s1 = new Student("Ram", 101);
$s1->display();
?>
When new Student("Ram", 101) runs, __construct() is invoked automatically and sets the name and roll values.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- Asked 2 times
- 2021 · 10 marks
- 2022 · 10 marks
What are advantages of inheritance? Write a PHP program to illustrate the concept of function overloading.
Answer
Advantages of inheritance
Inheritance is the mechanism by which a child class acquires the properties and methods of a parent class (class Child extends Parent).
- Code reusability: common code is written once in the parent and reused by all children.
- Reduced redundancy and less development time, since existing tested code is reused.
- Easy maintenance: a change in the parent is automatically reflected in all child classes.
- Extensibility: a child can add new members or override inherited ones to specialise behaviour.
- Polymorphism: objects of different child classes can be treated as objects of the parent type.
- Clear hierarchy: it models real "is-a" relationships (a Student is a Person), giving a better program structure.
Function overloading in PHP
Overloading means having several functions with the same name but different parameters. PHP does not support the C++/Java style of defining multiple methods with the same name; instead it supports overloading through the magic method __call(), which is invoked when an inaccessible or undefined method is called. Inside it, the number or type of arguments decides what to do.
<?php
class Calculator {
// called when an undefined method is invoked on an object
public function __call($name, $args) {
if ($name == "area") {
switch (count($args)) {
case 1:
return "Area of square = " . ($args[0] * $args[0]);
case 2:
return "Area of rectangle = " . ($args[0] * $args[1]);
case 3:
return "Area of triangle (Heron) = " .
$this->heron($args[0], $args[1], $args[2]);
default:
return "Invalid number of arguments";
}
}
return "Method $name does not exist";
}
private function heron($a, $b, $c) {
$s = ($a + $b + $c) / 2;
return round(sqrt($s * ($s - $a) * ($s - $b) * ($s - $c)), 2);
}
}
$c = new Calculator();
echo $c->area(4) . "<br>"; // 16
echo $c->area(4, 5) . "<br>"; // 20
echo $c->area(3, 4, 5) . "<br>"; // 6
?>
Output: square of side 4 gives 16; rectangle 4 by 5 gives 20; a triangle with sides 3, 4, 5 has and area . The same method name area() therefore behaves differently depending on the number of arguments.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
Design following form in HTML and write corresponding server-side script to upload and submit user's data into database in consideration of following validation rules. Assume your own database and database connectivity related constraints if necessary.
Online Project Submission Form
TU Registration Number
Email Address
Upload your Project File
supported file format:
pdf,doc,docx,ppt,pptx,jpegChoose File | No file chosen
Upload
Validation rules:
o Registration number, email and upload file are mandatory field. o Email address should not be a proper email format. o Upload file format must include pdf, doc, docx, ppt, pptx, jpeg file format.
o File size must be less than 5 MB.
Similar questions: Design following form in HTML and write (2022)
Answer
Online Project Submission Form
Assumed database college with the table:
CREATE TABLE submissions (
id INT AUTO_INCREMENT PRIMARY KEY,
reg_no VARCHAR(30) NOT NULL,
email VARCHAR(100) NOT NULL,
file_name VARCHAR(255) NOT NULL,
submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Note: the rule "email address should not be a proper email format" is taken as a misprint for "email address should be in a proper email format", since this is the only sensible validation.
form.html
<!DOCTYPE html>
<html>
<head><title>Online Project Submission Form</title></head>
<body>
<h2>Online Project Submission Form</h2>
<form method="post" action="upload.php" enctype="multipart/form-data">
TU Registration Number:<br>
<input type="text" name="reg_no"><br><br>
Email Address:<br>
<input type="text" name="email"><br><br>
Upload your Project File:<br>
<input type="file" name="project"><br>
<small>Supported file format: pdf, doc, docx, ppt, pptx, jpeg</small><br><br>
<input type="submit" name="upload" value="Upload">
</form>
</body>
</html>
enctype="multipart/form-data" is required for file upload.
upload.php
<?php
if (isset($_POST['upload'])) {
$errors = [];
$reg = trim($_POST['reg_no'] ?? '');
$email = trim($_POST['email'] ?? '');
// mandatory fields
if ($reg === '') $errors[] = "Registration number is required.";
if ($email === '') $errors[] = "Email is required.";
if (!isset($_FILES['project']) || $_FILES['project']['error'] == UPLOAD_ERR_NO_FILE) {
$errors[] = "Project file is required.";
}
// email format
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Email address is not in a proper format.";
}
if (empty($errors)) {
$file = $_FILES['project'];
$allowed = ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'jpeg'];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($file['error'] !== UPLOAD_ERR_OK) {
$errors[] = "File upload failed.";
}
if (!in_array($ext, $allowed)) {
$errors[] = "Only pdf, doc, docx, ppt, pptx, jpeg files are allowed.";
}
if ($file['size'] >= 5 * 1024 * 1024) { // less than 5 MB
$errors[] = "File size must be less than 5 MB.";
}
}
if (!empty($errors)) {
foreach ($errors as $e) echo "<p style='color:red'>$e</p>";
exit;
}
// save the file with a unique name
if (!is_dir("uploads")) mkdir("uploads", 0755);
$newName = uniqid("proj_") . "." . $ext;
if (!move_uploaded_file($file['tmp_name'], "uploads/" . $newName)) {
die("Could not save the file.");
}
// store in database
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
$stmt = $conn->prepare("INSERT INTO submissions(reg_no, email, file_name) VALUES(?,?,?)");
$stmt->bind_param("sss", $reg, $email, $newName);
if ($stmt->execute()) {
echo "Project submitted successfully.";
} else {
echo "Database error: " . $conn->error;
}
$conn->close();
}
?>
The script checks all mandatory fields, validates the email with filter_var, restricts extensions to the allowed list, enforces a size below 5 MB ( bytes), moves the file to the uploads folder and records the details using a prepared statement.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 10 marks
Design following form in HTML and write corresponding server-side script to upload and submit user's data into database in consideration of following validation rules. Assume your own database and database connectivity related constraints if necessary.
Validation rules:
Registration number, email and upload file are mandatory field. Email address should not be a proper email format. Upload file format must include pdf, doc, docx, ppt, pptx, jpeg file format.
File size must be less than 5MB.
Similar questions: Design following form in HTML and write (2021)
Answer
Project submission form with validation
Assumed database college with the table:
CREATE TABLE submissions (
id INT AUTO_INCREMENT PRIMARY KEY,
reg_no VARCHAR(30) NOT NULL,
email VARCHAR(100) NOT NULL,
file_name VARCHAR(255) NOT NULL,
submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Note: the rule "email address should not be a proper email format" is taken as a misprint for "email address should be in a proper email format", since this is the only sensible validation.
form.html
<!DOCTYPE html>
<html>
<head><title>Online Project Submission Form</title></head>
<body>
<h2>Online Project Submission Form</h2>
<form method="post" action="upload.php" enctype="multipart/form-data">
TU Registration Number:<br>
<input type="text" name="reg_no"><br><br>
Email Address:<br>
<input type="text" name="email"><br><br>
Upload your Project File:<br>
<input type="file" name="project"><br>
<small>Supported file format: pdf, doc, docx, ppt, pptx, jpeg</small><br><br>
<input type="submit" name="upload" value="Upload">
</form>
</body>
</html>
enctype="multipart/form-data" is required for file upload.
upload.php
<?php
if (isset($_POST['upload'])) {
$errors = [];
$reg = trim($_POST['reg_no'] ?? '');
$email = trim($_POST['email'] ?? '');
// mandatory fields
if ($reg === '') $errors[] = "Registration number is required.";
if ($email === '') $errors[] = "Email is required.";
if (!isset($_FILES['project']) || $_FILES['project']['error'] == UPLOAD_ERR_NO_FILE) {
$errors[] = "Project file is required.";
}
// email format
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Email address is not in a proper format.";
}
if (empty($errors)) {
$file = $_FILES['project'];
$allowed = ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'jpeg'];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($file['error'] !== UPLOAD_ERR_OK) {
$errors[] = "File upload failed.";
}
if (!in_array($ext, $allowed)) {
$errors[] = "Only pdf, doc, docx, ppt, pptx, jpeg files are allowed.";
}
if ($file['size'] >= 5 * 1024 * 1024) { // less than 5 MB
$errors[] = "File size must be less than 5 MB.";
}
}
if (!empty($errors)) {
foreach ($errors as $e) echo "<p style='color:red'>$e</p>";
exit;
}
// save the file with a unique name
if (!is_dir("uploads")) mkdir("uploads", 0755);
$newName = uniqid("proj_") . "." . $ext;
if (!move_uploaded_file($file['tmp_name'], "uploads/" . $newName)) {
die("Could not save the file.");
}
// store in database
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
$stmt = $conn->prepare("INSERT INTO submissions(reg_no, email, file_name) VALUES(?,?,?)");
$stmt->bind_param("sss", $reg, $email, $newName);
if ($stmt->execute()) {
echo "Project submitted successfully.";
} else {
echo "Database error: " . $conn->error;
}
$conn->close();
}
?>
The script checks all mandatory fields, validates the email with filter_var, restricts extensions to the allowed list, enforces a size below 5 MB ( bytes), moves the file to the uploads folder and records the details using a prepared statement.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
Explain the concept structure and importance of DOM.
Answer
Concept. The Document Object Model (DOM) is a platform- and language-neutral programming interface that represents an HTML or XML document as a tree of objects. The browser builds this tree when it loads a page, and scripts such as JavaScript use it to read and change the content, structure and style of the page.
Structure. The document is a tree of nodes:
- Document node is the root (
document). - Element nodes are the HTML tags (
<html>,<body>,<div>), nested as parents and children. - Attribute nodes hold attributes such as
idorclass. - Text nodes hold the text inside elements.
document
└── html
├── head ── title ── "My Page"
└── body ── h1 ── "Hello"
└── p (id="msg") ── "Welcome"
Example:
document.getElementById("msg").innerHTML = "Changed text";
Importance.
- Lets JavaScript change content, attributes and CSS dynamically without reloading the page.
- Allows adding, removing and reordering elements.
- Enables event handling (clicks, key presses) on elements.
- Provides a standard (W3C) interface that works across browsers.
- Is the foundation of interactive pages, form validation, AJAX updates and libraries such as jQuery.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
What is JavaScript? Write JavaScript code to print smallest and larges numbers among 10 elements of an array.
Answer
JavaScript is a lightweight, interpreted, object-based scripting language that runs in the web browser (and on servers through Node.js). It is used to make web pages interactive: validating forms, handling events, changing page content and communicating with servers.
Program to find the smallest and largest of 10 array elements:
<html>
<body>
<script>
var arr = [45, 12, 78, 3, 90, 56, 23, 67, 5, 34];
var smallest = arr[0];
var largest = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] < smallest) smallest = arr[i];
if (arr[i] > largest) largest = arr[i];
}
document.write("Smallest = " + smallest + "<br>");
document.write("Largest = " + largest);
</script>
</body>
</html>
Output: Smallest = 3 and Largest = 90.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
What is dialog box? Explain different dialog boxes with suitable example in JavaScript.
Answer
A dialog box is a small window that the browser displays to give a message to the user or to get input from the user. JavaScript provides three kinds of dialog boxes, all methods of window.
1. Alert box shows a message with an OK button. The user must click OK to continue.
alert("Welcome to the site!");
2. Confirm box shows a message with OK and Cancel buttons. It returns true for OK and false for Cancel.
var r = confirm("Do you want to delete this record?");
if (r == true) alert("Deleted");
else alert("Cancelled");
3. Prompt box asks the user to type a value. It takes a message and an optional default value, and returns the entered text, or null if Cancel is clicked.
var name = prompt("Enter your name:", "Guest");
if (name != null) document.write("Hello " + name);
Dialog boxes are modal: they stop the execution of the page until the user responds.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
Explain the two HTTP functions to accept the user values from interface with suitable PHP program
Answer
The two HTTP methods used to send user values from an HTML form to a PHP script are GET and POST. PHP receives the data in the superglobal arrays $_GET and $_POST.
| GET | POST |
|---|---|
Data is appended to the URL as a query string (page.php?name=Ram&age=20) | Data is sent in the body of the HTTP request |
| Visible in the address bar; can be bookmarked | Not visible in the URL |
| Limited length (about 2000 characters) | No practical size limit |
| Not suitable for passwords or sensitive data | Suitable for sensitive data and file uploads |
Retrieved with $_GET['name'] | Retrieved with $_POST['name'] |
Example (form.html):
<form action="process.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" value="Submit">
</form>
process.php:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$age = $_POST['age'];
echo "Name: " . $name . "<br>";
echo "Age: " . $age;
}
?>
Changing method="post" to method="get" and using $_GET makes the same program use the GET method.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
What is the use of jQuery? Write the sample program to show and hide the certain div with the use of jQuery.
Answer
Use of jQuery. jQuery is a fast, small, cross-browser JavaScript library that simplifies client-side scripting. Its use includes:
- selecting and manipulating HTML elements with short CSS-like selectors,
- handling events easily,
- creating animations and effects (show, hide, fade, slide),
- making AJAX requests with little code,
- traversing and modifying the DOM consistently across browsers.
Program to show and hide a div:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("#hide").click(function () {
$("#box").hide();
});
$("#show").click(function () {
$("#box").show();
});
});
</script>
</head>
<body>
<div id="box" style="background:lightblue; padding:20px;">
This is the div to show and hide.
</div>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
Clicking Hide hides the div with id box; clicking Show displays it again.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
Why Ajax is required in web development? Write a sample program to synchronize data between JavaScript and PHP.
Answer
Why AJAX is required. AJAX (Asynchronous JavaScript and XML) lets a page exchange data with the server in the background, without reloading the whole page. It is required because it:
- updates only part of a page, so the page is faster and uses less bandwidth,
- keeps the user's state (form data, scroll position) intact,
- keeps the page responsive since requests are asynchronous,
- enables features such as live search, auto-suggest, form validation and chat.
Sample program: JavaScript sends data to PHP and shows the reply.
index.html
<html>
<body>
<input type="text" id="name" placeholder="Enter name">
<button onclick="sendData()">Send</button>
<p id="result"></p>
<script>
function sendData() {
var name = document.getElementById("name").value;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.open("POST", "process.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=" + encodeURIComponent(name));
}
</script>
</body>
</html>
process.php
<?php
$name = htmlspecialchars($_POST['name']);
echo "Hello, " . $name . "! Data received from the server.";
?>
The page updates the result paragraph without reloading.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
What is CMS, Write the steps to create submenu in WordPress or Joomla?
Answer
CMS (Content Management System). A software application that lets users create, manage and publish website content without writing code, usually through a web-based admin panel, with themes, plugins and user roles. Examples: WordPress, Joomla, Drupal.
Steps to create a submenu in WordPress:
- Log in to the admin dashboard (
/wp-admin). - Create the pages (or posts, categories, custom links) that will appear in the menu: Pages > Add New.
- Go to Appearance > Menus.
- Click Create a new menu, give it a name (e.g. "Main Menu") and click Create Menu.
- In the left panel, tick the required pages and click Add to Menu.
- Drag a menu item slightly to the right under its parent item. It becomes a submenu (child) item, shown indented as "sub item".
- Under Menu Settings, tick Primary Menu (display location).
- Click Save Menu.
- Visit the site: hovering over the parent item shows the submenu (dropdown).
In Joomla: go to Menus > Main Menu > New, enter the title, choose the Menu Item Type, and select the Parent Item as the menu under which the submenu should appear; then Save & Close.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 10 marks
Design following form in HTML and display the value in the result box after calculating basic arithmetic operation based on the use input with the use of JavaScript.
Answer
The form has two number fields, an operation choice and a result box.
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<script>
function calculate(op) {
var a = parseFloat(document.getElementById("num1").value);
var b = parseFloat(document.getElementById("num2").value);
var result;
if (isNaN(a) || isNaN(b)) {
document.getElementById("result").value = "Enter valid numbers";
return;
}
switch (op) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/':
result = (b == 0) ? "Cannot divide by zero" : a / b;
break;
}
document.getElementById("result").value = result;
}
</script>
</head>
<body>
<form>
<table>
<tr><td>First Number</td>
<td><input type="text" id="num1"></td></tr>
<tr><td>Second Number</td>
<td><input type="text" id="num2"></td></tr>
<tr><td colspan="2">
<input type="button" value="Add" onclick="calculate('+')">
<input type="button" value="Subtract" onclick="calculate('-')">
<input type="button" value="Multiply" onclick="calculate('*')">
<input type="button" value="Divide" onclick="calculate('/')">
</td></tr>
<tr><td>Result</td>
<td><input type="text" id="result" readonly></td></tr>
</table>
</form>
</body>
</html>
Entering 12 and 4 and clicking Add shows 16 in the result box; Divide shows 3.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 10 marks
Write an object-oriented PHP program to implement the concept of inheritance in considering with following class diagram with the use of constructor for 20 students.
Answer
Assume the class diagram is a parent class Person (name, address) and a child class Student (roll number, marks) inheriting from it, with constructors, for 20 students.
<?php
class Person {
protected $name;
protected $address;
public function __construct($name, $address) {
$this->name = $name;
$this->address = $address;
}
public function displayPerson() {
echo "Name: $this->name, Address: $this->address";
}
}
class Student extends Person {
private $roll;
private $marks;
public function __construct($name, $address, $roll, $marks) {
parent::__construct($name, $address);
$this->roll = $roll;
$this->marks = $marks;
}
public function display() {
echo "Roll: $this->roll, ";
$this->displayPerson();
echo ", Marks: $this->marks<br>";
}
}
$students = array();
for ($i = 1; $i <= 20; $i++) {
$students[] = new Student("Student$i", "City$i", $i, rand(40, 100));
}
foreach ($students as $s) {
$s->display();
}
?>
Student inherits name, address and displayPerson() from Person using extends, and its constructor calls the parent constructor with parent::__construct(). A loop creates and displays 20 Student objects.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 10 marks
Design following forms in HTML and write corresponding PHP and MySQL code to store the user's values after satisfying following validation rules.
a. Length of Full name up to 40 characters
b. Email address must be valid email address
c. Username must be start with string and followed by number.
d. Password length must be more than 8 characters.
Answer
register.html
<!DOCTYPE html>
<html>
<body>
<h3>Registration Form</h3>
<form method="post" action="register.php">
Full Name: <input type="text" name="fullname"><br><br>
Email: <input type="text" name="email"><br><br>
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
register.php (database testdb, table users)
<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }
$fullname = trim($_POST['fullname']);
$email = trim($_POST['email']);
$username = trim($_POST['username']);
$password = $_POST['password'];
$errors = array();
// a. Full name up to 40 characters
if ($fullname == "" || strlen($fullname) > 40)
$errors[] = "Full name must be 1 to 40 characters.";
// b. Valid email
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
$errors[] = "Invalid email address.";
// c. Username starts with letters followed by numbers
if (!preg_match('/^[A-Za-z]+[0-9]+$/', $username))
$errors[] = "Username must start with letters followed by numbers.";
// d. Password longer than 8 characters
if (strlen($password) <= 8)
$errors[] = "Password must be more than 8 characters.";
if (count($errors) > 0) {
foreach ($errors as $e) echo $e . "<br>";
} else {
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = mysqli_prepare($conn,
"INSERT INTO users (fullname, email, username, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, "ssss", $fullname, $email, $username, $hash);
if (mysqli_stmt_execute($stmt))
echo "Registration successful.";
else
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Table:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
fullname VARCHAR(40),
email VARCHAR(100),
username VARCHAR(50),
password VARCHAR(255)
);
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
What is JavaScript? What are the potential platforms where JavaScript can be used?
Answer
JavaScript is a high-level, interpreted, object-based scripting language, created by Brendan Eich at Netscape in 1995. It is mainly used to add interactivity and dynamic behaviour to web pages, and it follows the ECMAScript standard.
Platforms where JavaScript can be used:
- Client-side web browsers (Chrome, Firefox, Edge): form validation, DOM manipulation, events, animations and AJAX.
- Server-side, using Node.js to build web servers, APIs and real-time applications.
- Mobile applications, using frameworks such as React Native, Ionic and Cordova.
- Desktop applications, using Electron (e.g. VS Code, Slack).
- Web application frameworks, such as React, Angular and Vue.js for single-page applications.
- Game development, in browser games using canvas, WebGL or Phaser.
- Embedded systems and IoT, using runtimes such as Espruino and Johnny-Five.
- Databases and tools, e.g. MongoDB shell queries, build tools and PDF scripting.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
Define JavaScript event. Illustrate how an event handler response particular event in web page.
Answer
JavaScript event. An event is an action or occurrence in the web page that the browser can detect, usually caused by the user or the browser, such as a mouse click (onclick), key press (onkeydown), page load (onload), form submit (onsubmit), mouse over (onmouseover) or change of an input (onchange).
Event handler. A function (or code) that runs when a specific event occurs on an element. It is attached to the element so that the page responds to the event.
Illustration:
<html>
<body>
<p id="msg">Click the button.</p>
<button id="btn" onclick="showMessage()">Click Me</button>
<script>
function showMessage() {
document.getElementById("msg").innerHTML = "Button was clicked!";
}
</script>
</body>
</html>
Working: when the user clicks the button, the click event occurs, the browser calls the handler showMessage() (specified in the onclick attribute), and the handler changes the paragraph text.
The handler can also be attached in script with addEventListener:
document.getElementById("btn").addEventListener("click", showMessage);
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
What is an Immediately Invoked Function in JavaScript? Explain with suitable example.
Answer
An Immediately Invoked Function Expression (IIFE) is a function that is defined and executed at the same moment, as soon as the interpreter reaches it. The function is wrapped in parentheses to make it an expression, and followed by () to call it.
Syntax:
(function () {
// code
})();
Example:
(function () {
var message = "Hello from IIFE";
console.log(message);
})();
var result = (function (a, b) {
return a + b;
})(5, 3);
console.log(result); // 8
Uses:
- Creates a private scope, so variables do not pollute the global namespace.
- Avoids name conflicts between scripts.
- Runs initialisation code once.
- Implements the module pattern with private data.
Variables declared inside (e.g. message) cannot be accessed from outside.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
Explain an array using suitable example and discuss how foreach loop accessing of elements is stored in an array using PHP.
Answer
Array. An array is a variable that stores multiple values under one name, accessed by an index or key. PHP has three kinds:
- Indexed array: numeric index starting at 0.
- Associative array: named keys.
- Multidimensional array: arrays containing arrays.
<?php
$fruits = array("Apple", "Banana", "Mango"); // indexed
$marks = array("Ram" => 80, "Sita" => 90); // associative
echo $fruits[1]; // Banana
?>
foreach loop. foreach loops through every element of an array without needing a counter or the array length. In each iteration the current element is copied to a variable, and the internal pointer moves to the next element automatically.
Syntax:
foreach ($array as $value) { ... }
foreach ($array as $key => $value) { ... }
Example:
<?php
$fruits = array("Apple", "Banana", "Mango");
foreach ($fruits as $f) {
echo $f . "<br>";
}
$marks = array("Ram" => 80, "Sita" => 90);
foreach ($marks as $name => $m) {
echo "$name scored $m<br>";
}
?>
Output: Apple, Banana, Mango, then Ram scored 80, Sita scored 90.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
What is jQuery? illustrate different types of selectors in jQuery with appropriate example?
Answer
jQuery is a fast, lightweight, cross-browser JavaScript library ("write less, do more") that simplifies DOM selection and manipulation, event handling, animation and AJAX. Its core is the $() function, which selects elements using CSS-style selectors.
Types of selectors:
| Selector | Syntax | Example | Meaning |
|---|---|---|---|
| Element | $("tag") | $("p") | All <p> elements |
| ID | $("#id") | $("#box") | Element with id box |
| Class | $(".class") | $(".note") | All elements with class note |
| Universal | $("*") | $("*") | All elements |
| Multiple | $("a, b") | $("h1, p") | All h1 and p elements |
| Descendant | $("a b") | $("div p") | All p inside div |
| Child | $("a > b") | $("ul > li") | Direct li children of ul |
| Attribute | $("[attr=v]") | $("input[type='text']") | Inputs with type text |
| Positional | :first, :last, :even, :odd | $("tr:even") | Even table rows |
Example:
<script>
$(document).ready(function () {
$("p").css("color", "blue"); // element selector
$("#box").hide(); // ID selector
$(".note").css("background", "yellow"); // class selector
});
</script>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
What is the benefit of using AJAX? Discuss major methods that communicate with server-side scripting.
Answer
Benefits of AJAX.
- Updates part of a page without reloading it, so pages feel faster and smoother.
- Reduces bandwidth and server load because only the needed data is transferred.
- Requests are asynchronous, so the user can keep working while data loads.
- Preserves page state and improves user experience (live search, form validation, auto-complete, chat).
- Works with many data formats: plain text, HTML, XML and JSON.
Major methods that communicate with server-side scripts.
- XMLHttpRequest object, the basic method in plain JavaScript.
open(method, url, async)prepares the request.send(data)sends it (send()for GET,send(params)for POST).setRequestHeader()sets headers for POST.onreadystatechangehandles the response whenreadyState == 4andstatus == 200; the reply is inresponseTextorresponseXML.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200)
document.getElementById("demo").innerHTML = xhr.responseText;
};
xhr.open("GET", "data.php?name=Ram", true);
xhr.send();
-
GET and POST requests. GET appends data to the URL (small, visible data); POST sends data in the body (larger or sensitive data).
-
jQuery methods:
$.ajax(),$.get(),$.post(),.load().
$.post("process.php", { name: "Ram" }, function (data) { alert(data); });
- Fetch API: modern promise-based
fetch(url).then(r => r.text()).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
Discuss about MVC architecture with appropriate diagram.
Answer
MVC (Model-View-Controller) is an architectural pattern that separates an application into three interconnected components so that data, user interface and control logic are developed and maintained independently.
Components.
- Model: manages the data, business logic and rules; interacts with the database (e.g. fetches, inserts and updates records). It does not know about the user interface.
- View: the presentation layer; displays the data to the user (HTML pages, templates). It has no business logic.
- Controller: receives user requests, handles input, calls the model to get or change data, and selects the view to display the result.
Diagram.
user request
User ------------> Controller
^ | ^
| | | data
| output v |
View <----------- Model <--> Database
(data)
Flow. The user sends a request; the controller processes it and asks the model for data; the model reads or updates the database and returns the data; the controller passes the data to the view; the view renders the page that the user sees.
Advantages. Separation of concerns, easier maintenance and testing, code reuse, parallel development by designers and programmers, and multiple views for the same model. Frameworks using MVC include Laravel, CodeIgniter, Django and ASP.NET MVC.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 10 marks
a) Write a program which includes a function sum(). This function sum() should be designed to add an arbitrary list of parameters. (For e.g ., if you call the function sum() as sum (1, 2) it should return the result 3 and if again you call the function sum() as sum(1,3,4) it should return the result 8).
b) Write a program that displays the continuous time in the web page. The time should be in the format of HH:MM:SS.
Answer
(a) Function sum() with an arbitrary number of parameters
Every JavaScript function has an arguments object holding all values passed to it.
<script>
function sum() {
var total = 0;
for (var i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
document.write(sum(1, 2) + "<br>"); // 3
document.write(sum(1, 3, 4) + "<br>"); // 8
</script>
(Modern alternative: function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }.)
(b) Continuous time in HH:MM:SS
<html>
<head>
<script>
function pad(n) {
return n < 10 ? "0" + n : n;
}
function showTime() {
var d = new Date();
var t = pad(d.getHours()) + ":" + pad(d.getMinutes()) + ":" + pad(d.getSeconds());
document.getElementById("clock").innerHTML = t;
}
window.onload = function () {
showTime();
setInterval(showTime, 1000);
};
</script>
</head>
<body>
<h2 id="clock"></h2>
</body>
</html>
setInterval calls showTime() every 1000 ms, so the clock updates every second.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 10 marks
Define method overriding. Write a PHP program to handle the overriding situation.
Answer
Method overriding. When a child class defines a method with the same name (and parameters) as a method in its parent class, the child's version replaces the parent's version for objects of the child class. It is a form of runtime polymorphism and requires inheritance (extends). The parent's version can still be called with parent::methodName(). A method declared final in the parent cannot be overridden.
PHP program:
<?php
class Shape {
public function area() {
echo "Area of a generic shape is undefined.<br>";
}
public function show() {
echo "This is a shape.<br>";
}
}
class Circle extends Shape {
private $r;
public function __construct($r) { $this->r = $r; }
// overrides Shape::area()
public function area() {
echo "Area of circle = " . (3.14159 * $this->r * $this->r) . "<br>";
}
// overrides and also reuses the parent method
public function show() {
parent::show();
echo "More precisely, it is a circle.<br>";
}
}
$s = new Shape();
$s->area(); // parent version
$c = new Circle(5);
$c->area(); // overridden version: 78.53975
$c->show(); // calls parent::show() too
?>
The call $c->area() runs Circle::area(), not Shape::area(), which demonstrates overriding.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 10 marks
Design following form in HTML and write corresponding PHP and SQL code for CRUD operations based on user's data. Assume your own database and database connectivity related constraints if necessary.
Answer
Assume a form with Name, Address and Phone, and a table student(id, name, address, phone) in database school.
db.php (connection)
<?php
$conn = mysqli_connect("localhost", "root", "", "school");
if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }
?>
form.html
<form method="post" action="crud.php">
<input type="hidden" name="id">
Name: <input type="text" name="name"><br>
Address: <input type="text" name="address"><br>
Phone: <input type="text" name="phone"><br>
<input type="submit" name="save" value="Save">
<input type="submit" name="update" value="Update">
</form>
SQL table
CREATE TABLE student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50), address VARCHAR(100), phone VARCHAR(15)
);
crud.php
<?php
include "db.php";
// CREATE
if (isset($_POST['save'])) {
$stmt = mysqli_prepare($conn, "INSERT INTO student (name, address, phone) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($stmt, "sss", $_POST['name'], $_POST['address'], $_POST['phone']);
mysqli_stmt_execute($stmt);
echo "Record inserted.<br>";
}
// UPDATE
if (isset($_POST['update'])) {
$stmt = mysqli_prepare($conn, "UPDATE student SET name=?, address=?, phone=? WHERE id=?");
mysqli_stmt_bind_param($stmt, "sssi", $_POST['name'], $_POST['address'], $_POST['phone'], $_POST['id']);
mysqli_stmt_execute($stmt);
echo "Record updated.<br>";
}
// DELETE
if (isset($_GET['delete'])) {
$id = (int)$_GET['delete'];
mysqli_query($conn, "DELETE FROM student WHERE id=$id");
echo "Record deleted.<br>";
}
// READ
$result = mysqli_query($conn, "SELECT * FROM student");
echo "<table border='1'><tr><th>ID</th><th>Name</th><th>Address</th><th>Phone</th><th>Action</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td>{$row['address']}</td>
<td>{$row['phone']}</td>
<td><a href='crud.php?delete={$row['id']}'>Delete</a></td></tr>";
}
echo "</table>";
mysqli_close($conn);
?>
The four CRUD operations map to SQL as: Create to INSERT, Read to SELECT, Update to UPDATE, Delete to DELETE. For update, the id of the record (hidden field) selects the row.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 10 marks
Write HTML and JavaScript code to create a calculator for performing basic arithmetic operations.
Answer
Calculator using HTML and JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
<style>
.calc { width: 240px; margin: 40px auto; padding: 12px; border: 2px solid #333; border-radius: 8px; }
#display { width: 100%; height: 40px; font-size: 20px; text-align: right; box-sizing: border-box; margin-bottom: 8px; }
button { width: 52px; height: 40px; margin: 3px; font-size: 18px; }
</style>
</head>
<body>
<div class="calc">
<input type="text" id="display" readonly>
<div>
<button onclick="press('7')">7</button>
<button onclick="press('8')">8</button>
<button onclick="press('9')">9</button>
<button onclick="press('/')">/</button>
</div>
<div>
<button onclick="press('4')">4</button>
<button onclick="press('5')">5</button>
<button onclick="press('6')">6</button>
<button onclick="press('*')">*</button>
</div>
<div>
<button onclick="press('1')">1</button>
<button onclick="press('2')">2</button>
<button onclick="press('3')">3</button>
<button onclick="press('-')">-</button>
</div>
<div>
<button onclick="press('0')">0</button>
<button onclick="press('.')">.</button>
<button onclick="calculate()">=</button>
<button onclick="press('+')">+</button>
</div>
<div>
<button onclick="clearDisplay()" style="width:112px">C</button>
<button onclick="backspace()" style="width:112px">←</button>
</div>
</div>
<script>
var display = document.getElementById("display");
function press(ch) {
display.value += ch;
}
function clearDisplay() {
display.value = "";
}
function backspace() {
display.value = display.value.slice(0, -1);
}
function calculate() {
var exp = display.value;
// allow only digits, operators and decimal point
if (!/^[0-9+\-*/.]+$/.test(exp)) {
display.value = "Error";
return;
}
try {
var result = Function('"use strict";return (' + exp + ')')();
display.value = (isFinite(result)) ? result : "Error";
} catch (e) {
display.value = "Error";
}
}
</script>
</body>
</html>
The buttons append characters to the display; = evaluates the expression after checking it contains only digits and the operators + - * /, so the four basic operations are performed with the usual precedence (for example, 2+3*4 gives 14). Division by zero produces Infinity, which is caught and shown as "Error".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What is need for client side scripting? Write a JavaScript which accept user's first and last name and print them in reverse order with space between them.
Answer
Need for client-side scripting
Client-side scripting means code that is executed in the user's browser rather than on the web server (JavaScript is the main example). It is needed because:
- Interactivity: pages can react to clicks, typing and mouse movement, and update content dynamically.
- Faster response and less server load: tasks such as form validation run locally with no request to the server.
- Immediate feedback: errors in forms are shown instantly to the user.
- Rich user interface: animations, menus, sliders, date pickers, charts and games are possible.
- Asynchronous updates: with AJAX, parts of a page are refreshed without reloading it.
- Reduced bandwidth, because incorrect data is stopped before being sent.
Program: print first and last name in reverse order
<!DOCTYPE html>
<html>
<body>
<script>
var first = prompt("Enter your first name:");
var last = prompt("Enter your last name:");
// last name first, then first name, separated by a space
document.write("Reverse order: " + last + " " + first);
</script>
</body>
</html>
For example, if the user enters "Ram" and "Sharma", the output is "Sharma Ram".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Write a HTML code to design a form with three radio button green, red, blue and black. Write a JavaScript code that will change the background color of the page when user clicks on particular button.
Answer
Form with colour radio buttons and background change
The question lists "three" buttons but names four colours (green, red, blue, black); all four are provided.
<!DOCTYPE html>
<html>
<head><title>Background Colour</title></head>
<body>
<form>
<h3>Choose background colour:</h3>
<input type="radio" name="color" value="green" onclick="changeColor(this.value)"> Green<br>
<input type="radio" name="color" value="red" onclick="changeColor(this.value)"> Red<br>
<input type="radio" name="color" value="blue" onclick="changeColor(this.value)"> Blue<br>
<input type="radio" name="color" value="black" onclick="changeColor(this.value)"> Black<br>
</form>
<script>
function changeColor(color) {
document.body.style.backgroundColor = color;
}
</script>
</body>
</html>
Each radio button calls changeColor() on click with its own value, and the function sets the backgroundColor style of the body, so the page colour changes immediately.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What do you mean by super global variable in PHP? How to read and write CSV file in PHP explain with suitable example.
Answer
Superglobal variables in PHP
Superglobals are built-in variables that are always available in all scopes (inside functions and classes) without using the global keyword. They are associative arrays filled by PHP:
$_GET: data sent in the URL query string.$_POST: data sent by an HTTP POST form.$_REQUEST: combination of GET, POST and COOKIE data.$_SERVER: information about the server and request (e.g.$_SERVER['REQUEST_METHOD']).$_FILES: uploaded file information.$_COOKIE,$_SESSION: cookies and session data.$_ENV,$GLOBALS: environment variables and all global variables.
Reading and writing a CSV file
Writing uses fopen, fputcsv and fclose; reading uses fgetcsv.
<?php
// ---- write ----
$students = [
["Name", "Roll", "Marks"],
["Ram", 1, 78],
["Sita", 2, 85],
["Hari", 3, 69]
];
$fp = fopen("students.csv", "w");
foreach ($students as $row) {
fputcsv($fp, $row);
}
fclose($fp);
// ---- read ----
if (($fp = fopen("students.csv", "r")) !== false) {
echo "<table border='1'>";
while (($data = fgetcsv($fp, 1000, ",")) !== false) {
echo "<tr>";
foreach ($data as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>";
}
echo "</table>";
fclose($fp);
}
?>
fputcsv converts each array into a comma-separated line (quoting values when required) and fgetcsv reads a line and returns it as an array of fields; it returns false at the end of the file. Mode "a" can be used to append rows.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What is an associative array? Write a PHP program to create a multidimensional array that holds the marks of five subject like Operating system, Scripting, Numerical method, DBMS, Software Engineering and of three student Anshis, Jayanti, Niraj. Then display the average marks of each student.
Answer
Associative array
An associative array is an array in which each element is accessed by a named key (string) instead of a numeric index, i.e. it stores key => value pairs. Example: $age = ["Ram" => 20, "Sita" => 22]; and echo $age["Ram"]; prints 20.
Program: multidimensional array of marks and average
<?php
$marks = [
"Anshis" => [
"Operating System" => 70, "Scripting" => 80, "Numerical Method" => 60,
"DBMS" => 75, "Software Engineering" => 65
],
"Jayanti" => [
"Operating System" => 85, "Scripting" => 90, "Numerical Method" => 78,
"DBMS" => 88, "Software Engineering" => 79
],
"Niraj" => [
"Operating System" => 55, "Scripting" => 65, "Numerical Method" => 50,
"DBMS" => 60, "Software Engineering" => 70
]
];
echo "<table border='1'><tr><th>Student</th><th>Average</th></tr>";
foreach ($marks as $student => $subjects) {
$avg = array_sum($subjects) / count($subjects);
echo "<tr><td>$student</td><td>" . number_format($avg, 2) . "</td></tr>";
}
echo "</table>";
?>
Calculation for the sample marks:
- Anshis:
- Jayanti:
- Niraj:
The outer array is keyed by student name, each inner associative array is keyed by subject, and array_sum() divided by count() gives each student's average.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What is use of inheritance? Write an object oriented PHP program to define Person class and derive student and employee class from it to demonstrate hierarchical inheritance.
Answer
Use of inheritance
Inheritance lets a class (child) reuse and extend the properties and methods of another class (parent). It promotes code reuse, avoids repetition of common code, makes maintenance easier and models "is-a" relationships (a Student is a Person).
Hierarchical inheritance: two or more child classes derive from a single parent class. Here Student and Employee both extend Person.
<?php
class Person {
protected $name;
protected $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function showPerson() {
echo "Name: {$this->name}, Age: {$this->age}<br>";
}
}
class Student extends Person {
private $roll;
private $course;
public function __construct($name, $age, $roll, $course) {
parent::__construct($name, $age);
$this->roll = $roll;
$this->course = $course;
}
public function showStudent() {
$this->showPerson();
echo "Roll: {$this->roll}, Course: {$this->course}<br>";
}
}
class Employee extends Person {
private $empId;
private $salary;
public function __construct($name, $age, $empId, $salary) {
parent::__construct($name, $age);
$this->empId = $empId;
$this->salary = $salary;
}
public function showEmployee() {
$this->showPerson();
echo "Employee ID: {$this->empId}, Salary: Rs {$this->salary}<br>";
}
}
$s = new Student("Ram", 20, 101, "BCA");
$s->showStudent();
$e = new Employee("Sita", 30, "E-07", 45000);
$e->showEmployee();
?>
Output:
Name: Ram, Age: 20
Roll: 101, Course: BCA
Name: Sita, Age: 30
Employee ID: E-07, Salary: Rs 45000
Common members (name, age, showPerson) are written once in Person and inherited by both children.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What is syntax to create AJAX object? Design and develop dynamic web application using HTML, AJAX and PHP.
Answer
Syntax to create an AJAX object
AJAX uses the XMLHttpRequest object of the browser:
var xhr = new XMLHttpRequest();
(For very old Internet Explorer versions: new ActiveXObject("Microsoft.XMLHTTP").) Its common methods are open(method, url, async) and send(), and the properties readyState, status and responseText.
Dynamic web application: live student search (HTML + AJAX + PHP)
The user types a name in a text box and matching students appear instantly, without reloading the page. Assumed table students(id, name, course) in database college.
search.html
<!DOCTYPE html>
<html>
<head><title>Live Search</title></head>
<body>
<h3>Search student</h3>
<input type="text" id="q" onkeyup="search(this.value)" placeholder="Type a name">
<div id="result"></div>
<script>
function search(str) {
if (str.length == 0) {
document.getElementById("result").innerHTML = "";
return;
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhr.open("GET", "search.php?q=" + encodeURIComponent(str), true);
xhr.send();
}
</script>
</body>
</html>
search.php
<?php
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) die("Connection failed");
$q = $_GET['q'] ?? '';
$like = "%" . $q . "%";
$stmt = $conn->prepare("SELECT name, course FROM students WHERE name LIKE ?");
$stmt->bind_param("s", $like);
$stmt->execute();
$res = $stmt->get_result();
if ($res->num_rows > 0) {
echo "<ul>";
while ($row = $res->fetch_assoc()) {
echo "<li>" . htmlspecialchars($row['name']) . " - " . htmlspecialchars($row['course']) . "</li>";
}
echo "</ul>";
} else {
echo "No student found.";
}
$conn->close();
?>
On every key release the page sends the typed text to search.php in the background, PHP queries MySQL, and the returned HTML list is inserted in the result div.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What is difference between WordPress theme and template? Write the steps to add and edit pages in WordPress.
Answer
Theme versus template in WordPress
| Theme | Template |
|---|---|
A complete collection of files (templates, CSS, JavaScript, images, functions.php) that controls the overall look and layout of the whole site. | A single PHP file inside a theme that controls the layout of one particular type of page (e.g. single.php, page.php, archive.php, header.php). |
| Installed and activated from Appearance > Themes. | Part of a theme; chosen automatically by the template hierarchy or selected for a specific page. |
| Changing it changes the design of the entire site. | Changing it changes only the pages that use that template. |
So a theme is made up of many templates.
Steps to add a page
- Log in to the WordPress dashboard (
/wp-admin). - Go to Pages > Add New.
- Enter the page title and write the content in the block editor (add text, images and other blocks).
- Choose options in the sidebar: template, parent page, featured image, permalink.
- Click Publish (or Save Draft / Schedule).
Steps to edit a page
- Go to Pages > All Pages.
- Hover over the required page and click Edit (or click its title).
- Change the title or content in the editor.
- Click Update to save the changes; use Preview to check before updating.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
What are different way to include JavaScript in HTML document? Create a HTML page containing a division with image and its description in paragraph. Write a JavaScript function to change the value of description in the paragraph during onmouseover and onmouseout on the image.
Answer
Ways to include JavaScript in an HTML document
- Inline (in an event attribute):
<button onclick="alert('Hi')">Click</button> - Internal: placed between
<script> ... </script>tags in theheadorbodyof the same page. - External: written in a separate
.jsfile and linked with<script src="script.js"></script>, which allows reuse across pages and browser caching.
Image with description changing on mouse over / out
<!DOCTYPE html>
<html>
<head>
<title>Image Description</title>
<style>
#box { width: 320px; margin: 30px auto; text-align: center; border: 1px solid #888; padding: 10px; }
img { width: 300px; height: 200px; }
</style>
</head>
<body>
<div id="box">
<img id="pic" src="mountain.jpg" alt="Mountain"
onmouseover="showInfo()" onmouseout="hideInfo()">
<p id="desc">Move the mouse over the image.</p>
</div>
<script>
function showInfo() {
document.getElementById("desc").innerHTML =
"Mount Everest, the highest mountain in the world, lies in Nepal.";
}
function hideInfo() {
document.getElementById("desc").innerHTML = "Move the mouse over the image.";
}
</script>
</body>
</html>
When the pointer enters the image, onmouseover calls showInfo() which replaces the paragraph text; when it leaves, onmouseout calls hideInfo() which restores the original text.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
Design a HTML registration form containing text box for Name and Email, radio button for gender, selection list for education field. Write a PHP script to validate input and then store data from the form into database using database connection and appropriate query.
Answer
Registration form
Assumed database college and table:
CREATE TABLE registration (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
gender VARCHAR(10) NOT NULL,
education VARCHAR(30) NOT NULL
);
register.html
<!DOCTYPE html>
<html>
<head><title>Registration Form</title></head>
<body>
<h2>Registration Form</h2>
<form method="post" action="register.php">
Name: <input type="text" name="name"><br><br>
Email: <input type="text" name="email"><br><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="radio" name="gender" value="Other"> Other<br><br>
Education:
<select name="education">
<option value="">-- Select --</option>
<option value="SEE">SEE</option>
<option value="+2">+2</option>
<option value="Bachelor">Bachelor</option>
<option value="Master">Master</option>
</select><br><br>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
register.php
<?php
if (isset($_POST['submit'])) {
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$gender = $_POST['gender'] ?? '';
$education = $_POST['education'] ?? '';
$errors = [];
// validation
if ($name === '' || !preg_match("/^[A-Za-z .]+$/", $name)) {
$errors[] = "Name is required and may contain only letters and spaces.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "A valid email address is required.";
}
if (!in_array($gender, ["Male", "Female", "Other"])) {
$errors[] = "Please select a gender.";
}
if ($education === '') {
$errors[] = "Please select your education.";
}
if (!empty($errors)) {
foreach ($errors as $e) echo "<p style='color:red'>$e</p>";
exit;
}
// database connection
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// insert query
$stmt = $conn->prepare("INSERT INTO registration(name, email, gender, education) VALUES(?,?,?,?)");
$stmt->bind_param("ssss", $name, $email, $gender, $education);
if ($stmt->execute()) {
echo "Registration successful.";
} else {
echo "Error: " . $conn->error;
}
$stmt->close();
$conn->close();
}
?>
The script first validates every field on the server (name pattern, email with filter_var, gender and education selected), then connects with mysqli, and stores the data with a prepared INSERT query to prevent SQL injection.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
How jQuery is differing from JavaScript? Discuss different types of jQuery selectors with example.
Answer
jQuery versus JavaScript
| JavaScript | jQuery |
|---|---|
| A programming language, the core of web scripting. | A fast, small library written in JavaScript that simplifies it. |
Longer code, for example document.getElementById("a").style.color="red". | Shorter code, for example $("#a").css("color","red"). |
| Developers must handle browser differences themselves. | Hides cross-browser differences. |
AJAX needs XMLHttpRequest or fetch with more code. | Simple methods such as $.ajax(), $.get(), $.post(). |
| Animations and effects must be coded manually. | Built-in effects: fadeIn(), slideUp(), animate(). |
| No extra file to load. | Requires including the jQuery file. |
jQuery selectors
Selectors find HTML elements; they begin with $() and use CSS-like syntax.
| Type | Syntax | Example |
|---|---|---|
| Element | $("p") | $("p").hide(); hides all paragraphs |
| ID | $("#id") | $("#title").css("color","red"); |
| Class | $(".class") | $(".note").fadeOut(); |
| Universal | $("*") | $("*").css("margin","0"); |
| Multiple | $("h1, p") | $("h1, p").addClass("x"); |
| Descendant | $("div p") | all p inside any div |
| Child | $("ul > li") | only direct li children of ul |
| Attribute | $("[href]"), $("input[type='text']") | $("input[type='text']").val(""); |
| Position filters | :first, :last, :even, :odd, :eq(n) | $("tr:even").css("background","#eee"); |
| Form | :input, :checked, :selected | $(":checked").length |
Example:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("#msg").text("Hello"); // id selector
$(".item").css("color", "blue"); // class selector
$("li:first").hide(); // position filter
});
});
</script>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Write JS program to highlight all of the words over eight characters long in the paragraph text (with a red background).
Answer
Approach: read the paragraph text, split it into words while keeping the spaces and punctuation, and wrap every word with more than eight letters in a <span> with a red background.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Highlight long words</title>
<style>
.long { background-color: red; color: white; }
</style>
</head>
<body>
<p id="para">Programming languages influence development productivity significantly, especially when documentation is comprehensive.</p>
<script>
var p = document.getElementById("para");
var text = p.textContent;
// split on word boundaries: words (letters/digits) vs. everything else
var parts = text.match(/[A-Za-z0-9]+|[^A-Za-z0-9]+/g);
var html = "";
parts.forEach(function (part) {
if (/^[A-Za-z0-9]+$/.test(part) && part.length > 8) {
html += '<span class="long">' + part + '</span>';
} else {
html += part;
}
});
p.innerHTML = html;
</script>
</body>
</html>
Explanation
match(/[A-Za-z0-9]+|[^A-Za-z0-9]+/g)breaks the text into alternating word and non-word pieces, so spaces and punctuation are preserved.- Only a word piece with
length > 8(over eight characters) is wrapped in<span class="long">; the CSS class gives it the red background. - The rebuilt string is assigned back to
innerHTML. For the sample text, "Programming", "influence", "development", "productivity", "significantly", "especially", "documentation" and "comprehensive" are highlighted.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What is JavaScript? Explain different types of JavaScript with proper example.
Answer
JavaScript is a lightweight, interpreted, high-level, dynamically typed scripting language that is mainly used to make web pages interactive. It runs in the browser (client side) and, with Node.js, on the server too. It supports event-driven, functional and object-oriented styles and is standardised as ECMAScript.
Types of JavaScript (by where and how the code is placed/run)
1. Inline JavaScript - code written directly in an HTML attribute (usually an event attribute).
<button onclick="alert('Hello Nepal')">Click me</button>
2. Internal (embedded) JavaScript - code written inside a <script> tag in the same HTML page.
<script>
function greet() { document.write("Welcome to Education Nepal"); }
greet();
</script>
3. External JavaScript - code kept in a separate .js file and linked with the src attribute. It can be cached and reused by many pages.
<script src="script.js"></script>
// script.js
console.log("External file loaded");
By execution environment
- Client-side JavaScript runs in the browser and manipulates the DOM, validates forms and handles events.
- Server-side JavaScript (Node.js) runs on a server to handle requests, files and databases.
Example (client-side validation)
<input type="text" id="name">
<button onclick="check()">Submit</button>
<script>
function check() {
if (document.getElementById("name").value === "") alert("Name required");
}
</script>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Write PHP function that accepts username and password as arguments and check with student table, if credential match, redirect to dashboard page otherwise display 'Invalid username/password'.
Answer
The function below uses a PDO prepared statement to look up the user in the student table, verifies the password with password_verify() (passwords are stored hashed), starts a session and redirects to the dashboard.
<?php
session_start();
function loginStudent($username, $password)
{
$pdo = new PDO("mysql:host=localhost;dbname=college;charset=utf8", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT id, username, password FROM student WHERE username = :u LIMIT 1");
$stmt->execute([':u' => $username]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row && password_verify($password, $row['password'])) {
$_SESSION['student_id'] = $row['id'];
$_SESSION['username'] = $row['username'];
header("Location: dashboard.php");
exit;
} else {
echo "Invalid username/password";
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
loginStudent(trim($_POST['username']), $_POST['password']);
}
?>
<form method="post">
Username: <input type="text" name="username" required>
Password: <input type="password" name="password" required>
<input type="submit" value="Login">
</form>
Notes
- A prepared statement prevents SQL injection.
header("Location: ...")must be called before any output;exitstops further execution.- If passwords are stored as plain text (not recommended), replace
password_verify(...)by$row['password'] === $password.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What is jQuery? Explain XMLHttpRequest object with it's properties and methods with relevant example.
Answer
jQuery is a fast, small, cross-browser JavaScript library ("write less, do more"). It simplifies DOM selection and manipulation, event handling, animation and AJAX with a short syntax, e.g. $("#id").hide().
XMLHttpRequest (XHR) object
XHR is a built-in browser object used to exchange data with a server in the background without reloading the page (the basis of AJAX). It is created with var xhr = new XMLHttpRequest();.
Properties
| Property | Meaning |
|---|---|
readyState | State of the request: 0 unsent, 1 opened, 2 headers received, 3 loading, 4 done |
status | HTTP status code (200 OK, 404 Not Found, ...) |
statusText | Status text, e.g. "OK" |
responseText | Response as a string |
responseXML | Response as an XML document |
onreadystatechange | Function called whenever readyState changes |
timeout | Time limit of the request in ms |
Methods
| Method | Purpose |
|---|---|
open(method, url, async) | Initialises the request (GET/POST) |
send(data) | Sends the request (data only for POST) |
setRequestHeader(name, value) | Sets an HTTP header (needed for POST forms) |
abort() | Cancels the request |
getResponseHeader(name) / getAllResponseHeaders() | Reads response headers |
Example
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.open("GET", "data.php?id=5", true);
xhr.send();
The same call with jQuery: $("#result").load("data.php?id=5"); or $.get("data.php", {id: 5}, function (d) { $("#result").html(d); });.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What is Widgets? Explain different Features of CMS.
Answer
Widgets
A widget is a small, self-contained block of content or functionality that can be placed in designated areas (sidebar, footer, header) of a CMS website without writing code. Examples: search box, recent posts, categories, calendar, login form, tag cloud, social media feed. In WordPress they are managed from Appearance > Widgets by drag and drop.
Features of a CMS (Content Management System)
- Easy content creation and editing - a WYSIWYG editor lets non-programmers write, edit, format and publish pages and posts.
- Separation of content and design - content is stored in a database and presented through themes/templates, so the look can be changed without touching content.
- Themes and templates - ready-made, customisable layouts.
- Plugins/extensions and widgets - add functionality (SEO, forms, e-commerce) without coding.
- User management and roles - admin, editor, author, subscriber, each with defined permissions.
- Media management - upload and organise images, videos and documents.
- Workflow and version control - drafts, scheduling, revisions and rollback.
- SEO-friendly URLs and metadata - helps search engine ranking.
- Security and backup - authentication, updates, access control, backups.
- Multi-language and responsive support, and a central admin dashboard.
Popular examples: WordPress, Joomla, Drupal.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Write rules to create variable in PHP. How to create, store, access and destroy session in PHP?
Answer
Rules for creating variables in PHP
- A variable name starts with the dollar sign
$, e.g.$name. - The first character after
$must be a letter or underscore, never a digit ($1ais invalid). - It can contain only letters, digits and underscores (
A-Z,a-z,0-9,_); no spaces or special characters like-. - Variable names are case sensitive (
$ageand$Agediffer). - A variable cannot be named
$this. - No type declaration is needed; the type is decided by the assigned value (
$x = 5; $y = "text";).
Session in PHP
A session stores user data on the server across multiple pages; the browser keeps only a session ID (in the PHPSESSID cookie).
Create / start
<?php
session_start(); // must be called before any output
Store
$_SESSION['username'] = "ram";
$_SESSION['role'] = "student";
Access (on any page after session_start())
session_start();
echo $_SESSION['username']; // ram
if (isset($_SESSION['role'])) { echo "Role set"; }
Destroy
session_start();
unset($_SESSION['username']); // remove one variable
session_unset(); // remove all session variables
session_destroy(); // destroy the session itself
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Write short note on (any two)
a) Types of array in PHP
b) Arrow Function in JavaScript
c) jQuery UI
Answer
(a) Types of array in PHP
An array stores multiple values in one variable. PHP has three types.
- Indexed array - elements accessed by numeric index starting from 0.
$fruits = array("Apple", "Mango", "Banana");
echo $fruits[1]; // Mango
- Associative array - elements accessed by named keys.
$marks = array("Ram" => 80, "Sita" => 90);
echo $marks["Sita"]; // 90
- Multidimensional array - an array containing one or more arrays.
$students = array(
array("Ram", 20),
array("Sita", 21)
);
echo $students[1][0]; // Sita
(c) jQuery UI
jQuery UI is a curated set of user-interface widgets, effects, interactions and themes built on top of jQuery. It lets developers build rich interactive pages with little code.
- Widgets: Datepicker, Dialog, Accordion, Tabs, Autocomplete, Slider, Progressbar, Button, Menu.
- Interactions: Draggable, Droppable, Resizable, Selectable, Sortable.
- Effects: extra animations such as
effect("bounce"),show("slide"). - Themes: ThemeRoller allows customising the look.
<input type="text" id="dob">
<script>
$(function () { $("#dob").datepicker({ dateFormat: "yy-mm-dd" }); });
</script>
It requires including the jQuery library, the jQuery UI script and CSS.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 10 marks
Write server side script to create and validate form with following rule and store given data into 'patients' table with details (name, patientid, mobile, gender, address, dob, doctor name)
• Name, Mobile, doctor name, gender, dob: Required
• Mobile: 10 digit start with 98,97 or 96
• DOB: YYYY-MM-DD format
Answer
The solution has an HTML form, server-side validation in PHP, and an insert into the patients table using a prepared statement.
Table
CREATE TABLE patients (
patientid INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
mobile CHAR(10) NOT NULL,
gender VARCHAR(10) NOT NULL,
address VARCHAR(150),
dob DATE NOT NULL,
doctor_name VARCHAR(100) NOT NULL
);
patient.php
<?php
$errors = [];
$name = $mobile = $gender = $address = $dob = $doctor = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name'] ?? '');
$mobile = trim($_POST['mobile'] ?? '');
$gender = trim($_POST['gender'] ?? '');
$address = trim($_POST['address'] ?? '');
$dob = trim($_POST['dob'] ?? '');
$doctor = trim($_POST['doctor'] ?? '');
if ($name === '') $errors[] = "Name is required.";
if ($gender === '') $errors[] = "Gender is required.";
if ($doctor === '') $errors[] = "Doctor name is required.";
if ($mobile === '') {
$errors[] = "Mobile is required.";
} elseif (!preg_match('/^(98|97|96)[0-9]{8}$/', $mobile)) {
$errors[] = "Mobile must be 10 digits and start with 98, 97 or 96.";
}
if ($dob === '') {
$errors[] = "DOB is required.";
} else {
$d = DateTime::createFromFormat('Y-m-d', $dob);
if (!$d || $d->format('Y-m-d') !== $dob) {
$errors[] = "DOB must be a valid date in YYYY-MM-DD format.";
}
}
if (empty($errors)) {
$pdo = new PDO("mysql:host=localhost;dbname=hospital;charset=utf8", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare(
"INSERT INTO patients (name, mobile, gender, address, dob, doctor_name)
VALUES (:n, :m, :g, :a, :d, :dr)");
$stmt->execute([':n'=>$name, ':m'=>$mobile, ':g'=>$gender,
':a'=>$address, ':d'=>$dob, ':dr'=>$doctor]);
echo "<p>Patient saved. ID = " . $pdo->lastInsertId() . "</p>";
} else {
foreach ($errors as $e) echo "<p style='color:red'>" . htmlspecialchars($e) . "</p>";
}
}
?>
<form method="post">
Name: <input type="text" name="name" value="<?= htmlspecialchars($name) ?>"><br>
Mobile: <input type="text" name="mobile" value="<?= htmlspecialchars($mobile) ?>"><br>
Gender:
<select name="gender">
<option value="">--Select--</option>
<option>Male</option><option>Female</option><option>Other</option>
</select><br>
Address: <input type="text" name="address" value="<?= htmlspecialchars($address) ?>"><br>
DOB (YYYY-MM-DD): <input type="text" name="dob" value="<?= htmlspecialchars($dob) ?>"><br>
Doctor name: <input type="text" name="doctor" value="<?= htmlspecialchars($doctor) ?>"><br>
<input type="submit" value="Save">
</form>
Rules implemented
- Required fields are checked with an empty test.
- Mobile uses the regex
^(98|97|96)[0-9]{8}$: two prefix digits plus eight digits, 10 in total. - DOB is checked with
DateTime::createFromFormat('Y-m-d')and compared back to the input, which rejects invalid dates such as 2024-02-31. patientidis auto-generated by the database; prepared statements prevent SQL injection andhtmlspecialcharsprevents XSS.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 10 marks
What is JavaScript Event? Explain different method that are available to access DOM element using id, class, name and selector with suitable example.
Answer
JavaScript event
An event is an action or occurrence in the browser that JavaScript can detect and respond to, such as a mouse click (click), key press (keydown), form submission (submit), input change (change), page load (load) or mouse hover (mouseover). Code that runs in response is called an event handler/listener.
<button id="btn">Click</button>
<script>
document.getElementById("btn").addEventListener("click", function () {
alert("Button clicked");
});
</script>
Methods to access DOM elements
1. By id: getElementById() - returns a single element.
var h = document.getElementById("title");
h.style.color = "blue";
2. By class: getElementsByClassName() - returns a live HTMLCollection.
var items = document.getElementsByClassName("item");
for (var i = 0; i < items.length; i++) items[i].style.fontWeight = "bold";
3. By name: getElementsByName() - returns a NodeList of elements with that name attribute (common for form fields and radio buttons).
var genders = document.getElementsByName("gender");
for (var i = 0; i < genders.length; i++) {
if (genders[i].checked) console.log(genders[i].value);
}
4. By tag: getElementsByTagName()
var paras = document.getElementsByTagName("p");
5. By CSS selector: querySelector() and querySelectorAll() - querySelector returns the first match, querySelectorAll returns a static NodeList of all matches.
var first = document.querySelector("#menu .link"); // first match
var all = document.querySelectorAll("ul.list li"); // all matches
all.forEach(function (li) { li.style.color = "green"; });
Summary
| Method | Returns |
|---|---|
getElementById | one element |
getElementsByClassName | HTMLCollection (live) |
getElementsByName | NodeList |
querySelector | first matching element |
querySelectorAll | NodeList of all matches |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 10 marks
What is Inheritance? Explain different ways to implement polymorphism in PHP with proper example.
Answer
Inheritance
Inheritance is an OOP mechanism in which a class (child/subclass) acquires the properties and methods of another class (parent/superclass) using the extends keyword. It promotes code reuse and a hierarchical relationship.
<?php
class Person {
public $name;
function __construct($name) { $this->name = $name; }
function show() { echo "Name: $this->name<br>"; }
}
class Student extends Person {
public $roll;
function __construct($name, $roll) {
parent::__construct($name);
$this->roll = $roll;
}
function show() {
parent::show();
echo "Roll: $this->roll<br>";
}
}
$s = new Student("Ram", 5);
$s->show();
Polymorphism means "many forms": the same method call behaves differently depending on the object. In PHP it can be implemented in these ways.
1. Method overriding (inheritance based) - a child class redefines a parent method.
class Shape { function draw() { echo "Drawing shape<br>"; } }
class Circle extends Shape { function draw() { echo "Drawing circle<br>"; } }
class Square extends Shape { function draw() { echo "Drawing square<br>"; } }
$shapes = [new Circle(), new Square()];
foreach ($shapes as $s) $s->draw(); // each object runs its own draw()
2. Abstract classes - the parent declares an abstract method that every child must implement.
abstract class Animal { abstract function sound(); }
class Dog extends Animal { function sound() { echo "Bark<br>"; } }
class Cat extends Animal { function sound() { echo "Meow<br>"; } }
foreach ([new Dog(), new Cat()] as $a) $a->sound();
3. Interfaces - unrelated classes implement the same contract.
interface Payment { function pay($amount); }
class Esewa implements Payment { function pay($a) { echo "Paid Rs $a by eSewa<br>"; } }
class Khalti implements Payment { function pay($a) { echo "Paid Rs $a by Khalti<br>"; } }
function checkout(Payment $p) { $p->pay(500); }
checkout(new Esewa());
checkout(new Khalti());
4. Method overloading using magic methods - PHP has no true overloading, but __call() (and __callStatic()) or variable arguments (func_get_args(), default parameters) let one name handle different argument lists.
class Calc {
function __call($name, $args) {
if ($name == "add") echo array_sum($args) . "<br>";
}
}
$c = new Calc();
$c->add(2, 3); // 5
$c->add(2, 3, 4); // 9
In all cases the caller uses one interface while the behaviour is chosen at run time.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Write a JavaScript program to accept n integers into an array calculate and display the sum and average of the numbers; also find the largest number among them.
Answer
<!DOCTYPE html>
<html>
<head><title>Sum, average and largest</title></head>
<body>
<script>
var n = parseInt(prompt("How many integers?"));
var arr = [];
for (var i = 0; i < n; i++) {
arr.push(parseInt(prompt("Enter number " + (i + 1) + ":")));
}
var sum = 0;
var largest = arr[0];
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
if (arr[i] > largest) largest = arr[i];
}
var average = sum / n;
document.write("Numbers: " + arr.join(", ") + "<br>");
document.write("Sum = " + sum + "<br>");
document.write("Average = " + average.toFixed(2) + "<br>");
document.write("Largest = " + largest);
</script>
</body>
</html>
Sample run: n = 4, numbers 12, 7, 25, 6 gives sum , average , largest .
Alternative for the same results: arr.reduce((a, b) => a + b, 0) for the sum and Math.max(...arr) for the largest.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
PHP and JavaScript are both programming languages that generate dynamic results for web pages. What is their main difference, and why would you use both of them?
Answer
Main difference
- PHP is a server-side language. The code runs on the web server, can access databases and files, and only the generated HTML is sent to the browser; the user never sees the PHP source.
- JavaScript is mainly a client-side language. It runs inside the user's browser, working with the DOM, events and the page already loaded, and the user can view its source.
| Basis | PHP | JavaScript |
|---|---|---|
| Runs on | Web server | Browser (also Node.js) |
| Executed | Before page is sent | After page is loaded |
| Database / file access | Direct | Not directly (needs a server) |
| Typical use | Login, CRUD, sessions, processing forms | Validation, animation, dynamic UI, AJAX |
| Variables | Start with $ | var, let, const |
Why use both
- JavaScript gives instant feedback (form validation, menus, dynamic updates) without a round trip to the server, making the site responsive.
- PHP is needed for secure tasks: authentication, saving to MySQL, sending email and enforcing business rules. Client-side checks can be bypassed, so important validation must be repeated on the server.
- Together, with AJAX, JavaScript sends a request in the background and PHP returns data (for example checking whether a username is free), so the page updates without reloading.
- PHP can generate JavaScript data (such as JSON), joining the two sides into one application.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Explain event handling in JavaScript. Difference between map and forEach method in JavaScript.
Answer
Event handling in JavaScript
An event is something that happens to an HTML element (click, keypress, submit, load, mouseover). Event handling means writing code that runs when the event occurs. There are three ways.
1. Inline handler
<button onclick="alert('Hi')">Click</button>
2. DOM property
document.getElementById("btn").onclick = function () { alert("Hi"); };
3. addEventListener() (preferred) - allows several handlers on one event and can be removed with removeEventListener().
var btn = document.getElementById("btn");
btn.addEventListener("click", function (e) {
console.log("Clicked", e.target);
});
The handler receives an event object (type, target, key, preventDefault(), stopPropagation()). Events travel through capturing and bubbling phases, so a click on a child can also be handled by its parent (event delegation).
Difference between map() and forEach()
| Basis | forEach() | map() |
|---|---|---|
| Return value | undefined | A new array with the results |
| Purpose | Perform a side effect for each element | Transform each element |
| Chaining | Cannot be chained | Can be chained (.map().filter()) |
| Original array | Not changed unless you change it | Not changed |
var nums = [1, 2, 3];
nums.forEach(function (n) { console.log(n * 2); }); // prints 2 4 6, returns undefined
var doubled = nums.map(function (n) { return n * 2; }); // [2, 4, 6]
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is jQuery? Explain any four jQuery effect methods with example.
Answer
jQuery is a lightweight JavaScript library that simplifies DOM traversal, event handling, animation and AJAX with a short syntax such as $(selector).action().
Four jQuery effect methods
1. hide() / show() - hide or show elements, optionally with a speed.
$("#hideBtn").click(function () { $("#box").hide(1000); });
$("#showBtn").click(function () { $("#box").show(1000); });
2. toggle() - switches between hide and show.
$("#btn").click(function () { $("#box").toggle("slow"); });
3. fadeIn() / fadeOut() - gradually changes opacity (also fadeToggle(), fadeTo()).
$("#in").click(function () { $("#box").fadeIn(800); });
$("#out").click(function () { $("#box").fadeOut(800); });
4. slideDown() / slideUp() - slides an element vertically (also slideToggle()).
$("#panelHead").click(function () { $("#panel").slideToggle(500); });
Other effects: animate() for custom CSS animation, e.g. $("#box").animate({left: "200px", opacity: 0.5}, 1000);
Complete example
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<div id="box" style="width:100px;height:100px;background:orange"></div>
<button id="b">Toggle</button>
<script>
$(document).ready(function () {
$("#b").click(function () { $("#box").fadeToggle(500); });
});
</script>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Write the necessary scripts to check for unique phone numbers in the 'students' table without reloading the webpage, using AJAX.
Answer
The page sends the phone number to the server with AJAX (fetch/XHR) while the user types or leaves the field; a PHP script checks the students table and answers, and the page shows the message without reloading.
signup.html
<input type="text" id="phone" placeholder="Phone number" maxlength="10">
<span id="msg"></span>
<script>
document.getElementById("phone").addEventListener("blur", function () {
var phone = this.value.trim();
if (phone === "") return;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var msg = document.getElementById("msg");
if (xhr.responseText === "taken") {
msg.style.color = "red";
msg.textContent = "Phone number already exists";
} else {
msg.style.color = "green";
msg.textContent = "Phone number is available";
}
}
};
xhr.open("POST", "check_phone.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("phone=" + encodeURIComponent(phone));
});
</script>
check_phone.php
<?php
$pdo = new PDO("mysql:host=localhost;dbname=college;charset=utf8", "root", "");
$stmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE phone = :p");
$stmt->execute([':p' => $_POST['phone'] ?? '']);
echo $stmt->fetchColumn() > 0 ? "taken" : "available";
The server check should be repeated (and the column made UNIQUE) when the form is finally submitted.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is the use of $_FILES array? Explain different types of array available in PHP.
Answer
$_FILES array
$_FILES is a PHP superglobal associative array that holds information about files uploaded through an HTML form with method="post" and enctype="multipart/form-data". For <input type="file" name="photo"> it contains:
$_FILES['photo']['name']- original file name['type']- MIME type['tmp_name']- temporary path on the server['size']- size in bytes['error']- error code (0 = no error)
if ($_FILES['photo']['error'] == 0) {
move_uploaded_file($_FILES['photo']['tmp_name'], "uploads/" . basename($_FILES['photo']['name']));
echo "Uploaded";
}
Types of array in PHP
- Indexed array - numeric index from 0.
$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Red
- Associative array - named keys.
$age = array("Ram" => 20, "Sita" => 22);
echo $age["Sita"]; // 22
- Multidimensional array - arrays within arrays.
$m = array(array(1, 2), array(3, 4));
echo $m[1][0]; // 3
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Why is the error reporting function important for PHP applications? Explain how cookies are stored, accessed, and destroyed using server-side PHP scripts.
Answer
Importance of error reporting
- It helps developers find syntax errors, undefined variables, failed database connections and logic problems quickly during development.
- Functions such as
error_reporting(E_ALL);andini_set('display_errors', 1);show all errors while developing. - In production errors should be hidden from users (
display_errors = 0) and written to a log (log_errors = 1,error_log), because messages can reveal file paths and database details to attackers. - Handling errors properly (custom
set_error_handler(),try/catch) gives friendly messages and keeps the application stable and secure.
Cookies in PHP
A cookie is a small text file that the server asks the browser to store on the client machine; the browser sends it back with every request to that site.
Create / store - setcookie(name, value, expire, path, domain, secure, httponly); it must be called before any output.
setcookie("user", "Ram", time() + 86400 * 30, "/"); // lasts 30 days
Access - through the $_COOKIE superglobal (available from the next request).
if (isset($_COOKIE["user"])) {
echo "Welcome " . $_COOKIE["user"];
} else {
echo "Cookie not set";
}
Destroy - set the expiry time in the past.
setcookie("user", "", time() - 3600, "/");
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 10 marks
What are the major features of CMS? Implement an interface in PHP with specific properties (radius for a Circle class, side for a Square class, and base and height for a Triangle class) to ensure that multiple classes define their own implementation of a method (calculateArea), utilizing these properties in their calculations.
Answer
Major features of a CMS
- Easy content management - create, edit, publish and delete pages, posts and media through a WYSIWYG editor, with no coding knowledge.
- Themes/templates - the design is separate from the content and can be changed at any time.
- Plugins/extensions and widgets - add features such as SEO, contact forms, galleries or e-commerce.
- User roles and permissions - admin, editor, author and subscriber, each with specific rights.
- Media library - upload and organise images, videos and files.
- Version control and scheduling - drafts, revisions with rollback, and scheduled publishing.
- SEO-friendly URLs and metadata, multi-language support and responsive design.
- Security, backup and update management from a central dashboard.
PHP interface with Circle, Square and Triangle
An interface declares method signatures that every implementing class must define; each class below uses its own properties to compute the area.
<?php
interface Shape {
public function calculateArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) { $this->radius = $radius; }
public function calculateArea() {
return M_PI * $this->radius * $this->radius; // pi r^2
}
}
class Square implements Shape {
private $side;
public function __construct($side) { $this->side = $side; }
public function calculateArea() {
return $this->side * $this->side; // s^2
}
}
class Triangle implements Shape {
private $base, $height;
public function __construct($base, $height) {
$this->base = $base;
$this->height = $height;
}
public function calculateArea() {
return 0.5 * $this->base * $this->height; // 1/2 b h
}
}
$shapes = [new Circle(7), new Square(5), new Triangle(6, 4)];
foreach ($shapes as $s) {
echo get_class($s) . " area = " . round($s->calculateArea(), 2) . "<br>";
}
Output
- Circle area
- Square area
- Triangle area
Each class gives its own implementation of calculateArea(), and the loop treats all objects through the common Shape interface (polymorphism).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 10 marks
Create a webpage with a form for BCA entrance exam, including fields for name, email, mobile number, password, gender, intermediate faculty, and date of birth. Store the entered data in the MySQL database 'FOHSS' in the table 'BCA', and validate the form using JavaScript with following rules.
i. Required: All fields are mandatory.
ii. Format: Must follow valid formats, such as a proper email address and a 10-digit mobile number.
iii. Valid Date: Ensure the input follows a valid date format for date of birth (YYYY-MM-DD).
Answer
The solution has three parts: the database table, the HTML form with JavaScript validation, and the PHP script that stores the data in database FOHSS, table BCA.
Database
CREATE DATABASE FOHSS;
USE FOHSS;
CREATE TABLE BCA (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
mobile CHAR(10) NOT NULL,
password VARCHAR(255) NOT NULL,
gender VARCHAR(10) NOT NULL,
faculty VARCHAR(50) NOT NULL,
dob DATE NOT NULL
);
bca_form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BCA Entrance Form</title>
</head>
<body>
<h2>BCA Entrance Exam Form</h2>
<form id="frm" method="post" action="save.php" onsubmit="return validate()">
Name: <input type="text" name="name" id="name"><br><br>
Email: <input type="text" name="email" id="email"><br><br>
Mobile: <input type="text" name="mobile" id="mobile"><br><br>
Password: <input type="password" name="password" id="password"><br><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="radio" name="gender" value="Other"> Other<br><br>
Intermediate Faculty:
<select name="faculty" id="faculty">
<option value="">--Select--</option>
<option>Science</option><option>Management</option>
<option>Humanities</option><option>Education</option>
</select><br><br>
Date of Birth (YYYY-MM-DD): <input type="text" name="dob" id="dob"><br><br>
<input type="submit" value="Register">
</form>
<script>
function validate() {
var name = document.getElementById("name").value.trim();
var email = document.getElementById("email").value.trim();
var mobile = document.getElementById("mobile").value.trim();
var pass = document.getElementById("password").value;
var faculty = document.getElementById("faculty").value;
var dob = document.getElementById("dob").value.trim();
var gender = document.querySelector('input[name="gender"]:checked');
// i. Required
if (!name || !email || !mobile || !pass || !gender || !faculty || !dob) {
alert("All fields are mandatory");
return false;
}
// ii. Format
var emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRe.test(email)) { alert("Enter a valid email address"); return false; }
if (!/^[0-9]{10}$/.test(mobile)) { alert("Mobile must be exactly 10 digits"); return false; }
if (pass.length < 6) { alert("Password must be at least 6 characters"); return false; }
// iii. Valid date YYYY-MM-DD
if (!/^\d{4}-\d{2}-\d{2}$/.test(dob)) { alert("DOB must be in YYYY-MM-DD format"); return false; }
var p = dob.split("-");
var d = new Date(p[0], p[1] - 1, p[2]);
if (d.getFullYear() != p[0] || d.getMonth() != p[1] - 1 || d.getDate() != p[2]) {
alert("DOB is not a valid date");
return false;
}
return true;
}
</script>
</body>
</html>
save.php
<?php
$conn = new mysqli("localhost", "root", "", "FOHSS");
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt = $conn->prepare(
"INSERT INTO BCA (name, email, mobile, password, gender, faculty, dob)
VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss",
$_POST['name'], $_POST['email'], $_POST['mobile'], $hash,
$_POST['gender'], $_POST['faculty'], $_POST['dob']);
if ($stmt->execute()) {
echo "Registration successful";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
$conn->close();
JavaScript validation gives quick feedback in the browser; because it can be bypassed, a production system should also validate on the server.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 10 marks
Write a JavaScript program to create and design a calculator with the following features:
• When the user presses numbers or an arithmetic operator, it should append to the input bar.
• When the user presses the equals (=) button, the entered value should be calculated and displayed.
Answer
The calculator has an input bar and buttons. Pressing a number or operator appends it to the bar, = evaluates the expression, and C clears.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Calculator</title>
<style>
#calc { width: 220px; margin: 30px auto; padding: 10px; border: 1px solid #555; }
#display { width: 100%; height: 40px; font-size: 20px; text-align: right; box-sizing: border-box; }
.btn { width: 48px; height: 40px; margin: 3px; font-size: 18px; }
</style>
</head>
<body>
<div id="calc">
<input type="text" id="display" readonly>
<div>
<button class="btn" onclick="press('7')">7</button>
<button class="btn" onclick="press('8')">8</button>
<button class="btn" onclick="press('9')">9</button>
<button class="btn" onclick="press('/')">/</button>
</div>
<div>
<button class="btn" onclick="press('4')">4</button>
<button class="btn" onclick="press('5')">5</button>
<button class="btn" onclick="press('6')">6</button>
<button class="btn" onclick="press('*')">*</button>
</div>
<div>
<button class="btn" onclick="press('1')">1</button>
<button class="btn" onclick="press('2')">2</button>
<button class="btn" onclick="press('3')">3</button>
<button class="btn" onclick="press('-')">-</button>
</div>
<div>
<button class="btn" onclick="press('0')">0</button>
<button class="btn" onclick="press('.')">.</button>
<button class="btn" onclick="calculate()">=</button>
<button class="btn" onclick="press('+')">+</button>
</div>
<div><button class="btn" style="width:96px" onclick="clearAll()">C</button>
<button class="btn" style="width:96px" onclick="back()">Del</button></div>
</div>
<script>
var display = document.getElementById("display");
function press(ch) { // append number/operator to the input bar
display.value += ch;
}
function calculate() { // evaluate the expression on '='
var expr = display.value;
if (!/^[0-9+\-*\/.() ]+$/.test(expr)) return; // allow only safe characters
try {
var result = new Function("return " + expr)();
display.value = (isFinite(result)) ? result : "Error";
} catch (e) {
display.value = "Error";
}
}
function clearAll() { display.value = ""; }
function back() { display.value = display.value.slice(0, -1); }
</script>
</body>
</html>
Working
press()adds the clicked character to the input value, so7,+,3builds "7+3".calculate()first checks the string contains only digits and operators (this blocks arbitrary code), then evaluates it and shows the result. For "7+3" the display shows 10.- Division by zero gives
Infinity, which is caught byisFiniteand displayed as "Error".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 5 marks
Write the code to create and remove new list item into Unordered list dynamically into JavaScript DOM.
Answer
The DOM lets JavaScript create elements with createElement(), attach them with appendChild(), and delete them with removeChild() or remove().
<!DOCTYPE html>
<html>
<body>
<input type="text" id="itemText" placeholder="Enter item">
<button onclick="addItem()">Add Item</button>
<button onclick="removeItem()">Remove Last Item</button>
<ul id="myList">
<li>Apple</li>
<li>Mango</li>
</ul>
<script>
function addItem() {
var text = document.getElementById("itemText").value.trim();
if (text === "") {
alert("Please enter an item");
return;
}
var li = document.createElement("li"); // create element
li.appendChild(document.createTextNode(text)); // add text
document.getElementById("myList").appendChild(li); // attach to ul
document.getElementById("itemText").value = "";
}
function removeItem() {
var list = document.getElementById("myList");
if (list.lastElementChild) {
list.removeChild(list.lastElementChild); // remove last li
} else {
alert("List is empty");
}
}
</script>
</body>
</html>
createElement("li")creates a new list item node in memory.appendChild()inserts it at the end of the<ul>, so it appears on the page.removeChild()(orelement.remove()) deletes a child node from the list.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 1+4 marks
What is Ajax? Write code to check if phone is available or not into signup form using Ajax?
Answer
Ajax (Asynchronous JavaScript and XML) is a technique for exchanging data with a server in the background, using XMLHttpRequest or fetch(), and updating part of a web page without reloading the whole page.
Checking phone availability in a signup form
Client side (signup.html):
<form>
<input type="text" id="phone" placeholder="Phone number" onblur="checkPhone()">
<span id="msg"></span>
<button type="submit">Sign Up</button>
</form>
<script>
function checkPhone() {
var phone = document.getElementById("phone").value;
if (phone === "") return;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var msg = document.getElementById("msg");
if (xhr.responseText === "taken") {
msg.style.color = "red";
msg.innerHTML = "Phone number is already registered";
} else {
msg.style.color = "green";
msg.innerHTML = "Phone number is available";
}
}
};
xhr.open("GET", "check_phone.php?phone=" + encodeURIComponent(phone), true);
xhr.send();
}
</script>
Server side (check_phone.php):
<?php
$conn = new mysqli("localhost", "root", "", "mydb");
$phone = $_GET['phone'];
$stmt = $conn->prepare("SELECT id FROM users WHERE phone = ?");
$stmt->bind_param("s", $phone);
$stmt->execute();
$stmt->store_result();
echo ($stmt->num_rows > 0) ? "taken" : "available";
?>
When the user leaves the phone field, the request is sent asynchronously, PHP checks the database, and the message is shown without a page reload.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 1+4 marks
What is JS arrow function? Explain use of forEach() and map() method in JavaScript.
Answer
Arrow function: an arrow function is a short syntax for writing a function expression in ES6, using => instead of the function keyword. It also does not have its own this; it takes this from the surrounding scope.
// normal function
var add = function (a, b) { return a + b; };
// arrow function
const add = (a, b) => a + b;
const square = n => n * n; // single parameter, no brackets needed
forEach() runs a given function once for every element of an array. It returns nothing (undefined) and is used for side effects such as printing.
const nums = [1, 2, 3, 4];
nums.forEach((n, index) => console.log(index + ": " + n));
// 0: 1, 1: 2, 2: 3, 3: 4
map() calls a function on every element and returns a new array of the results. The original array is not changed.
const nums = [1, 2, 3, 4];
const doubled = nums.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]
The main difference is that forEach() only iterates, whereas map() transforms the array and returns the new one.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 1+4 marks
What is session? Describe how can we relate session with cookie?
Answer
Session: a session is a way of storing information about a user (such as login status or a shopping cart) on the server across multiple page requests. HTTP is stateless, so a session lets the server remember the user while they browse the site. In PHP it is started with session_start() and data is kept in $_SESSION.
Relation between session and cookie
- When a session starts, the server generates a unique session ID and stores the user's data on the server.
- The server sends this ID to the browser in a cookie, by default named
PHPSESSID. - On every later request the browser sends this cookie back, and the server uses the ID to find that user's session data.
- So the cookie only holds the ID on the client, while the actual data stays on the server. This makes sessions safer than storing data directly in cookies.
- If cookies are disabled, the session ID can instead be passed in the URL.
- Deleting the cookie, or destroying the session, ends the link between the user and the stored data.
<?php
session_start(); // creates ID and sends PHPSESSID cookie
$_SESSION['user'] = "Ram"; // stored on the server
echo session_id(); // same value as the PHPSESSID cookie
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 1+4 marks
What is CMS? Describe major features of CMS.
Answer
CMS (Content Management System): a CMS is software that lets users create, edit, organise, publish and manage website content without writing code. Examples include WordPress, Joomla and Drupal.
Major features of a CMS
- Easy content creation and editing: a WYSIWYG editor lets non-programmers add text, images and media.
- Templates and themes: the design is separated from the content, so the look can be changed without touching the content.
- User management and roles: administrators, editors and authors have different permissions.
- Plugins and extensions: extra functions such as SEO, forms and e-commerce can be added easily.
- Media management: a library for uploading and organising images, videos and documents.
- Workflow and versioning: drafts, scheduled publishing and revision history.
- SEO friendliness: clean URLs, meta tags and sitemaps.
- Security and backup: login control, updates and data backup.
- Database-driven: content is stored in a database (for example MySQL) and pages are generated dynamically.
- Multi-language and responsive support for wider reach.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 5 marks
Describe different types of arrays in PHP with proper example.
Answer
An array in PHP stores multiple values in a single variable. PHP has three types of arrays.
1. Indexed array: elements are accessed by a numeric index starting from 0.
<?php
$fruits = array("Apple", "Mango", "Banana");
echo $fruits[1]; // Mango
foreach ($fruits as $f) echo $f . " ";
?>
2. Associative array: elements are accessed by named keys.
<?php
$marks = array("Ram" => 80, "Sita" => 90, "Hari" => 75);
echo $marks["Sita"]; // 90
foreach ($marks as $name => $m) echo "$name scored $m<br>";
?>
3. Multidimensional array: an array that contains one or more other arrays, used to represent tables.
<?php
$students = array(
array("Ram", 80, "BCA"),
array("Sita", 90, "BCA")
);
echo $students[1][0]; // Sita
for ($i = 0; $i < 2; $i++) {
for ($j = 0; $j < 3; $j++) echo $students[$i][$j] . " ";
echo "<br>";
}
?>
Useful functions include count(), array_push(), array_pop(), sort() and print_r().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 5 marks
Write PHP code to upload file in PHP with rules of file type (png, jpg, gif) and file size maximum 500kb?
Answer
<!-- upload.html -->
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="submit" name="submit" value="Upload">
</form>
<?php
// upload.php
if (isset($_POST['submit'])) {
$file = $_FILES['myfile'];
if ($file['error'] !== UPLOAD_ERR_OK) {
die("Error while uploading file.");
}
$allowedExt = array("png", "jpg", "jpeg", "gif");
$maxSize = 500 * 1024; // 500 KB
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowedExt)) {
die("Only PNG, JPG and GIF files are allowed.");
}
if ($file['size'] > $maxSize) {
die("File size must not exceed 500 KB.");
}
$folder = "uploads/";
if (!is_dir($folder)) {
mkdir($folder, 0777, true);
}
$newName = uniqid() . "." . $ext;
if (move_uploaded_file($file['tmp_name'], $folder . $newName)) {
echo "File uploaded successfully: " . $newName;
} else {
echo "Failed to upload file.";
}
}
?>
The form needs enctype="multipart/form-data" and method="post". The file information is in $_FILES. The code checks the extension and the size (500 KB = 512000 bytes) before move_uploaded_file() saves it.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 5+5 marks
Write a program to perform Create and List Operation for student record with (roll, course, name, email, phone, result) database using PHP and MySQL?
Answer
Database setup
CREATE DATABASE school;
USE school;
CREATE TABLE student (
roll INT PRIMARY KEY,
course VARCHAR(50),
name VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(15),
result VARCHAR(20)
);
Create operation (create.php)
<?php
$conn = new mysqli("localhost", "root", "", "school");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['save'])) {
$roll = $_POST['roll'];
$course = $_POST['course'];
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$result = $_POST['result'];
$stmt = $conn->prepare("INSERT INTO student (roll, course, name, email, phone, result) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("isssss", $roll, $course, $name, $email, $phone, $result);
if ($stmt->execute()) {
echo "Record inserted successfully";
} else {
echo "Error: " . $stmt->error;
}
}
?>
<form method="post">
Roll: <input type="number" name="roll" required><br>
Course: <input type="text" name="course" required><br>
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
Phone: <input type="text" name="phone" required><br>
Result: <input type="text" name="result" required><br>
<input type="submit" name="save" value="Save">
</form>
List operation (list.php)
<?php
$conn = new mysqli("localhost", "root", "", "school");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$res = $conn->query("SELECT * FROM student ORDER BY roll");
echo "<table border='1'>
<tr><th>Roll</th><th>Course</th><th>Name</th><th>Email</th><th>Phone</th><th>Result</th></tr>";
if ($res->num_rows > 0) {
while ($row = $res->fetch_assoc()) {
echo "<tr>
<td>" . htmlspecialchars($row['roll']) . "</td>
<td>" . htmlspecialchars($row['course']) . "</td>
<td>" . htmlspecialchars($row['name']) . "</td>
<td>" . htmlspecialchars($row['email']) . "</td>
<td>" . htmlspecialchars($row['phone']) . "</td>
<td>" . htmlspecialchars($row['result']) . "</td>
</tr>";
}
} else {
echo "<tr><td colspan='6'>No records found</td></tr>";
}
echo "</table>";
?>
create.php inserts a record using a prepared statement. list.php selects all rows and displays them in an HTML table.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 3+7 marks
Difference between abstract class and interface. Write PHP code to create a parent class Book with properties title, author and price and a method displayBookDetails(). Also create two subclasses TextBook and ReferenceBook that inherit from Book. Add property subject in TextBook and edition in ReferenceBook. Create methods to display complete details of each book.
Answer
Difference between abstract class and interface
| Abstract class | Interface |
|---|---|
Declared with abstract class. | Declared with interface. |
| Can have both abstract and concrete (implemented) methods. | Methods are only declared (no body); implementation is in the class. |
| Can have properties (variables) and constructors. | Cannot have instance properties or constructors (only constants). |
A class extends only one abstract class (extends). | A class can implement many interfaces (implements). |
| Members may be public, protected or private. | All methods must be public. |
| Used for classes that share common code ("is-a" relation). | Used to define a contract/capability that unrelated classes can follow. |
PHP program
<?php
class Book {
public $title;
public $author;
public $price;
public function __construct($title, $author, $price) {
$this->title = $title;
$this->author = $author;
$this->price = $price;
}
public function displayBookDetails() {
echo "Title: $this->title<br>";
echo "Author: $this->author<br>";
echo "Price: Rs $this->price<br>";
}
}
class TextBook extends Book {
public $subject;
public function __construct($title, $author, $price, $subject) {
parent::__construct($title, $author, $price);
$this->subject = $subject;
}
public function displayTextBookDetails() {
echo "<b>Text Book</b><br>";
$this->displayBookDetails();
echo "Subject: $this->subject<br><br>";
}
}
class ReferenceBook extends Book {
public $edition;
public function __construct($title, $author, $price, $edition) {
parent::__construct($title, $author, $price);
$this->edition = $edition;
}
public function displayReferenceBookDetails() {
echo "<b>Reference Book</b><br>";
$this->displayBookDetails();
echo "Edition: $this->edition<br><br>";
}
}
$t = new TextBook("PHP Basics", "Ram Sharma", 650, "Web Programming");
$r = new ReferenceBook("Advanced PHP", "Sita Thapa", 1200, "3rd");
$t->displayTextBookDetails();
$r->displayReferenceBookDetails();
?>
TextBook and ReferenceBook inherit title, author, price and displayBookDetails() from Book. Each adds its own property and a method that prints the complete details.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 1+3+6 marks
Why do we need validation? Explain with examples which validation is best among client side and server-side validation. Write JavaScript program that use countries array to display 50 countries into tabular format with 4 countries in a row.
Answer
Why validation is needed
Validation checks that the data entered by a user is correct, complete and in the proper format before it is processed or stored. It prevents empty or wrong entries (for example an invalid email or phone number), keeps the database clean, protects against malicious input such as SQL injection and XSS, and gives users quick feedback.
Client-side vs server-side validation
- Client-side validation runs in the browser using JavaScript or HTML5 attributes. It is fast and gives instant feedback without a server request. Example: checking that the name field is not empty before submit. However, the user can disable JavaScript or alter the page, so it cannot be trusted for security.
- Server-side validation runs on the server (PHP, etc.) after the form is submitted. It cannot be bypassed by the user and is secure. Example: checking in PHP that the email is valid and that the username is not already in the database. It is slower because it needs a request to the server.
Server-side validation is the best and is essential, because only it is reliable and secure. In practice, both are used together: client-side for a good user experience and server-side as the final safeguard.
JavaScript program to display 50 countries, 4 per row
<!DOCTYPE html>
<html>
<body>
<div id="output"></div>
<script>
var countries = [
"Nepal","India","China","Bhutan","Bangladesh","Sri Lanka","Pakistan","Afghanistan","Maldives","Myanmar",
"Thailand","Vietnam","Laos","Cambodia","Malaysia","Singapore","Indonesia","Philippines","Japan","South Korea",
"North Korea","Mongolia","Russia","Kazakhstan","Iran","Iraq","Saudi Arabia","Turkey","Egypt","Kenya",
"Nigeria","Ghana","Ethiopia","South Africa","Morocco","Algeria","France","Germany","Italy","Spain",
"Portugal","United Kingdom","Ireland","Norway","Sweden","Canada","United States","Mexico","Brazil","Australia"
];
var perRow = 4;
var html = "<table border='1' cellpadding='6'>";
for (var i = 0; i < countries.length; i++) {
if (i % perRow === 0) html += "<tr>";
html += "<td>" + countries[i] + "</td>";
if (i % perRow === perRow - 1) html += "</tr>";
}
// close last row if incomplete (50 countries = 12 full rows + 2 cells)
if (countries.length % perRow !== 0) {
for (var k = countries.length % perRow; k < perRow; k++) html += "<td></td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("output").innerHTML = html;
</script>
</body>
</html>
A new row <tr> starts when i % 4 === 0 and closes after every fourth cell. With 50 countries there are 12 full rows and a last row with 2 countries, which is padded with empty cells.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BCA 2020 Fourth Semester Operating System (TU board exam, 2020), TU BCA 2021 Fourth Semester Operating System (TU board exam, 2021), TU BCA 2022 Fourth Semester Operating System (TU board exam, 2022), TU BCA 2023 Fourth Semester Operating System (TU board exam, 2023), TU BCA 2024 Fourth Semester Operating System (TU board exam, 2024), TU BCA 2025 Fourth Semester Operating System (TU board exam, 2025), TU BCA 2026 Fourth Semester Operating System (TU board exam, 2026), TU BCA 2020 Fourth Semester Database Management System (TU board exam, 2020), TU BCA 2021 Fourth Semester Database Management System (TU board exam, 2021), TU BCA 2022 Fourth Semester Database Management System (TU board exam, 2022), TU BCA 2023 Fourth Semester Database Management System (TU board exam, 2023), TU BCA 2024 Fourth Semester Database Management System (TU board exam, 2024), TU BCA 2025 Fourth Semester Database Management System (TU board exam, 2025), TU BCA 2026 Fourth Semester Database Management System (TU board exam, 2026), TU BCA 2020 Fourth Semester Software Engineering (TU board exam, 2020), TU BCA 2021 Fourth Semester Software Engineering (TU board exam, 2021), TU BCA 2022 Fourth Semester Software Engineering (TU board exam, 2022), TU BCA 2023 Fourth Semester Software Engineering (TU board exam, 2023), TU BCA 2024 Fourth Semester Software Engineering (TU board exam, 2024), TU BCA 2025 Fourth Semester Software Engineering (TU board exam, 2025), TU BCA 2026 Fourth Semester Software Engineering (TU board exam, 2026), TU BCA 2020 Fourth Semester Numerical Method (TU board exam, 2020), TU BCA 2021 Fourth Semester Numerical Method (TU board exam, 2021), TU BCA 2022 Fourth Semester Numerical Method (TU board exam, 2022), TU BCA 2023 Fourth Semester Numerical Method (TU board exam, 2023), TU BCA 2024 Fourth Semester Numerical Method (TU board exam, 2024), TU BCA 2025 Fourth Semester Numerical Method (TU board exam, 2025), TU BCA 2026 Fourth Semester Numerical Method (TU board exam, 2026), TU BCA 2019 Fourth Semester Scripting Language (TU board exam, 2019), TU BCA 2020 Fourth Semester Scripting Language (TU board exam, 2020), TU BCA 2021 Fourth Semester Scripting Language (TU board exam, 2021), TU BCA 2022 Fourth Semester Scripting Language (TU board exam, 2022), TU BCA 2023 Fourth Semester Scripting Language (TU board exam, 2023), TU BCA 2024 Fourth Semester Scripting Language (TU board exam, 2024), TU BCA 2025 Fourth Semester Scripting Language (TU board exam, 2025) and TU BCA 2026 Fourth Semester Scripting Language (TU board exam, 2026). Answers are written for this site; check them against your class notes.