Chapter 8
Web Programming II (old course)
TU BIM past exam questions
Past questions and answers
83 questions set from this chapter. Most repeated first.
- 2015 AD · 1 mark
What is web browser?
Answer
A web browser is application software used to access, retrieve and display web pages and other resources from web servers on the internet. It sends HTTP requests and renders HTML, CSS and JavaScript. Examples are Chrome, Firefox and Edge.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
What are the basic rules of PHP?
Answer
- PHP code is written inside
<?php ... ?>tags. - Every statement ends with a semicolon
;. - Variable names start with
$, are case-sensitive, and cannot start with a digit. - Keywords, function names and class names are not case-sensitive.
- Comments use
//,#or/* ... */. - Output is produced with
echoorprint. - PHP files are saved with the
.phpextension and run on a web server.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
Write syntax of if statement.
Answer
if (condition) {
// statements executed when the condition is true
} elseif (condition2) {
// statements for the second condition
} else {
// statements when no condition is true
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
What is array padding? Give example.
Answer
Array padding means extending an array to a given size by filling it with a chosen value. In PHP this is done with array_pad(array, size, value). A positive size pads on the right, a negative size pads on the left.
$a = array(1, 2, 3);
$b = array_pad($a, 5, 0); // 1, 2, 3, 0, 0
$c = array_pad($a, -5, 0); // 0, 0, 1, 2, 3
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
Write code to assign values to an array.
Answer
<?php
// using array()
$fruits = array("Apple", "Banana", "Mango");
// assigning by index
$nums[0] = 10;
$nums[1] = 20;
$nums[2] = 30;
// associative array
$marks["Ram"] = 80;
$marks["Sita"] = 90;
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
Write syntax of function in PHP which returns value to the calling function.
Answer
function functionName($param1, $param2) {
// statements
return $value;
}
$result = functionName(5, 10); // the returned value is stored in $result
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
How is the connection with the web server created?
Answer
The connection from a browser to a web server is created as follows: the user enters a URL, the browser resolves the domain name to an IP address through DNS, opens a TCP connection to the server (port 80 for HTTP, 443 for HTTPS), and sends an HTTP request. The server processes it and returns an HTTP response, which the browser displays.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
What is the role of mysql_fetch_array() in php?
Answer
mysql_fetch_array() fetches one row of a query result (returned by mysql_query()) and returns it as an array that can be accessed both by numeric index and by column name. Each call moves to the next row, and it returns false when no rows are left, so it is normally used in a while loop.
while ($row = mysql_fetch_array($result)) {
echo $row['name'];
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
What does mktime() function do?
Answer
mktime() returns the Unix timestamp (seconds since 1 January 1970) for a given date and time. Its syntax is mktime(hour, minute, second, month, day, year). For example, mktime(0, 0, 0, 12, 25, 2015) gives the timestamp of 25 December 2015, which can be formatted with date().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 4 marks
Write a program in PHP to add three numbers
Answer
<?php
$a = 10;
$b = 20;
$c = 30;
$sum = $a + $b + $c;
echo "Sum of three numbers = " . $sum; // Sum of three numbers = 60
?>
The three numbers are stored in variables, added with the + operator, and the result is printed with echo.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 4 marks
Write a program to display first and last character of a string.
Answer
<?php
$str = "Education";
$first = $str[0]; // or substr($str, 0, 1)
$last = $str[strlen($str) - 1]; // or substr($str, -1)
echo "First character: " . $first . "<br>";
echo "Last character: " . $last;
?>
Output:
First character: E
Last character: n
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 4 marks
Create two integer arrays of size 5 each with data in them. Then display sum of all the number of both arrays.
Answer
<?php
$a = array(1, 2, 3, 4, 5);
$b = array(6, 7, 8, 9, 10);
$sum = 0;
for ($i = 0; $i < 5; $i++) {
$sum += $a[$i] + $b[$i];
}
echo "Sum of all numbers = " . $sum;
// equivalent: array_sum($a) + array_sum($b)
?>
The sum of the first array is 15 and of the second is 40, so the output is Sum of all numbers = 55.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 4 marks
Write a program in PHP to store "coding in PHP" in a file named "coding.txt".
Answer
<?php
$file = fopen("coding.txt", "w"); // open for writing (creates the file)
if ($file) {
fwrite($file, "coding in PHP");
fclose($file);
echo "Data written to coding.txt";
} else {
echo "Unable to open file";
}
// shorter: file_put_contents("coding.txt", "coding in PHP");
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 4 marks
Make following table using PHP.
Name Age Gender R 21 M A 20 F
Answer
<?php
$data = array(
array("R", 21, "M"),
array("A", 20, "F")
);
echo "<table border='1'>";
echo "<tr><th>Name</th><th>Age</th><th>Gender</th></tr>";
foreach ($data as $row) {
echo "<tr>";
foreach ($row as $cell) {
echo "<td>" . $cell . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
This prints a table with the header row Name, Age, Gender followed by the rows R, 21, M and A, 20, F.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 5 marks
Explain the steps and functions required to delete records from database table.
Answer
Deleting records from a MySQL table in PHP needs these steps:
- Connect to the database server with
mysql_connect(host, user, password). If it fails, stop withdie(). - Select the database with
mysql_select_db("dbname", $conn). - Write the DELETE query, normally with a
WHEREclause (without it all rows are deleted):DELETE FROM student WHERE id = 5. - Execute the query with
mysql_query($sql, $conn). It returnstrueon success. - Check the result (and optionally
mysql_affected_rows()for the number of deleted rows) and report an error withmysql_error()if needed. - Close the connection with
mysql_close($conn).
<?php
$conn = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("school", $conn);
$sql = "DELETE FROM student WHERE id = 5";
if (mysql_query($sql, $conn)) {
echo mysql_affected_rows() . " record(s) deleted";
} else {
echo "Error: " . mysql_error();
}
mysql_close($conn);
?>
In newer PHP versions the same steps use mysqli_connect(), mysqli_query() and mysqli_close().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 5 marks
Differentiate between GET and POST method. How these two methods of data submission is handled in PHP? Explain with example.
Answer
Difference between GET and POST
| Basis | GET | POST |
|---|---|---|
| Data location | Appended to the URL as a query string (page.php?name=Ram&age=20) | Sent in the HTTP request body |
| Visibility | Visible in the address bar, history and logs | Not shown in the URL |
| Security | Less secure; unsuitable for passwords | More secure (still needs HTTPS) |
| Size limit | Limited (about 2000 characters) | No practical limit |
| Data type | Only ASCII characters | Any data, including binary/file uploads |
| Bookmarking | Can be bookmarked and cached | Cannot be bookmarked |
| Use | Fetching or searching data | Submitting, inserting or updating data |
Handling in PHP
PHP collects submitted form data in the superglobal arrays $_GET (for the GET method) and $_POST (for the POST method). Each is an associative array whose keys are the name attributes of the form fields. $_REQUEST holds both.
<form method="get" action="process.php">
Name: <input type="text" name="name">
<input type="submit" value="Send by GET">
</form>
<form method="post" action="process.php">
Name: <input type="text" name="name">
Password: <input type="password" name="pass">
<input type="submit" value="Send by POST">
</form>
<?php
// process.php
if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['name'])) {
echo "GET: Hello " . htmlspecialchars($_GET['name']);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['name'])) {
echo "POST: Hello " . htmlspecialchars($_POST['name']);
}
?>
With GET the browser requests process.php?name=Ram and PHP reads $_GET['name']. With POST the values travel in the request body and PHP reads $_POST['name'].
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 1 mark
List out the advantages of using PHP.
Answer
- Open source and free to use.
- Easy to learn, with C-like syntax.
- Platform independent (Windows, Linux, macOS) and works with Apache, IIS, etc.
- Supports many databases such as MySQL, PostgreSQL and Oracle.
- Fast, with a large community, many frameworks and good documentation.
- Can be embedded directly in HTML.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 1 mark
What is use of identical operator (===)?
Answer
The identical operator === returns true only if both operands have the same value and the same data type. For example, 5 === "5" is false (integer vs string), while 5 == "5" is true. 5 === 5 is true.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 1 mark
Explain briefly how different kinds of numbers are stored using PHP variables.
Answer
PHP is loosely typed, so a variable's type is set by the value assigned to it. Whole numbers are stored as integers ($a = 25;, also in hex 0x1A, octal 012 or binary 0b101). Numbers with a decimal point or exponent are stored as floats/doubles ($b = 3.14;, $c = 2.5e3;). If an integer exceeds the platform's integer range, PHP automatically converts it to a float. The function gettype() or var_dump() shows the type.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 1 mark
Write syntax of foreach loop?
Answer
foreach loops over each element of an array.
foreach ($array as $value) {
// statements using $value
}
foreach ($array as $key => $value) {
// statements using $key and $value
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 1 mark
How a function is declared using default values for its arguments.
Answer
A default value is given in the parameter list with =. If the caller omits that argument, the default is used. Parameters with defaults should come after those without.
function greet($name, $greeting = "Hello") {
echo "$greeting, $name!";
}
greet("Ram"); // Hello, Ram!
greet("Sita", "Namaste"); // Namaste, Sita!
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 1 mark
"Validations should be performed on both the client and server side". Why?
Answer
Client-side validation (JavaScript) gives instant feedback and reduces server load and unnecessary requests, but it can be bypassed: a user can disable JavaScript or send a crafted request directly. Server-side validation is the only one that is reliable and secure, since it runs on the server where the user has no control; it protects against invalid data, SQL injection and XSS. Hence both are used: client-side for user convenience and speed, server-side for security and data integrity.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 1 mark
Define server variable HTTP_USER_AGENT with example.
Answer
$_SERVER['HTTP_USER_AGENT'] is a server (superglobal) variable that holds the User-Agent string sent by the client's browser, identifying the browser, version and operating system.
<?php
echo $_SERVER['HTTP_USER_AGENT'];
// e.g. Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0 Safari/537.36
?>
It is often used to detect the browser or device type.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 1 mark
What are the advantages of using PEAR over PHP built in functions to work with database?
Answer
PEAR (for example PEAR DB or MDB2) provides a database abstraction layer. Its advantages over PHP's built-in database functions are:
- Same functions work for different databases (MySQL, Oracle, PostgreSQL), so changing the database needs little code change (portability).
- Provides consistent, easier error handling.
- Offers ready-made, tested reusable code that shortens development.
- Supports features such as prepared statements and simpler fetching of results.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 1 mark
How will you display current date in web page using PHP statement?
Answer
Use the date() function:
<?php echo date("Y-m-d"); ?>
For example, echo date("l, d F Y"); prints a date such as "Tuesday, 21 October 2026".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 1 mark
What is use of mysql_fetch_assoc() function?
Answer
mysql_fetch_assoc() fetches one row of a query result as an associative array, where the keys are the column names. Each call returns the next row and it returns false when no rows remain, so it is normally used in a while loop: while ($row = mysql_fetch_assoc($result)) { echo $row['name']; }.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 4 marks
Write a PHP program to create a web form that contains a textbox for name, and checkboxes for hobbies. When a form is submitted, check a name is entered and at least one of the hobbies is selected.
Answer
<form method="post" action="">
Name: <input type="text" name="name"><br>
Hobbies:
<input type="checkbox" name="hobbies[]" value="Reading"> Reading
<input type="checkbox" name="hobbies[]" value="Music"> Music
<input type="checkbox" name="hobbies[]" value="Sports"> Sports<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if (isset($_POST['submit'])) {
$errors = array();
$name = trim($_POST['name']);
if ($name == "") {
$errors[] = "Name is required.";
}
if (!isset($_POST['hobbies']) || count($_POST['hobbies']) == 0) {
$errors[] = "Select at least one hobby.";
}
if (count($errors) > 0) {
foreach ($errors as $e) {
echo "<p style='color:red'>$e</p>";
}
} else {
echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Hobbies: " . htmlspecialchars(implode(", ", $_POST['hobbies']));
}
}
?>
The checkbox group is named hobbies[] so PHP receives the selected values as an array. An unchecked group is not submitted at all, hence the isset() test.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 1 MCQ
Loading…
- 2016 AD · 4 marks
Write a PHP program to display the contents of a database. Make your own assumptions about database.
Answer
Assumed database school with table student(id, name, address, phone).
<?php
$conn = mysqli_connect("localhost", "root", "", "school");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($conn, "SELECT id, name, address, phone FROM student");
if (mysqli_num_rows($result) > 0) {
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Address</th><th>Phone</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No records found.";
}
mysqli_close($conn);
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 4 marks
Write a PHP function that makes three arguments: principle, rate and time and returns the calculated interest. Make all the required validation to calculate the interest.
Answer
Simple interest is calculated by
where is principal, the rate (% per year) and the time in years.
<?php
function calculateInterest($principal, $rate, $time) {
// validation
if (!is_numeric($principal) || !is_numeric($rate) || !is_numeric($time)) {
return "Error: all values must be numeric.";
}
if ($principal <= 0 || $rate <= 0 || $time <= 0) {
return "Error: principal, rate and time must be greater than zero.";
}
return ($principal * $rate * $time) / 100;
}
echo calculateInterest(10000, 10, 2); // 2000
echo calculateInterest(-500, 10, 2); // Error message
?>
For Rs 10000 at 10% for 2 years the interest is Rs 2000.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 4 marks
What is file? Write a program to write value taken from user to a file.
Answer
A file is a named collection of related data stored permanently on secondary storage (disk). PHP can create, read, write and delete files using functions such as fopen(), fwrite(), fgets(), fclose().
<form method="post" action="">
Enter text: <input type="text" name="data">
<input type="submit" name="save" value="Save">
</form>
<?php
if (isset($_POST['save'])) {
$data = $_POST['data'];
$fp = fopen("data.txt", "a"); // open for appending
if ($fp) {
fwrite($fp, $data . "\n");
fclose($fp);
echo "Data written to file.";
} else {
echo "Cannot open file.";
}
}
?>
Mode "w" would overwrite the file each time, while "a" appends.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 4 marks
Write a PHP program to create a multidimensional array that holds the cities of districts in Kathmandu valley such as Kathmandu (Newroad, Durbar Marg, Thamel), Lalitpur (Patan, Jawalakhel, Kupandole), Bhaktpur (Durbar Square, Suryabinayak). Then display the contents of array.
Answer
<?php
$cities = array(
"Kathmandu" => array("Newroad", "Durbar Marg", "Thamel"),
"Lalitpur" => array("Patan", "Jawalakhel", "Kupandole"),
"Bhaktapur" => array("Durbar Square", "Suryabinayak")
);
foreach ($cities as $district => $places) {
echo "<b>$district</b><ul>";
foreach ($places as $place) {
echo "<li>$place</li>";
}
echo "</ul>";
}
?>
The outer array is associative (district => array of places); the nested foreach loops print each district and its places.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 5 marks
Explain the importance of default values in a form with examples.
Answer
A default value is the value shown in a form field when the form first loads (or re-displayed after a failed submission). It is set with the value attribute for text boxes, checked for check boxes and radio buttons, and selected for options in a list.
Importance
- Saves the user's time by pre-filling common values (for example country "Nepal").
- Guides the user on the expected input.
- Reduces errors and ensures a valid value is submitted even if the user does not touch the field.
- When validation fails, re-displaying the entered values (sticky form) means the user need not retype everything.
Example
<?php $name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ""; ?>
<form method="post">
Name: <input type="text" name="name" value="<?php echo $name; ?>"><br>
Country: <input type="text" name="country" value="Nepal"><br>
Gender:
<input type="radio" name="gender" value="M" checked> Male
<input type="radio" name="gender" value="F"> Female<br>
City:
<select name="city">
<option value="ktm" selected>Kathmandu</option>
<option value="pkr">Pokhara</option>
</select>
<input type="submit" value="Submit">
</form>
Here the country text box, the Male radio button and Kathmandu option are pre-selected as defaults, and the name field keeps its previous value after submission.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2016 AD · 5 marks
What is session? How are session variables handled in PHP? Explain with example.
Answer
A session is a way to store information about a user across multiple pages of a website. Because HTTP is stateless, the server creates a unique session ID for each visitor, keeps the data on the server, and sends the ID to the browser (usually in a cookie PHPSESSID). The data is available until the session is destroyed or times out.
Handling session variables in PHP
session_start()starts or resumes a session; it must be called before any output.- Variables are stored in and read from the superglobal
$_SESSIONarray. unset($_SESSION['key'])removes one variable.session_destroy()ends the session.
Example
<?php
// page1.php
session_start();
$_SESSION['user'] = "Ram";
$_SESSION['role'] = "admin";
echo "Session set.";
?>
<?php
// page2.php
session_start();
if (isset($_SESSION['user'])) {
echo "Welcome " . $_SESSION['user'];
}
?>
<?php
// logout.php
session_start();
session_unset();
session_destroy();
?>
Sessions are used for login systems, shopping carts and user preferences.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
What do you mean by register global variables?
Answer
Register globals was a PHP setting (register_globals in php.ini) which automatically created global variables for request data, so ?name=Ram would create $name directly instead of $_GET['name']. It is insecure because users could inject values into variables, so it was deprecated in PHP 5.3 and removed in PHP 5.4. Superglobals like $_GET and $_POST should be used instead.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
How constant is created in PHP?
Answer
A constant is created with the define() function or the const keyword. Its value cannot be changed later, and it has no $ prefix.
define("SITE", "Education Nepal");
const PI = 3.14159;
echo SITE;
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
What does substr() do?
Answer
substr($string, $start, $length) returns a part (substring) of a string, beginning at position $start (counted from 0; negative counts from the end) with optional length $length. Example: echo substr("Kathmandu", 0, 4); prints Kath.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
Define web server
Answer
A web server is software (and the computer that runs it) that stores web pages and serves them to clients over HTTP in response to browser requests. It processes requests, runs server-side scripts such as PHP and returns the result as HTML. Examples are Apache, Nginx and IIS.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
Why trim() function used in php?
Answer
trim() removes whitespace (spaces, tabs, newlines) or other specified characters from the beginning and end of a string. It is used to clean user input before validation or storage, for example so that a name consisting only of spaces is detected as empty. Example: trim(" Ram ") gives "Ram".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
What do you mean by URL?
Answer
URL (Uniform Resource Locator) is the unique address of a resource on the internet. It has the form protocol://domain:port/path?query#fragment, for example https://www.example.com/pages/index.php?id=5. It tells the browser which protocol to use, which server to contact and which resource to fetch.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
Differentiate between mysql_fetch_assoc() and mysql_fetch_array().
Answer
mysql_fetch_assoc() | mysql_fetch_array() |
|---|---|
| Returns the row only as an associative array (column names as keys) | Returns the row as both numeric and associative array by default (MYSQL_BOTH) |
Access as $row['name'] | Access as $row[0] or $row['name'] |
| Uses less memory | Uses more memory since data is held twice |
mysql_fetch_array() can behave like mysql_fetch_assoc() if called with MYSQL_ASSOC.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
Write syntax of PHP function to connect mysql database.
Answer
$conn = mysql_connect("hostname", "username", "password");
mysql_select_db("database_name", $conn);
In the newer MySQLi extension: $conn = mysqli_connect("hostname", "username", "password", "database_name");
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
How can you generate current date and time in PHP?
Answer
Use the date() function with a format string:
echo date("Y-m-d H:i:s"); // e.g. 2026-10-21 14:30:05
time() returns the current Unix timestamp and date_default_timezone_set("Asia/Kathmandu"); sets the time zone first.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
List two advantages of using CSV file.
Answer
- Simple, plain-text format that is easy to create, read and edit with any text editor or spreadsheet program.
- Small in size and highly portable, so data can easily be exchanged between different applications and databases.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 3 marks
Differentiate between server side validation (check for empty, alphabets, numbers, email and password length validation)
Answer
Server-side validation is done on the web server after the form is submitted, so it cannot be bypassed. Client-side validation is done in the browser with JavaScript, and is faster but can be bypassed. The checks asked for are done on the server in PHP as follows.
| Check | PHP technique |
|---|---|
| Empty | empty(trim($v)) or trim($v) == "" |
| Alphabets only | preg_match("/^[A-Za-z ]+$/", $v) or ctype_alpha($v) |
| Numbers | is_numeric($v) or ctype_digit($v) |
filter_var($v, FILTER_VALIDATE_EMAIL) | |
| Password length | strlen($v) >= 8 |
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = trim($_POST['name']);
$age = trim($_POST['age']);
$email = trim($_POST['email']);
$pass = $_POST['password'];
$err = array();
if ($name == "") $err[] = "Name is required.";
elseif (!preg_match("/^[A-Za-z ]+$/", $name)) $err[] = "Name must contain only alphabets.";
if (!is_numeric($age)) $err[] = "Age must be a number.";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $err[] = "Invalid email.";
if (strlen($pass) < 8) $err[] = "Password must be at least 8 characters.";
if (empty($err)) echo "Valid data.";
else foreach ($err as $e) echo "$e<br>";
}
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 3 marks
Write a function to calculate sum of all even numbers that occurs between given two integers passed as parameters.
Answer
<?php
function sumEven($a, $b) {
if ($a > $b) { // swap if given in reverse order
$t = $a; $a = $b; $b = $t;
}
$sum = 0;
for ($i = $a; $i <= $b; $i++) {
if ($i % 2 == 0) {
$sum += $i;
}
}
return $sum;
}
echo sumEven(1, 10); // 2+4+6+8+10 = 30
?>
The function loops from the smaller to the larger integer and adds each number whose remainder on division by 2 is zero. (Whether the end values themselves count if they are even is a matter of interpretation; here they are included.)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 3 marks
Create an array that contains your name, address, age, gender. Then write the array to the file name "profile.csv"
Answer
<?php
$profile = array("Ram Sharma", "Kathmandu", 21, "Male");
$fp = fopen("profile.csv", "w");
if ($fp) {
fputcsv($fp, array("Name", "Address", "Age", "Gender")); // header row
fputcsv($fp, $profile);
fclose($fp);
echo "Profile written to profile.csv";
} else {
echo "Cannot open file.";
}
?>
fputcsv() converts the array into one comma-separated line, so profile.csv contains:
Name,Address,Age,Gender
"Ram Sharma",Kathmandu,21,Male
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 3 marks
Create a login system, making your own assumptions about database, authorize the login credentials.
Answer
Assumed database mydb with table users(id, username, password) where the password is stored as a hash made by password_hash().
<?php
// login.php
session_start();
$msg = "";
if (isset($_POST['login'])) {
$conn = mysqli_connect("localhost", "root", "", "mydb");
$user = mysqli_real_escape_string($conn, trim($_POST['username']));
$pass = $_POST['password'];
if ($user == "" || $pass == "") {
$msg = "Enter username and password.";
} else {
$res = mysqli_query($conn, "SELECT * FROM users WHERE username='$user'");
if ($row = mysqli_fetch_assoc($res)) {
if (password_verify($pass, $row['password'])) {
$_SESSION['user'] = $row['username'];
header("Location: welcome.php");
exit;
}
}
$msg = "Invalid username or password.";
}
}
?>
<form method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="login" value="Login">
</form>
<p style="color:red"><?php echo $msg; ?></p>
<?php
// welcome.php
session_start();
if (!isset($_SESSION['user'])) {
header("Location: login.php");
exit;
}
echo "Welcome " . $_SESSION['user'];
?>
The credentials are checked against the database, a session records the logged-in user, and protected pages redirect to login when no session exists.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 3 marks
Write PHP function to calculate the difference between two dates in PHP
Answer
<?php
function dateDifference($date1, $date2) {
$d1 = new DateTime($date1);
$d2 = new DateTime($date2);
$diff = $d1->diff($d2);
return $diff->y . " years, " . $diff->m . " months, " . $diff->d . " days (total "
. $diff->days . " days)";
}
echo dateDifference("2024-01-15", "2026-10-21");
?>
DateTime::diff() returns a DateInterval with year, month, day and total-day properties. An older approach is (strtotime($d2) - strtotime($d1)) / 86400 for the number of days.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 4 marks
Write down the PHP script to display data from a database table to a web page in following format. Make your own assumption about database and table name.
Id Product name Category Brand Size
Answer
Assumed database shop with table product(id, product_name, category, brand, size).
<?php
$conn = mysqli_connect("localhost", "root", "", "shop");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($conn, "SELECT id, product_name, category, brand, size FROM product");
echo "<table border='1' cellpadding='5'>";
echo "<tr><th>Id</th><th>Product name</th><th>Category</th><th>Brand</th><th>Size</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['product_name'] . "</td>";
echo "<td>" . $row['category'] . "</td>";
echo "<td>" . $row['brand'] . "</td>";
echo "<td>" . $row['size'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 4 marks
Define array and string. Create associative array of size seven and display the contents in ascending order of key.
Answer
Array: a variable that stores multiple values under one name, each accessed by an index or key. PHP has indexed, associative and multidimensional arrays.
String: a sequence of characters enclosed in single or double quotes, such as "Hello".
Associative array of size seven, displayed in ascending order of key
<?php
$days = array(
"sun" => "Sunday",
"mon" => "Monday",
"tue" => "Tuesday",
"wed" => "Wednesday",
"thu" => "Thursday",
"fri" => "Friday",
"sat" => "Saturday"
);
ksort($days); // sort by key, ascending
foreach ($days as $key => $value) {
echo "$key => $value<br>";
}
?>
ksort() sorts by key in ascending order, so the output is fri, mon, sat, sun, thu, tue, wed with their values.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
List the advantages of using PHP.
Answer
- Open source and free.
- Easy to learn and use.
- Platform independent and runs on most web servers.
- Connects easily to databases, especially MySQL.
- Fast execution, large community support and many frameworks.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
What is the use of trim()?
Answer
trim() removes whitespace (or other given characters) from both ends of a string. It is used to clean user input before validation or storing. Example: trim(" hello ") returns "hello".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
Write syntax of foreach loop.
Answer
foreach ($array as $value) {
// statements
}
foreach ($array as $key => $value) {
// statements
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
Write PHP source code to create multi-dimensional array.
Answer
<?php
$students = array(
array("Ram", 20, "Kathmandu"),
array("Sita", 21, "Pokhara"),
array("Hari", 22, "Lalitpur")
);
for ($i = 0; $i < count($students); $i++) {
for ($j = 0; $j < count($students[$i]); $j++) {
echo $students[$i][$j] . " ";
}
echo "<br>";
}
?>
A multidimensional array is an array whose elements are themselves arrays.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
How global variables can be accessed inside the function?
Answer
A global variable is not visible inside a function by default. It can be accessed in two ways:
$x = 10;
function show() {
global $x; // using the global keyword
echo $x;
}
function show2() {
echo $GLOBALS['x']; // using the $GLOBALS array
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
Differentiate between fetchAll() and getAll().
Answer
fetchAll() is a PDO method (PDOStatement::fetchAll()) that returns all remaining rows of a result set at once as an array. It is a standard PHP function.
getAll() is not a built-in PHP function. It is a method found in some database abstraction libraries (such as PEAR DB/MDB2) that executes a query and returns all rows as an array in a single call. fetchAll() is called after execute(), whereas getAll() combines the query and the fetch.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
Write a statement to print the date in "2075/03/03" format.
Answer
echo date("Y/m/d");
date() formats the current date. Y gives the 4-digit year, m the 2-digit month and d the 2-digit day, so the output has the form 2075/03/03.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
What is the use of str_replace() in PHP?
Answer
str_replace() replaces all occurrences of a search string with a replacement string inside a given string (or array). It is case-sensitive.
echo str_replace("World", "Nepal", "Hello World"); // Hello Nepal
Syntax: str_replace($search, $replace, $subject [, &$count]).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
What is isset() function?
Answer
isset() checks whether a variable is declared and its value is not NULL. It returns true if the variable exists and has a non-null value, otherwise false. It is commonly used to check form inputs, $_GET, $_POST and $_SESSION values.
if (isset($_POST['submit'])) {
echo "Form submitted";
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 4 marks
Write a PHP program to create a form that contains two textboxes that accepts number and a submit button. When a submit button is clicked, sum of two numbers will be displayed.
Answer
<!DOCTYPE html>
<html>
<body>
<form method="post" action="">
First number: <input type="text" name="num1"><br>
Second number: <input type="text" name="num2"><br>
<input type="submit" name="submit" value="Add">
</form>
<?php
if (isset($_POST['submit'])) {
$a = $_POST['num1'];
$b = $_POST['num2'];
if (is_numeric($a) && is_numeric($b)) {
$sum = $a + $b;
echo "Sum = " . $sum;
} else {
echo "Please enter valid numbers.";
}
}
?>
</body>
</html>
The form posts to the same page. When the submit button is clicked, the values are read from $_POST, validated, added and displayed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 4 marks
Write a PHP program to print the following List in array and display as follows:
a. Bachelor in Information Management.
b. Bachelor in Business Administration.
c. Bachelor in Business Studies.
Answer
<?php
$programs = array(
"Bachelor in Information Management",
"Bachelor in Business Administration",
"Bachelor in Business Studies"
);
$label = 'a';
foreach ($programs as $p) {
echo $label . ". " . $p . ".<br>";
$label++;
}
?>
Output:
a. Bachelor in Information Management.
b. Bachelor in Business Administration.
c. Bachelor in Business Studies.
PHP's string increment turns 'a' into 'b' and then 'c', which gives the list labels.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 4 marks
Write a PHP program to find difference between two dates.
Answer
<?php
$date1 = new DateTime("2075-03-03");
$date2 = new DateTime("2075-06-15");
$diff = $date1->diff($date2);
echo "Difference: " . $diff->y . " years, "
. $diff->m . " months, "
. $diff->d . " days<br>";
echo "Total days: " . $diff->days;
?>
DateTime::diff() returns a DateInterval object with the years, months and days between the two dates, and days gives the total number of days. Alternatively, (strtotime($d2) - strtotime($d1)) / 86400 gives the difference in days.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 4 marks
Write a PHP to read name and address from a database and display them.
Answer
<?php
$conn = mysqli_connect("localhost", "root", "", "college");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT name, address FROM student";
$result = mysqli_query($conn, $sql);
echo "<table border='1'><tr><th>Name</th><th>Address</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['address'] . "</td></tr>";
}
echo "</table>";
mysqli_close($conn);
?>
Assumption: database college has a table student(name, address).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 4 marks
Write a PHP program to copy content of one text file to another.
Answer
<?php
$source = fopen("source.txt", "r");
$dest = fopen("destination.txt", "w");
if (!$source || !$dest) {
die("Unable to open file.");
}
while (!feof($source)) {
$line = fgets($source);
fwrite($dest, $line);
}
fclose($source);
fclose($dest);
echo "Content copied successfully.";
?>
Alternatively, copy("source.txt", "destination.txt"); or file_put_contents("destination.txt", file_get_contents("source.txt")); does the same in one line.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 5 marks
Write session variables are used? Explain with examples.
Answer
A session is a way to store information about a user on the server so that it is available across multiple pages of a website. HTTP is stateless, so sessions are used to remember the user (for example, after login). The server creates a unique session ID, which is sent to the browser (usually as the cookie PHPSESSID), and the data itself is kept on the server.
Session variables are stored in the $_SESSION superglobal array.
Steps
- Call
session_start()at the very top of every page, before any output. - Set variables:
$_SESSION['key'] = value; - Read them on any other page after
session_start(). - Remove with
unset($_SESSION['key'])and end the session withsession_destroy().
Example
page1.php
<?php
session_start();
$_SESSION['username'] = "Ram";
$_SESSION['role'] = "student";
echo "Session variables are set.";
?>
page2.php
<?php
session_start();
echo "Welcome " . $_SESSION['username']; // Welcome Ram
?>
logout.php
<?php
session_start();
session_unset();
session_destroy();
?>
Uses: login and authentication, shopping carts, keeping user preferences, and passing data between pages without exposing it in the URL.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 5 marks
Write short notes on:
a. Require vs include
b. Default function parameters
c. String Manipulation in PHP
Answer
(a) Require vs include
Both insert and execute the code of another file in the current script.
includegives a warning (E_WARNING) if the file is missing and the script continues.requiregives a fatal error (E_COMPILE_ERROR) if the file is missing and the script stops.include_onceandrequire_onceinclude the file only once.
Use require for essential files (such as database configuration) and include for optional ones (such as a sidebar).
include "header.php";
require "config.php";
(b) Default function parameters
A parameter can be given a default value in the function definition. If the caller omits the argument, the default is used. Parameters with defaults should come after those without.
function greet($name, $greeting = "Hello") {
return "$greeting, $name";
}
echo greet("Sita"); // Hello, Sita
echo greet("Sita", "Namaste"); // Namaste, Sita
(c) String manipulation in PHP
PHP provides many built-in functions to work with strings:
strlen($s)gives the length.strtoupper($s),strtolower($s),ucfirst($s)change case.substr($s, start, len)extracts part of a string.strpos($s, $find)finds the position of a substring.str_replace($a, $b, $s)replaces text.trim($s)removes whitespace.strrev($s)reverses a string.explode()andimplode()convert between strings and arrays.
$s = "Hello World";
echo strlen($s); // 11
echo strtoupper($s); // HELLO WORLD
echo substr($s, 0, 5); // Hello
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
"PHP is cross platform". Justify it.
Answer
PHP is cross platform because PHP code is interpreted by the PHP engine rather than compiled for a specific machine. The same script runs without change on Windows, Linux, macOS and other operating systems, and works with web servers such as Apache, Nginx and IIS and with databases such as MySQL and PostgreSQL.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
What is dynamic website?
Answer
A dynamic website is a website whose content is generated at the time of the request, usually by server-side scripts (such as PHP) and a database. The content can change according to the user, input or time, for example, login pages, online shops and news sites. In contrast, a static website shows the same fixed HTML pages to everyone.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
How do you find the length of string in PHP?
Answer
Use the built-in strlen() function, which returns the number of characters (bytes) in a string.
$str = "Nepal";
echo strlen($str); // 5
For multibyte (UTF-8) strings, mb_strlen() should be used.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
Define associative array.
Answer
An associative array is an array in which each element is identified by a named key (usually a string) instead of a numeric index.
$marks = array("Ram" => 80, "Sita" => 90);
echo $marks["Sita"]; // 90
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
List any four register global variables.
Answer
Four PHP superglobal variables:
$_GET: data sent through the URL query string.$_POST: data sent through an HTTP POST request.$_SESSION: session variables.$_COOKIE: cookie values sent by the browser.
Others include $_SERVER, $_FILES, $_REQUEST and $GLOBALS.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
What do you mean by epoch timestamp?
Answer
An epoch (Unix) timestamp is the number of seconds that have elapsed since 1 January 1970, 00:00:00 UTC (the Unix epoch). In PHP, time() returns the current timestamp, and functions such as date(), mktime() and strtotime() use it.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
What is the purpose of mktime() function?
Answer
mktime() returns the Unix timestamp for a given date and time. Its syntax is mktime(hour, minute, second, month, day, year). It is used to build timestamps, find the weekday of a date and do date arithmetic.
$ts = mktime(0, 0, 0, 7, 15, 2024);
echo date("l, d M Y", $ts); // Monday, 15 Jul 2024
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
What is CSV file?
Answer
A CSV (Comma Separated Values) file is a plain text file that stores tabular data, where each line is a record and the fields in a record are separated by commas. It is widely used to exchange data between spreadsheets and databases. In PHP it can be read with fgetcsv() and written with fputcsv().
itemId,itemDesc,rate,qty
1,Pen,10,50
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
Write method of php used to connect database.
Answer
PHP can connect to a MySQL database using:
mysqli_connect()(MySQLi extension):
$conn = mysqli_connect("localhost", "username", "password", "dbname");
- or
new PDO()(PDO extension):
$conn = new PDO("mysql:host=localhost;dbname=dbname", "username", "password");
The old mysql_connect() is deprecated and removed in PHP 7.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 4 marks
Write a PHP function that accepts list of countries and a search value as parameters and checks whether the search value is in the list or not.
Answer
<?php
function searchCountry($countries, $search) {
if (in_array($search, $countries)) {
echo "$search is in the list.";
} else {
echo "$search is not in the list.";
}
}
$list = array("Nepal", "India", "China", "Japan");
searchCountry($list, "Nepal"); // Nepal is in the list.
searchCountry($list, "Brazil"); // Brazil is not in the list.
?>
in_array() checks whether a value exists in an array. Pass true as the third argument for strict comparison.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 4 marks
Write a PHP program that reads CSV file which contains (itemId, itemDesc, rate, qty) and insert them into a database. Assumption can be made if required.
Answer
<?php
$conn = mysqli_connect("localhost", "root", "", "shop");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$file = fopen("items.csv", "r");
fgetcsv($file); // skip header row (itemId,itemDesc,rate,qty)
$stmt = mysqli_prepare($conn,
"INSERT INTO item (itemId, itemDesc, rate, qty) VALUES (?, ?, ?, ?)");
while (($data = fgetcsv($file, 1000, ",")) !== false) {
$id = $data[0];
$desc = $data[1];
$rate = $data[2];
$qty = $data[3];
mysqli_stmt_bind_param($stmt, "isdi", $id, $desc, $rate, $qty);
mysqli_stmt_execute($stmt);
}
fclose($file);
mysqli_close($conn);
echo "Data imported successfully.";
?>
Assumptions: the CSV file is items.csv with a header row, and the database shop has a table item(itemId INT, itemDesc VARCHAR, rate DECIMAL, qty INT).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 4 marks
Write php function that accepts year (int) and month (int) as arguments and displays the calendar.
Answer
<?php
function showCalendar($year, $month) {
$firstDay = mktime(0, 0, 0, $month, 1, $year);
$daysInMonth = date("t", $firstDay);
$startDay = date("w", $firstDay); // 0 = Sunday
$title = date("F Y", $firstDay);
echo "<table border='1'>";
echo "<tr><th colspan='7'>$title</th></tr>";
echo "<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th>
<th>Thu</th><th>Fri</th><th>Sat</th></tr><tr>";
for ($i = 0; $i < $startDay; $i++) {
echo "<td></td>";
}
for ($day = 1; $day <= $daysInMonth; $day++) {
echo "<td>$day</td>";
if (($day + $startDay) % 7 == 0 && $day != $daysInMonth) {
echo "</tr><tr>";
}
}
$remaining = (7 - ($daysInMonth + $startDay) % 7) % 7;
for ($i = 0; $i < $remaining; $i++) {
echo "<td></td>";
}
echo "</tr></table>";
}
showCalendar(2024, 7);
?>
mktime() gives the timestamp of the first day, date("t") the number of days in the month and date("w") the weekday of the first day, which decides how many empty cells come first.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 4 marks
Write php function that accepts username and password as argument and check credentials in user table which is stored in database if record found welcome the user with welcome message and if not found redirect user to the login page. Make your own assumptions about database.
Answer
Assumption: database site has table users(id, username, password) where the password is stored as a hash created with password_hash().
<?php
session_start();
function checkLogin($username, $password) {
$conn = mysqli_connect("localhost", "root", "", "site");
if (!$conn) {
die("Connection failed");
}
$stmt = mysqli_prepare($conn,
"SELECT password FROM users WHERE username = ?");
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $hash);
if (mysqli_stmt_fetch($stmt) && password_verify($password, $hash)) {
$_SESSION['user'] = $username;
echo "Welcome, " . htmlspecialchars($username) . "!";
} else {
header("Location: login.php");
exit();
}
mysqli_close($conn);
}
checkLogin($_POST['username'], $_POST['password']);
?>
If a matching record is found the user is welcomed; otherwise header("Location: login.php") redirects to the login page. A prepared statement prevents SQL injection.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 4 marks
Write a PHP program to create a web form that contains a textbox for name, a textbox for age, check boxes for hobbies and a textarea for comments and a submit button. When a submit button is clicked, the following validations should be done.
a. Name should be between 2 to 10 characters and should contain characters only.
b. Age should be the numbers between 16 and 55.
c. At least one hobby should be selected.
d. Comment is required.
Answer
<?php
$errors = array();
if (isset($_POST['submit'])) {
$name = trim($_POST['name']);
$age = $_POST['age'];
$hobbies = isset($_POST['hobby']) ? $_POST['hobby'] : array();
$comment = trim($_POST['comment']);
// a. name: 2 to 10 letters only
if (!preg_match("/^[A-Za-z]{2,10}$/", $name)) {
$errors[] = "Name must be 2 to 10 characters and contain letters only.";
}
// b. age between 16 and 55
if (!is_numeric($age) || $age < 16 || $age > 55) {
$errors[] = "Age must be a number between 16 and 55.";
}
// c. at least one hobby
if (count($hobbies) == 0) {
$errors[] = "Select at least one hobby.";
}
// d. comment required
if ($comment == "") {
$errors[] = "Comment is required.";
}
if (count($errors) == 0) {
echo "Form submitted successfully.";
} else {
foreach ($errors as $e) {
echo "<p style='color:red'>$e</p>";
}
}
}
?>
<form method="post" action="">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
Hobbies:
<input type="checkbox" name="hobby[]" value="Reading"> Reading
<input type="checkbox" name="hobby[]" value="Music"> Music
<input type="checkbox" name="hobby[]" value="Sports"> Sports<br>
Comments:<br>
<textarea name="comment" rows="4" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BIM Fourth Semester ACC 202 Cost and Management Accounting Model Question 2024 (Faculty of Management model question 2024, BIM fourth semester (new course), via EducateNepal), TU BIM Fourth Semester ECO 206 Economics for Business Model Question 2024 (Faculty of Management model question 2024, BIM fourth semester (new course), via EducateNepal), TU BIM Fourth Semester IT 239 Web Technology II Model Question 2024 (Faculty of Management model question 2024, BIM fourth semester (new course), via EducateNepal), TU BIM Fourth Semester IT 240 Business Data Communication and Networking Model Question 2024 (Faculty of Management model question 2024, BIM fourth semester (new course), via EducateNepal), TU BIM Fourth Semester IT 220 Database Management System Model Question 2024 (Faculty of Management model question 2024, BIM fourth semester (new course), via EducateNepal), TU BIM Fourth Semester IT 241 Operating System Model Question 2024 (Faculty of Management model question 2024, BIM fourth semester (new course), via EducateNepal), TU BBA/BIM 4th Semester Cost and Management Accounting 2014 (model question) (Faculty of Management model question 2014 (old course), via EducateNepal), TU BIM Data Structure and Algorithm with Java (IT 218) 2015 AD (Board exam paper, 2015 AD), TU BIM Data Structure and Algorithm with Java (IT 218) 2016 AD (Board exam paper, 2016 AD), TU BIM Data Structure and Algorithm with Java (IT 218) 2017 AD (Board exam paper, 2017 AD), TU BIM Data Structure and Algorithm with Java (IT 218) 2018 AD (Board exam paper, 2018 AD), TU BIM Data Structure and Algorithm with Java (IT 218) 2019 AD (Board exam paper, 2019 AD), TU BIM Web Programming II (IT 219) 2015 AD (Board exam paper, 2015 AD), TU BIM Web Programming II (IT 219) 2016 AD (Board exam paper, 2016 AD), TU BIM Web Programming II (IT 219) 2017 AD (Board exam paper, 2017 AD), TU BIM Web Programming II (IT 219) 2018 AD (Board exam paper, 2018 AD), TU BIM Web Programming II (IT 219) 2019 AD (Board exam paper, 2019 AD), TU BIM Database Management System (ITC 218) 2007 AD (Board exam paper, 2007 AD), TU BIM Database Management System (ITC 218) 2008 AD (Board exam paper, 2008 AD), TU BIM Database Management System (ITC 218) 2009 AD (Board exam paper, 2009 AD), TU BIM Database Management System (ITC 218) 2010 AD (Board exam paper, 2010 AD), TU BIM Database Management System (ITC 218) 2011 AD (Board exam paper, 2011 AD), TU BIM Database Management System (ITC 218) 2012 AD (Board exam paper, 2012 AD), TU BIM Database Management System (ITC 218) 2013 AD (Board exam paper, 2013 AD), TU BIM Database Management System (ITC 218) 2014 AD (Board exam paper, 2014 AD), TU BIM Database Management System (ITC 218) 2015 AD (Board exam paper, 2015 AD), TU BIM Database Management System (ITC 218) 2016 AD (Board exam paper, 2016 AD), TU BIM Database Management System (ITC 218) 2017 AD (Board exam paper, 2017 AD), TU BIM Database Management System (ITC 218) 2018 AD (Board exam paper, 2018 AD), TU BIM Database Management System (ITC 218) 2019 AD (Board exam paper, 2019 AD), TU BIM Micro Economics (ECO 201) 2007 AD (Board exam paper, 2007 AD), TU BIM Micro Economics (ECO 201) 2008 AD (Board exam paper, 2008 AD), TU BIM Micro Economics (ECO 201) 2009 AD (Board exam paper, 2009 AD), TU BIM Micro Economics (ECO 201) 2010 AD (Board exam paper, 2010 AD), TU BIM Micro Economics (ECO 201) 2014 AD (Board exam paper, 2014 AD), TU BIM Micro Economics (ECO 201) 2015 AD (Board exam paper, 2015 AD), TU BIM Micro Economics (ECO 201) 2016 AD (Board exam paper, 2016 AD), TU BIM Micro Economics (ECO 201) 2017 AD (Board exam paper, 2017 AD), TU BIM Micro Economics (ECO 201) 2018 AD (Board exam paper, 2018 AD) and TU BIM Micro Economics (ECO 201) 2019 AD (Board exam paper, 2019 AD). Answers are written for this site; check them against your class notes.