Skip to main content

Chapter 3

Web Technology II

NEB Class 12 past exam questions

Past questions and answers

28 questions set from this chapter. Most repeated first.

  • 2083 Baishakh · 1 mark

Which JavaScript method is used to write HTML output? (a) document.write() (b) document.output() (c) console.log() (d) document.writeHTML()

Answer

(a) document.write()

It writes HTML or text directly into the document (web page) at the point where the script runs. console.log() only prints to the browser's developer console, while the other two methods do not exist in JavaScript.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • 2083 Baishakh · 1 mark

What will be the output of the following PHP code?
<?php
echo b;
?>
(a) 0 (b) 1 (c) 2 (d) 5

Answer

None of the given options (0, 1, 2, 5) is the output.

In PHP, b without quotes or a $ sign is treated as a constant named b, which has not been defined. In PHP 8 and later this throws a fatal error (Undefined constant "b"); in PHP 7 it gives a warning and prints the string b. To print the letter, the code must be written echo "b";.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • 2083 Baishakh · 5 marks

Write a JavaScript program that accepts three numbers as input and finds the smallest among them.

Answer

JavaScript program to find the smallest of three numbers

<html>
<head>
    <title>Smallest of Three Numbers</title>
    <script>
        function findSmallest() {
            var a = parseFloat(document.getElementById("num1").value);
            var b = parseFloat(document.getElementById("num2").value);
            var c = parseFloat(document.getElementById("num3").value);

            if (a <= b && a <= c) {
                document.getElementById("result").innerHTML = "The smallest number is " + a;
            } else if (b <= a && b <= c) {
                document.getElementById("result").innerHTML = "The smallest number is " + b;
            } else {
                document.getElementById("result").innerHTML = "The smallest number is " + c;
            }
        }
    </script>
</head>
<body>
    <h3>Find the Smallest of Three Numbers</h3>

    Enter first number : <input type="text" id="num1"><br><br>
    Enter second number: <input type="text" id="num2"><br><br>
    Enter third number : <input type="text" id="num3"><br><br>

    <input type="button" value="Find Smallest" onclick="findSmallest()">

    <p id="result"></p>
</body>
</html>

Working of the program

  1. Three text boxes (num1, num2, num3) accept the three numbers from the user.
  2. When the button is clicked, the function findSmallest() runs.
  3. parseFloat() converts the string values of the text boxes into numbers.
  4. The if…else if…else ladder compares the numbers:
    • If a is less than or equal to both b and c, then a is the smallest.
    • Otherwise, if b is less than or equal to both a and c, then b is the smallest.
    • Otherwise, c is the smallest.
  5. The result is displayed in the paragraph with id="result" using innerHTML.

Sample input and output

First numberSecond numberThird numberOutput
12527The smallest number is 5
883The smallest number is 3
-4-9-2The smallest number is -9

Alternative (shorter) version

The same result can be obtained using the built-in Math.min() method:

var a = parseFloat(prompt("Enter first number"));
var b = parseFloat(prompt("Enter second number"));
var c = parseFloat(prompt("Enter third number"));

var smallest = Math.min(a, b, c);
document.write("The smallest number is " + smallest);

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2083 Baishakh · 5 marks

Write a PHP script that connects to a MySQL database named school, retrieves all records from the student table, and displays them in an HTML table.

Answer

PHP script to connect to MySQL, retrieve all records from the student table, and display them in an HTML table

<?php
// 1. Database connection details
$host     = "localhost";   // MySQL server (usually localhost)
$username = "root";        // MySQL username
$password = "";            // MySQL password
$database = "school";      // Database name

// 2. Connect to the MySQL server
$conn = mysqli_connect($host, $username, $password, $database);

// 3. Check whether the connection succeeded
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// 3. Write the SQL query to retrieve all records
$sql = "SELECT * FROM student";

// 4. Execute the query
$result = mysqli_query($conn, $sql);

// 5. Check whether any records were returned
if (mysqli_num_rows($result) > 0) {

    // 6. Start the HTML table with a header row
    echo "<table border='1' cellpadding='8' cellspacing='0'>";
    echo "<tr>
            <th>ID</th>
            <th>Name</th>
            <th>Address</th>
            <th>Marks</th>
          </tr>";

    // 7. Fetch each row as an associative array and print it
    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['marks']   . "</td>";
        echo "</tr>";
    }

    echo "</table>";

} else {
    echo "No records found in the student table.";
}

// 8. Close the connection
mysqli_close($conn);
?>

Explanation of the steps

  1. Connection details — The server name, MySQL username, password, and database name are stored in variables so they are easy to change.
  2. mysqli_connect() — Opens a connection to the MySQL server and selects the school database. It returns a connection object, or false on failure.
  3. Error check — mysqli_connect_error() displays the reason if the connection fails, and die() stops the script.
  4. SQL query — SELECT * FROM student fetches every column of every row in the student table.
  5. mysqli_query() — Sends the query to the database and returns a result set.
  6. mysqli_num_rows() — Counts the returned rows so the script knows whether to build the table or show a "no records" message.
  7. HTML table — <table>, <tr>, <th>, and <td> tags build the table. The header row uses <th> for column titles.
  8. mysqli_fetch_assoc() — Fetches one row at a time as an associative array (column name as key). The while loop repeats until all rows are printed.
  9. mysqli_close() — Frees the result and closes the connection to release server resources.

Note: The column names (id, name, address, marks) must match the actual columns of the student table. For a real application, mysqli_prepare() with bound parameters should be used instead of direct query strings to prevent SQL injection.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 Supplementary · 5 marks

Write a program in JavaScript to input Age of a person and display whether the person is eligible for voting or not. (If Age is greater than or equal to 18 years, eligible for voting otherwise not eligible)

Answer

Program to check voting eligibility

<html>
<head>
    <title>Voting Eligibility</title>
</head>
<body>
    <script>
        // Input age from the user
        var age = parseInt(prompt("Enter the age of the person:"));

        // Check the eligibility condition
        if (age >= 18) {
            document.write("The person is eligible for voting.");
        } else {
            document.write("The person is not eligible for voting.");
        }
    </script>
</body>
</html>

Explanation

  1. prompt() takes the age as input from the user. Since input from prompt() is a string, parseInt() converts it into an integer so that it can be compared numerically.
  2. The if statement tests the condition age >= 18.
  3. If the condition is true, the message "The person is eligible for voting." is displayed using document.write().
  4. If the condition is false, the else part runs and "The person is not eligible for voting." is displayed.

Sample run

Age enteredOutput
20The person is eligible for voting.
15The person is not eligible for voting.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 Supplementary · 5 marks

Write a PHP function which is commonly used to establish a connection to a MySQL database with an example.

Answer

PHP Function to Connect to a MySQL Database

The commonly used function to establish a connection to a MySQL database in PHP is mysqli_connect() (the MySQL Improved extension). It opens a connection to a MySQL server and returns a connection object (or false on failure).

Syntax

mysqli_connect(host, username, password, database_name);
ParameterDescription
hostMySQL server name (e.g. localhost)
usernameMySQL user name (e.g. root)
passwordMySQL password for that user
database_nameName of the database to select

Example

<?php
// Database connection parameters
$host = "localhost";
$user = "root";
$pass = "";
$db   = "school";

// Establish connection
$conn = mysqli_connect($host, $user, $pass, $db);

// Check whether the connection succeeded
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully to the database.";

// Close the connection when done
mysqli_close($conn);
?>

Explanation

  1. mysqli_connect() attempts to connect to the MySQL server running on localhost using the given username and password, and selects the database school.
  2. If the connection fails, it returns false; the die() statement with mysqli_connect_error() stops the script and displays the error message.
  3. If successful, a connection object $conn is returned, which can be used to run SQL queries using functions like mysqli_query().
  4. mysqli_close() closes the connection and frees server resources.

Note: The older mysql_connect() function is deprecated. mysqli_connect() or PDO should be used for secure and modern database connectivity.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 Baishakh · 1 mark

Which control structure in JS (JavaScript) is used to execute a block of code repeatedly based on a given condition? (a) For Loop (b) if-else (c) switch-case (d) function

Answer

(a) For Loop

A for loop is a looping (iteration) control structure — it executes a block of code repeatedly as long as the given condition remains true. The other options are selection or modular constructs: if-else and switch-case choose between alternatives, and a function merely groups statements for reuse.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • 2082 Baishakh · 1 mark

Select the invalid variable name in PHP. (a) name(b)name (b) _name (c) 1name(d)1name (d) name123

Answer

(c) $1name

In PHP, a variable name must begin with a letter or an underscore after the $ sign; it cannot begin with a digit.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • 2082 Baishakh · 5 marks

Write JavaScript code to input any three numbers and find the smallest number among them.

Answer

JavaScript program to find the smallest of three numbers

<html>
<head>
  <title>Smallest of Three Numbers</title>

  <script>
    function findSmallest() {
      // input three numbers from the text boxes
      var a = parseFloat(document.getElementById("num1").value);
      var b = parseFloat(document.getElementById("num2").value);
      var c = parseFloat(document.getElementById("num3").value);
      var small;

      // compare and find the smallest
      if (a <= b && a <= c) {
        small = a;
      } else if (b <= a && b <= c) {
        small = b;
      } else {
        small = c;
      }

      // display the result
      document.getElementById("result").innerHTML =
        "The smallest number is " + small;
    }
  </script>
</head>

<body>
  <h3>Find the smallest of three numbers</h3>

  Enter first number : <input type="text" id="num1"><br><br>
  Enter second number: <input type="text" id="num2"><br><br>
  Enter third number : <input type="text" id="num3"><br><br>

  <input type="button" value="Find Smallest" onclick="findSmallest()">

  <p id="result"></p>
</body>
</html>

Working / logic

  1. Three text boxes (num1, num2, num3) take the input, and the button calls the function findSmallest().
  2. parseFloat() converts the string values from the text boxes into numbers, so that comparison is done numerically and not as text.
  3. The if…else if…else ladder checks the conditions:
    • if a is less than or equal to both b and c, then a is the smallest;
    • otherwise, if b is less than or equal to both a and c, then b is the smallest;
    • otherwise c must be the smallest.
  4. The smallest value is written into the paragraph with id="result" using innerHTML.

Alternative (shorter) method

JavaScript provides a built-in method Math.min() that returns the smallest of the given numbers:

var small = Math.min(a, b, c);
document.getElementById("result").innerHTML = "The smallest number is " + small;

Sample run: If the three inputs are 25, 9 and 14, the output is:

The smallest number is 9

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 Baishakh · 5 marks

Write a PHP script to connect to a MySQL database.

Answer

PHP Script to Connect to a MySQL Database

To connect a PHP script to a MySQL database, PHP provides the mysqli (MySQL Improved) extension. The connection is established using the mysqli_connect() function, which takes the server name, username, password, and database name as arguments. If the connection fails, the script should stop and display an error message using die().

Syntax

mysqli_connect(servername, username, password, databasename);

PHP Script

<?php
// Database connection parameters
$servername = "localhost";   // server name (host)
$username   = "root";        // MySQL username
$password   = "";            // MySQL password
$dbname     = "school";      // database name

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

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully to the database.";
?>

Explanation

StepDescription
1The server name, username, password, and database name are stored in variables.
2mysqli_connect() opens a connection to the MySQL server and selects the database.
3The if (!$conn) condition checks whether the connection failed.
4mysqli_connect_error() returns the reason for the failure, and die() stops the script.
5If successful, a confirmation message is displayed.

Note: The connection should be closed after use with mysqli_close($conn); to free server resources.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 Baishakh · 1 mark

What is the correct syntax for a 'for-loop' in JavaScript? (a) for (var i = 0; i < 5; i++) {} (b) for (i = 0; i < 5; i++) {} (c) for (var i = 0; i < 5) {} (d) for (var i < 5; i++) {}

Answer

(a) for (var i = 0; i < 5; i++) {}

A JavaScript for loop needs three parts inside the parentheses — initialisation, condition and update — each separated by a semicolon. Option (a) has all three in the correct order, while the others either drop the initialisation keyword, omit the update expression, or place the condition in the initialisation position.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • 2081 Baishakh · 1 mark

Which PHP function is commonly used to execute SQL queries on a database connection established using mysqli extension? (a) mysqli_query() (b) pdo_query() (c) mysql_query() (d) pgsql_query()

Answer

(a) mysqli_query()

It is the mysqli extension's function that sends an SQL statement to the connected MySQL server and returns a result set or true/false — e.g. mysqli_query($conn, "SELECT * FROM student"). The other options are not mysqli functions: pdo_query() does not exist (PDO uses PDO::query()), mysql_query() belongs to the removed old mysql extension, and pgsql_query() is for PostgreSQL.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • 2081 Baishakh · 5 marks

Write a JavaScript function that checks if a number is even or odd and print the result.

Answer

JavaScript function to check even or odd

function checkEvenOdd(num) {
    if (num % 2 === 0) {
        return "The number " + num + " is Even.";
    } else {
        return "The number " + num + " is Odd.";
    }
}

// Calling the function and printing the result
console.log(checkEvenOdd(7));
console.log(checkEvenOdd(12));

Explanation

  1. The function checkEvenOdd(num) takes one parameter num, the number to be tested.
  2. The modulus operator % gives the remainder after division. A number is even when num % 2 leaves remainder 0, and odd when the remainder is 1.
  3. The strict equality operator === compares the remainder with 0 and returns true or false.
  4. If the condition is true, the function returns a message saying the number is Even; otherwise it returns a message saying the number is Odd.
  5. console.log() calls the function with sample values and prints the returned result on the console.

Output

The number 7 is Odd.
The number 12 is Even.

The same logic can also be written in a shorter form using the conditional (ternary) operator:

function checkEvenOdd(num) {
    return num % 2 === 0 ? "Even" : "Odd";
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 Baishakh · 5 marks

What is purpose of the mysqli_connect() function in PHP? Describe its usage and parameters.

Answer

Purpose of mysqli_connect()

The mysqli_connect() function is used to open a connection between a PHP script and a MySQL database server. Without this connection, PHP cannot send queries to or retrieve data from the database. It is the first step in any database-driven PHP application. The "i" in mysqli stands for improved, and it supports both the procedural style (where mysqli_connect() is used) and the object-oriented style.

Syntax

mysqli_connect(host, username, password, database, port);

Parameters

ParameterDescription
hostThe hostname or IP address of the MySQL server (e.g. localhost or 127.0.0.1). Optional; defaults to php.ini setting.
usernameThe MySQL user account name used to log in. Optional; defaults to the server's default user.
passwordThe password for that MySQL user. Optional; defaults to an empty string.
databaseThe name of the database to select by default. Optional.
portThe port number of the MySQL server. Optional; defaults to 3306.

Return value: It returns a mysqli connection object on success, or false on failure.

Usage example

<?php
$host = "localhost";
$user = "root";
$pass = "";
$db   = "school";

// Open the connection
$conn = mysqli_connect($host, $user, $pass, $db);

// Check whether the connection succeeded
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

// ... run queries using $conn ...

// Close the connection when done
mysqli_close($conn);
?>

Explanation of usage

  1. The four arguments (host, username, password, database) are passed to mysqli_connect() to establish the link.
  2. The returned connection object $conn is stored in a variable and reused for all subsequent operations such as mysqli_query(), mysqli_fetch_assoc(), etc.
  3. If the connection fails, mysqli_connect_error() returns the error message, which helps in debugging.
  4. Finally, mysqli_close() closes the connection to free server resources.

Thus, mysqli_connect() serves as the bridge between PHP and MySQL, and its parameters allow the programmer to specify exactly which server, user, and database to connect to.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 Supplementary · 1 mark

What function do you need to call to ask the user of the program to enter text in JavaScript? (a) readline (b) readln (c) text (d) println

Answer

(None of the above) — In browser JavaScript, the function to ask the user to enter text is prompt(), e.g. let name = prompt("Enter your name:");. The readline module is specific to Node.js and is used via readline.createInterface() and rl.question(), not as a general JavaScript input function. The other options are also not correct.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • 2080 Supplementary · 1 mark

Which function is used to connect to MySql database? (a) mysqli_connect() (b) mysqli_open() (c) mysqli_query() (d) $mysqli_con()

Answer

(a) mysqli_connect()

It opens a connection to a MySQL server and returns a connection object, e.g. mysqli_connect("localhost", "root", "", "school"). mysqli_query() is also a PHP function, but it only runs a query on an already-open connection; mysqli_open() and $mysqli_con() are not valid PHP MySQL connection functions.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • 2080 Supplementary · 5 marks

Write a program to find the largest number among three numbers in JavaScript.

Answer

Program to find the largest among three numbers in JavaScript

The program takes three numbers, compares them using if…else if…else, and displays the largest one. It is written inside an HTML page so that the result can be shown in the browser.

<!DOCTYPE html>
<html>
<head>
    <title>Largest of Three Numbers</title>
</head>
<body>
    <h2>Largest among three numbers</h2>

    <script>
        // Step 1: declare three variables and assign values
        var a = 25;
        var b = 47;
        var c = 19;

        // Step 2: compare the numbers
        if (a >= b && a >= c) {
            document.write("The largest number is " + a);
        }
        else if (b >= a && b >= c) {
            document.write("The largest number is " + b);
        }
        else {
            document.write("The largest number is " + c);
        }
    </script>
</body>
</html>

Output

The largest number is 47

Working

  1. Three variables a, b and c are declared and given the values 25, 47 and 19.
  2. The first condition a >= b && a >= c checks whether a is greater than or equal to both the other numbers. If true, a is the largest.
  3. If the first condition is false, the second condition b >= a && b >= c is tested. If true, b is the largest.
  4. If both conditions fail, then c must be the largest, so the else block runs.
  5. The result is printed on the web page using the document.write() method.

Alternative (shorter) method

JavaScript provides a built-in Math.max() function that returns the largest of the given values:

var a = 25, b = 47, c = 19;
var largest = Math.max(a, b, c);
document.write("The largest number is " + largest);

Both programs give the same output, but the if…else version is preferred in the exam because it shows the logic of comparison clearly.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 Supplementary · 5 marks
  • NEB Class 12 Computer Science · 5 marks

How do you connect MySQL database with PHP? Explain with an example.

Answer

Connecting MySQL Database with PHP

PHP provides built-in support for connecting to a MySQL database. The connection is made in the following steps:

Step 1: Create the database and table (in MySQL)

CREATE DATABASE schooldb;
USE schooldb;
CREATE TABLE student (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    marks INT
);

Step 2: Connect PHP to MySQL using mysqli_connect()

The function mysqli_connect(host, username, password, database) establishes the connection. It returns a connection object on success or false on failure.

<?php
$host = "localhost";
$user = "root";
$pass = "";
$db   = "schooldb";

// Establish connection
$conn = mysqli_connect($host, $user, $pass, $db);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Step 3: Execute SQL queries

Once connected, queries are run using mysqli_query().

<?php
// Insert a record
$sql = "INSERT INTO student (id, name, marks) VALUES (1, 'Ram', 450)";
if (mysqli_query($conn, $sql)) {
    echo "Record inserted";
} else {
    echo "Error: " . mysqli_error($conn);
}

// Fetch records
$result = mysqli_query($conn, "SELECT * FROM student");
while ($row = mysqli_fetch_assoc($result)) {
    echo $row['id'] . " " . $row['name'] . " " . $row['marks'] . "<br>";
}
?>

Step 4: Close the connection

mysqli_close($conn);

Explanation of the functions used:

FunctionPurpose
mysqli_connect()Opens a connection to the MySQL server
mysqli_connect_error()Returns the error message if connection fails
mysqli_query()Sends an SQL query to the database
mysqli_fetch_assoc()Fetches a result row as an associative array
mysqli_error()Returns the last error description
mysqli_close()Closes the open connection

Note: PHP also supports the object-oriented style (new mysqli(...)) and PDO. The procedural mysqli style shown above is the simplest and most commonly used for board-level examples. Always close the connection after use to free server resources.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 Baishakh · 1 mark

Which of the given sign is used as a shortcut for JQuery? (a) the % sign (b) the & sign (c) the S sign (d) the @sign

Answer

(c) the $ sign

The dollar sign $ is the shortcut (alias) for the jQuery function, so $(selector) means the same as jQuery(selector).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • 2080 Baishakh · 1 mark

Which jQuery method is used to hide selected elements? (a) hide() (b) hide (on) (c) invisible() (d) display (none)

Answer

(a) hide()

The jQuery hide() method hides the selected elements by setting their CSS display to none. For example, $("p").hide(); hides all paragraph elements on the page.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • 2080 Baishakh · 1+4 marks

Define a syntax for database connectivity. Write a server side scripting code to insert data into the table student having fields (first name, last name, mark and email:) Assume that server name="localhost", username="root", password="" database name="student DB".

Answer

Syntax for database connectivity (PHP–MySQLi procedural style):

$conn = mysqli_connect("servername", "username", "password", "dbname");

This opens a connection to the MySQL server and selects the database. It returns a connection object on success, or false on failure. The connection is then used by queries such as mysqli_query($conn, $sql), and closed with mysqli_close($conn).


Server-side scripting code to insert data into the table student:

<?php
// 1. Connect to the database
$conn = mysqli_connect("localhost", "root", "", "student DB");

// 2. Check the connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// 3. Values to be inserted
$first_name = "Ram";
$last_name  = "Sharma";
$mark       = 85;
$email      = "ram@gmail.com";

// 4. SQL INSERT statement
$sql = "INSERT INTO student (first_name, last_name, mark, email)
        VALUES ('$first_name', '$last_name', $mark, '$email')";

// 5. Execute the query
if (mysqli_query($conn, $sql)) {
    echo "Record inserted successfully.";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

// 6. Close the connection
mysqli_close($conn);
?>

Explanation of the steps:

  1. mysqli_connect() establishes the connection using the given server name, username, password and database name.
  2. The connection is verified; if it fails, the script stops with an error message.
  3. The data to be inserted is stored in variables.
  4. The INSERT INTO statement lists the columns and their values in matching order. String values are enclosed in single quotes; the numeric mark is written without quotes.
  5. mysqli_query() sends the statement to the server; a success or failure message is displayed.
  6. mysqli_close() releases the connection.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 Baishakh · 5 marks

Write a JavaScript code to calculate the factorial of a given number.

Answer

JavaScript program to calculate the factorial of a given number

The factorial of a number nn is the product of all integers from 1 to nn:

n!=1×2×3×⋯×n,0!=1n! = 1 \times 2 \times 3 \times \dots \times n, \qquad 0! = 1

Method 1: Using a for loop

<html>
<head>
    <title>Factorial of a Number</title>
</head>
<body>
<script>
    var n = parseInt(prompt("Enter a number:"));
    var fact = 1;

    for (var i = 1; i <= n; i++) {
        fact = fact * i;
    }

    document.write("Factorial of " + n + " is " + fact);
</script>
</body>
</html>

Working: The variable fact is initialised to 1. The loop runs from i = 1 up to i = n, and in every repetition fact is multiplied by i. When the loop ends, fact holds n!n!, which is printed on the page. For n = 0 the loop body never executes, so the answer is correctly 1.

Method 2: Using a recursive function

<script>
    function factorial(n) {
        if (n == 0 || n == 1)
            return 1;
        else
            return n * factorial(n - 1);
    }

    var n = parseInt(prompt("Enter a number:"));
    document.write("Factorial of " + n + " is " + factorial(n));
</script>

Here the function calls itself with n - 1 until the base case n = 0 or n = 1 is reached, and the results are multiplied back.

Sample output

Enter a number: 5
Factorial of 5 is 120

Since 5!=1×2×3×4×5=1205! = 1 \times 2 \times 3 \times 4 \times 5 = 120.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 Jestha · 1 mark

Correct syntax for referring to an external JavaScript: (a) <script src="myscript.js"></script> (b) <script href="myscript.js"></script> (c) <js href="myscript.js"></js> (d) <js src="myscript.js"></js>

Answer

(a) <script src="myscript.js"></script>

The <script> tag uses the src attribute to point to an external JavaScript file; href belongs to <a> and <link>, and <js> is not a valid HTML tag.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • 2079 Jestha · 1 mark

Correct way of defining a variable in PHP: (a) $variable name = value; (b) $variable_name = value; (c) $variable_name = value (d) $variable name as value;

Answer

(b) $variable_name = value;

In PHP a variable name must start with the $ sign, followed by a letter or underscore (no spaces allowed), and the statement must end with a semicolon. So $variable_name = value; is the correct form, while options (a) and (d) contain a space in the name and option (c) is missing the semicolon.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • 2079 Jestha · 5 marks

Write a program to find the factorial of any given number using JavaScript.

Answer

Factorial of a Number using JavaScript

Logic: The factorial of a number nn (written n!n!) is the product of all integers from 1 to nn, i.e. n!=1×2×3×⋯×nn! = 1 \times 2 \times 3 \times \dots \times n. A loop is used to multiply the numbers one by one, starting with the result set to 1. Factorial of 0 is 1.

Complete HTML + JavaScript Program

<!DOCTYPE html>
<html>
<head>
    <title>Factorial of a Number</title>
</head>
<body>
    <h2>Factorial of a Number</h2>

    <script>
        // Input the number
        var n = parseInt(prompt("Enter any number:"));

        var fact = 1;      // result variable

        // Loop from 1 to n and multiply
        for (var i = 1; i <= n; i++) {
            fact = fact * i;
        }

        document.write("The factorial of " + n + " is " + fact);
    </script>
</body>
</html>

Sample Output

Enter any number: 5
The factorial of 5 is 120

Working

Stepifact = fact × i
Start–1
111 × 1 = 1
221 × 2 = 2
332 × 3 = 6
446 × 4 = 24
5524 × 5 = 120

Alternative: Using a User-Defined Function (Recursion)

<script>
    function factorial(n) {
        if (n == 0 || n == 1)
            return 1;
        else
            return n * factorial(n - 1);
    }

    var num = parseInt(prompt("Enter any number:"));
    document.write("The factorial of " + num + " is " + factorial(num));
</script>

Note: The loop method is preferred for large numbers because recursion uses more memory. Factorial is not defined for negative numbers, so the input should be a non-negative integer.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 Jestha · 5 marks

How do you fetch data from database in PHP and display it in form? Describe.

Answer

Fetching data from a database in PHP and displaying it in a form

PHP connects to a database (usually MySQL/MariaDB) through MySQLi or PDO, runs an SQL SELECT query, and then places the returned values into HTML form fields using the value attribute. The steps are:

Step 1 — Connect to the database Use mysqli_connect() (or a PDO object) with the server name, username, password and database name. Check for a connection error.

$conn = mysqli_connect("localhost", "root", "", "school");
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

Step 2 — Write the SELECT query Select the row(s) you need. For a single record to edit, filter by a unique key such as id.

$id = $_GET['id'];                 // id passed from the previous page
$sql = "SELECT * FROM students WHERE id = $id";

Step 3 — Execute the query Pass the connection and the SQL string to mysqli_query(). It returns a result set on success or false on failure.

$result = mysqli_query($conn, $sql);

Step 4 — Fetch the record Use mysqli_fetch_assoc() to bring the row into an associative array whose keys are the column names. For many rows, call it inside a while loop.

$row = mysqli_fetch_assoc($result);   // single row

Step 5 — Display the data inside the form Echo each array element into the value attribute of the matching input, so the form opens pre-filled with the stored data. For a <select> or radio buttons, compare each option with the stored value and mark it selected/checked.

<form method="post" action="update.php">
  <input type="hidden" name="id" value="<?php echo $row['id']; ?>">

  Name:  <input type="text" name="name"
                value="<?php echo $row['name']; ?>"><br>

  Email: <input type="text" name="email"
                value="<?php echo $row['email']; ?>"><br>

  Gender:
  <input type="radio" name="gender" value="Male"
     <?php if ($row['gender']=="Male") echo "checked"; ?>> Male
  <input type="radio" name="gender" value="Female"
     <?php if ($row['gender']=="Female") echo "checked"; ?>> Female<br>

  <input type="submit" value="Update">
</form>

Step 6 — Close the connection After the data has been used, free the result and close the connection.

mysqli_free_result($result);
mysqli_close($conn);

Key points

  • The value attribute of an input is what makes the form show existing data; without it the field stays empty.
  • Always escape output with htmlspecialchars() to prevent XSS, and use prepared statements (mysqli_prepare() with ? placeholders) when the value comes from user input, to prevent SQL injection.
  • The same technique is used to build an edit/update form: fetch the record, display it in the form, let the user change it, then run an UPDATE query on submit.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • NEB Class 12 Computer Science · 1 mark

Which of the following is a server-side scripting language? (a) JavaScript (b) MySQL (c) PHP (d) jQuery

Answer

(c) PHP

PHP code runs on the web server and sends only the generated HTML to the browser. JavaScript and jQuery mainly run in the browser, and MySQL is a database system, not a scripting language.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 1 MCQ

Loading…

  • NEB Class 12 Computer Science · 5 marks

Write a JavaScript program to swap the values of two variables.

Answer

The values are swapped using a third temporary variable.

<!DOCTYPE html>
<html>
<body>
<script>
var a = 10;
var b = 20;
document.write("Before swapping: a = " + a + ", b = " + b + "<br>");

var temp = a;   // store a in temp
a = b;          // put b into a
b = temp;       // put old a into b

document.write("After swapping: a = " + a + ", b = " + b);
</script>
</body>
</html>

Output

Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10

Here temp keeps the original value of a so that it is not lost when a is overwritten with b.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

Questions from NEB Class 12 2083 Computer Science (Board exam, Baishakh 2083; typed transcription), NEB Class 12 2082 Supplementary Computer Science (Supplementary exam 2082; set B; scanned images), NEB Class 12 2082 Computer Science (Board exam, Baishakh 2082; set D; typed transcription), NEB Class 12 2081 Computer Science (Board exam, Baishakh 2081; typed transcription), NEB Class 12 2080 Supplementary Computer Science (Supplementary/grade-increment exam 2080; set B; typed transcription), NEB Class 12 2080 Computer Science (Board exam, Baishakh 2080; typed text (solved)), NEB Class 12 2079 Computer Science (Board exam, Jestha 2079; set A; typed transcription) and NEB Class 12 Computer Science (4281) Model Question (NEB model question set, 50 marks, 2 hours; questions only (answers not taken). Wording of some questions reconstructed from a page summary, so check against the paper.). Answers are written for this site; check them against your class notes.

Chapter titles and hours from the official syllabus ↗