Sikshya Plus Get appGet the app free
Class 12 · Computer Science

Web technology ll – Class 12 Computer Science Notes and Solutions

Complete solutions and answers for “Web technology ll”, a chapter in Class 12 Computer Science (NEB exam preparation). This page covers Table of Contents, Section A — Multiple Choice Questions, Section B — Short Answer Questions and Section C — Long Answer Questions.

  • Free, no login needed
  • 40 min read
  • Updated 1 July 2026

Chapter at a glance

This chapter provides a comprehensive overview of Web Technology, covering both client-side and server-side scripting. It delves into JavaScript, jQuery, PHP, and MySQL, offering detailed explanations and practical examples for Class 12 Computer Science students.

  • Web Technology
  • Client-Side Scripting
  • Server-Side Scripting
  • JavaScript
  • jQuery
  • PHP
  • MySQL
  • SQL

Exam focus: Students should focus on understanding the differences between client-side and server-side scripting, the core concepts of JavaScript (data types, functions, events), and the basics of PHP for web development and database interaction with MySQL.

Key formulas and definitions

  • Client-Side Scripting: Executed in user's browser, code visible, e.g., JavaScript.
  • Server-Side Scripting: Executed on web server, code invisible, e.g., PHP, Python.
  • JavaScript <script> tag: Used to embed JavaScript in HTML.
  • PHP script delimiters: <?php ... ?>
  • mysqli_connect(): Function to establish a MySQL database connection.
On this page (4 sections)
  1. Table of Contents
  2. Section A — Multiple Choice Questions
  3. Section B — Short Answer Questions
  4. Section C — Long Answer Questions

Solutions and answers

Client-Side & Server-Side Scripting, JavaScript, jQuery, PHP & MySQL — fully solved exercises for Class 12 Computer Science.

Table of Contents

Section A — Multiple Choice Questions Section B — Short Answer Questions (1–21) Section C — Long Answer Questions (1–7)
📝

Section A — Multiple Choice Questions

16 objective-type questions with detailed explanations

Q1. Which is not the client-side scripting?
  • i. CSS
  • ii. PHP
  • iii. Python
  • iv. Perl
✅ Answer: ii. PHP
Explanation: PHP (Hypertext Preprocessor) is a server-side scripting language. It is executed on the web server before the result is sent to the client's browser. CSS is used for styling on the client side. Although Python and Perl are primarily server-side languages, in this context PHP is the most well-known server-side option among the choices.
Q2. __________ is a server-side scripting language.
  • i. PHP
  • ii. Python
  • iii. Ruby
  • iv. All of the above
✅ Answer: iv. All of the above
Explanation: PHP, Python, Ruby, and Perl can all be used as server-side scripting languages. They are executed on the server to generate dynamic web content, process form data, interact with databases, etc.
Q3. Server-side script is __________.
  • i. visible to users
  • ii. dependent on browser
  • iii. invisible to user
  • iv. executed on client's browser
✅ Answer: iii. invisible to user
Explanation: Server-side scripts are processed on the web server. Only the output (usually HTML) is sent to the browser. The original source code is never visible to the end user, providing security for proprietary logic.
Q4. A JavaScript code is added in <body> section of HTML by using __________.
  • i. <A> tag
  • ii. <insert> tag
  • iii. <script> tag
  • iv. <javascript> tag
✅ Answer: iii. <script> tag
Explanation: The <script> tag is the standard HTML element used to embed or reference JavaScript code. It can be placed inside the <head> or <body> section of an HTML document.
Q5. A valid JavaScript identifier is __________.
  • i. 1st_name
  • ii. $$address
  • iii. new
  • iv. $price
✅ Answer: iv. $price
Explanation:
  • 1st_name — Invalid: an identifier cannot start with a digit.
  • $$address — Valid syntax but unusual; $price is the cleaner standard answer.
  • new — Invalid: new is a reserved keyword in JavaScript.
  • $price — Valid: JavaScript allows identifiers to begin with $ or _.
Q6. An object in JavaScript is __________.
  • i. table
  • ii. button
  • iii. image
  • iv. All of the above
✅ Answer: iv. All of the above
Explanation: In JavaScript (via the DOM), table, button, and image are all represented as objects. The Document Object Model treats every HTML element as an object that can be accessed and manipulated through JavaScript.
Q7. A variable in JavaScript that has not been assigned a value has __________.
  • i. symbol data type
  • ii. null data type
  • iii. undefined data type
  • iv. None of the above
✅ Answer: iii. undefined data type
Explanation: When a variable is declared but not assigned a value, JavaScript automatically assigns it the value undefined. This is different from null, which must be explicitly assigned.
Q8. A variable in JavaScript can be declared by __________ keyword.
  • i. const
  • ii. var
  • iii. varchar
  • iv. var_def
✅ Answer: ii. var
Explanation: The var keyword is the traditional way to declare variables in JavaScript. Modern JavaScript also provides let and const. varchar is a SQL data type, and var_def does not exist.
Q9. Which is not true for a variable in JavaScript?
  • i. A variable is case sensitive.
  • ii. A variable name can begin with number.
  • iii. A variable can be declared anywhere in a program when it is needed.
  • iv. A variable can store any type of data.
✅ Answer: ii. A variable name can begin with number.
Explanation: This statement is false. JavaScript identifiers (including variable names) cannot begin with a digit. They must start with a letter, underscore (_), or dollar sign ($).
Q10. Which is not the event handler?
  • i. onmouseup
  • ii. onmousedown
  • iii. onmousemove
  • iv. onmouseround
✅ Answer: iv. onmouseround
Explanation: onmouseup, onmousedown, and onmousemove are all valid JavaScript event handlers. onmouseround is not a valid event handler in JavaScript.
Q11. jQuery is __________.
  • i. client side scripting language
  • ii. server side scripting language
  • iii. JavaScript library file
  • iv. None of the above
✅ Answer: iii. JavaScript library file
Explanation: jQuery is a fast, lightweight JavaScript library (not a separate language). It simplifies tasks like DOM manipulation, event handling, animation, and AJAX calls with a concise, cross-browser-compatible API.
Q12. __________ is needed in a computer to run PHP.
  • i. Web server
  • ii. PHP interpreter
  • iii. SQL database server
  • iv. All of the above
✅ Answer: iv. All of the above
Explanation: To fully run PHP-based web applications you need a web server (e.g., Apache), a PHP interpreter to execute the scripts, and typically an SQL database server (e.g., MySQL) for data storage. Software bundles like XAMPP/WAMP package all three together.
Q13. Each PHP script starts with __________ and ends with ?>.
  • i. <?php and ends with ?>
  • ii. <phpp and ends with ?>
  • iii. <?php and ends with <phpp>
  • iv. None of the above
✅ Answer: i. <?php and ends with ?>
Explanation: The standard PHP opening tag is <?php and the closing tag is ?>. All PHP code must be enclosed within these delimiters.
Q14. __________ statement in PHP displays output.
  • i. console
  • ii. write
  • iii. display
  • iv. print
✅ Answer: iv. print
Explanation: In PHP, print (and echo) are the built-in language constructs used to output data. console and write are JavaScript concepts; display is not a PHP keyword.
Q15. To establish the database connection with MySQL server, __________ function is used.
  • i. mysquli_connect()
  • ii. mysqli_connection()
  • iii. mysqli_connect()
  • iv. None of the above
✅ Answer: iii. mysqli_connect()
Explanation: The correct function is mysqli_connect() (MySQL Improved extension). It takes parameters for server hostname, username, password, and database name to establish a connection to MySQL.
Q16. Which one of the following statements is used to create a table in PHP?
  • i. CREATE TABLE table_Name(ColumnName, ColumnType)
  • ii. CREATE TABLE table_Name(ColumnType, ColumnName)
  • iii. CREATE table_Name (ColumnName, ColumnType)
  • iv. CREATE table_Name (ColumnType, ColumnName)
✅ Answer: i. CREATE TABLE table_Name(ColumnName, ColumnType)
Explanation: The correct SQL syntax requires the TABLE keyword after CREATE, and columns are defined with ColumnName first, followed by the ColumnType (e.g., CREATE TABLE students(name VARCHAR(50), age INT)).
📖

Section B — Short Answer Questions

Questions 1–21 with comprehensive, exam-ready solutions

Web Q1. What is web technology? Write the differences between client-side scripting and server-side scripting.

What is Web Technology?

Web Technology refers to the collection of tools, languages, protocols, and software frameworks used to create, deliver, and manage web-based applications and services over the internet or an intranet.

Web technology encompasses:

  • Front-end (Client-Side): HTML, CSS, JavaScript — runs in the user's browser.
  • Back-end (Server-Side): PHP, Python, Node.js, Java — runs on the web server.
  • Protocols: HTTP, HTTPS, FTP, TCP/IP for data transmission.
  • Databases: MySQL, PostgreSQL, MongoDB for data storage and retrieval.
  • Markup & Styling: HTML5, CSS3 for structuring and presenting content.

Differences Between Client-Side and Server-Side Scripting

Client-Side Scripting

  • Executed in the user's web browser.
  • Source code is visible to users (can view via "View Source").
  • Languages: JavaScript, VBScript.
  • Used for form validation, UI interactions, animations.
  • Reduces server load — work happens on the client machine.
  • Cannot directly access or manipulate server-side databases.
  • Runs after the web page has loaded in the browser.
  • Files typically have .html, .js extensions.

Server-Side Scripting

  • Executed on the web server.
  • Source code is invisible to users — only the output is sent.
  • Languages: PHP, Python, Ruby, ASP.NET, JSP.
  • Used for database operations, authentication, dynamic content.
  • Processes requests and generates HTML to send to the client.
  • Can directly interact with databases (MySQL, PostgreSQL, etc.).
  • Runs before the page is sent to the browser.
  • Files typically have .php, .py, .asp, .jsp extensions.
CriteriaClient-SideServer-Side
Execution LocationWeb BrowserWeb Server
Code VisibilityVisible to userHidden from user
Processing SpeedFaster (no server round-trip)Depends on server & network
SecurityLess secure (code exposed)More secure (code hidden)
Database AccessNo direct accessFull database access
ExamplesJavaScript, CSSPHP, Python, Ruby
JS Q2. What is client-side scripting? Write its features.

Client-side scripting is a technique in web development where scripts (programs) are executed in the user's web browser rather than on the web server. The script code is downloaded along with the HTML page and runs locally on the client machine after the page loads.

Client-side scripts are embedded within HTML using tags like <script> and are typically written in JavaScript.

Features of Client-Side Scripting

  • Browser Execution: The script runs entirely in the user's browser, eliminating the need for a server round-trip for each interaction.
  • Instant Feedback: Provides immediate responses to user actions such as button clicks, form input, and mouse movements without page reload.
  • Form Validation: Can validate user input (e.g., email format, password strength) on the client side before sending data to the server, reducing unnecessary network traffic.
  • Dynamic UI Manipulation: Can dynamically change HTML content, CSS styles, and create animations using the Document Object Model (DOM).
  • Reduced Server Load: Since processing happens on the client, fewer requests are sent to the server, improving scalability.
  • Source Code Visibility: The script source code is visible to any user who views the page source, which limits security-sensitive operations.
  • Cross-Browser Compatibility: Must be tested across different browsers, as behavior may vary slightly between Chrome, Firefox, Safari, Edge, etc.
  • No Database Access: Client-side scripts cannot directly connect to or query server-side databases; they rely on AJAX or fetch APIs to request data from the server.
  • Rich User Experience: Enables interactive features like sliders, modals, carousels, drag-and-drop, and real-time content updates.
JS Q3. What is JavaScript? Mention its uses and advantages.

JavaScript is a lightweight, interpreted, high-level programming language primarily used to create interactive and dynamic content on websites. It was created by Brendan Eich at Netscape in 1995 and has become one of the three core technologies of the World Wide Web alongside HTML and CSS.

JavaScript is an event-driven, functional, and object-oriented language that runs in the browser (client-side) as well as on the server (via Node.js).

Uses of JavaScript

  • Form Validation: Validates user input (e.g., checking empty fields, email format, password strength) before submitting to the server.
  • Dynamic Content: Modifies HTML content and CSS styles on the fly without reloading the page (DOM manipulation).
  • Event Handling: Responds to user interactions like clicks, key presses, mouse movements, and scroll events.
  • Animations & Effects: Creates smooth animations, transitions, sliders, carousels, and visual effects.
  • AJAX Communication: Sends and receives data from the server asynchronously, enabling seamless page updates.
  • Cookies & Storage: Manages browser cookies, localStorage, and sessionStorage for persisting user data.
  • Web Applications: Powers complex single-page applications (SPAs) using frameworks like React, Angular, and Vue.js.
  • Server-Side Development: With Node.js, JavaScript can build back-end APIs, microservices, and real-time applications.
  • Game Development: Browser-based games can be built using JavaScript with HTML5 Canvas and WebGL.

Advantages of JavaScript

  • Easy to Learn: Has a relatively simple syntax compared to many programming languages.
  • Immediate Execution: Runs directly in the browser without any compilation step.
  • Rich Interfaces: Enables creation of highly interactive and visually appealing user interfaces.
  • Reduced Server Load: Client-side processing reduces the number of server requests.
  • Platform Independent: Runs on any platform with a web browser — Windows, macOS, Linux, mobile devices.
  • Vast Ecosystem: Supported by thousands of libraries (jQuery, Lodash) and frameworks (React, Angular, Vue, Express).
  • Asynchronous Processing: Supports asynchronous operations using callbacks, promises, and async/await.
  • Extended Functionality: Can be extended to large-scale applications through various add-on technologies.
JS Q4. Write the ways to add JavaScript in HTML. Explain them briefly with examples.

There are three main ways to add JavaScript code to an HTML document:

1. Internal JavaScript (Inline in <script>tag)

JavaScript code is written directly inside <script> tags within the HTML file, usually within the <head> or <body> section.

<!DOCTYPE html>
<html>
<head>
    <title>Internal JS Example</title>
    <script>
        function greet() {
            alert("Hello, Welcome to Sikshya Plus!");
        }
    </script>
</head>
<body>
    <button onclick="greet()">Click Me</button>
</body>
</html>

2. External JavaScript (Separate .jsfile)

JavaScript code is written in a separate file with a .js extension and linked to HTML using the src attribute of the <script> tag. This is the recommended best practice for maintainability.

<!-- In the HTML file (myPage.html) -->
<head>
    <script src="myScript.js"></script>
</head>

/* In the external file (myScript.js) */
function greet() {
    alert("Hello from external JS file!");
}

3. Inline JavaScript (Inside HTML attributes)

JavaScript code is written directly inside an HTML event-handler attribute such as onclick, onmouseover, onchange, etc.

<button onclick="alert('Hello from inline JS!')">
    Click Me
</button>
💡 Best Practice
External JavaScript is preferred for larger projects because it promotes code reusability, separation of concerns, caching by browsers, and easier maintenance.
JS Q5. What is a JavaScript identifier? Write the rules of naming identifiers.

A JavaScript identifier is the name given to variables, functions, objects, classes, loops, and other programming elements. Identifiers are used to identify and reference these elements throughout the program.

var studentName = "Ram";     studentName is an identifier
function calculateTotal() { }  calculateTotal is an identifier
const MAX_SIZE = 100;          MAX_SIZE is an identifier

Rules for Naming Identifiers

  • An identifier must begin with a letter (a-z, A-Z), an underscore (_), or a dollar sign ($). It cannot start with a digit.
  • Subsequent characters can be letters, digits, underscores, or dollar signs.
  • Identifiers are case-sensitive. For example, myVar, MyVar, and MYVAR are three different identifiers.
  • Reserved keywords (such as var, let, const, function, return, if, else, new, this, etc.) cannot be used as identifiers.
  • Identifiers should not contain spaces or special characters (like @, #, %, !).
  • Identifiers should be meaningful and descriptive to improve code readability (e.g., totalMarks instead of tm).
  • JavaScript supports Unicode characters in identifiers, but it is standard practice to use only ASCII letters.
⚠️ Common Mistakes
1stName ✗ (starts with digit)  |  my-var ✗ (contains hyphen)  |  new ✗ (reserved keyword)  |  $price ✓  |  _count ✓
JS Q6. Describe JavaScript data types with examples.

JavaScript supports two broad categories of data types: Primitive (value) types and Non-primitive (reference) types.

Primitive Data Types

  • Number — Represents both integer and floating-point numbers.
    var age = 25;
    var price = 99.99;
    var negative = -10;
    console.log(typeof age); "number"
  • String — Represents textual data enclosed in single quotes, double quotes, or backticks.
    var name = "Sikshya Plus";
    var greeting = 'Hello';
    var template = `Welcome ${name}`;
    console.log(typeof name); "string"
  • Boolean — Represents logical values: true or false.
    var isActive = true;
    var isLoggedIn = false;
    console.log(typeof isActive); "boolean"
  • Undefined — A variable that has been declared but not assigned a value has the value undefined.
    var x;
    console.log(x);          undefined
    console.log(typeof x); "undefined"
  • Null — Represents the intentional absence of any object value. Must be explicitly assigned.
    var data = null;
    console.log(data);          null
    console.log(typeof data); "object" (known JS quirk)
  • BigInt — Represents integers of arbitrary precision (larger than Number.MAX_SAFE_INTEGER).
    var big = 9007199254740991n;
    console.log(typeof big); "bigint"
  • Symbol — Represents a unique and immutable identifier, often used as object property keys.
    var sym = Symbol("id");
    console.log(typeof sym); "symbol"

Non-Primitive (Reference) Data Types

  • Object — A collection of key-value pairs.
    var student = {
        name: "Aarav",
        age: 18,
        grade: "XII"
    };
    console.log(student.name); "Aarav"
  • Array — An ordered list of values (technically a type of object).
    var colors = ["red", "green", "blue"];
    console.log(colors[0]); "red"
  • Function — A reusable block of code (also a type of object in JavaScript).
    var add = function(a, b) {
        return a + b;
    };
    console.log(add(5, 3)); 8
JS Q7. Write a way to create a user-defined function in JavaScript with examples.

A user-defined function in JavaScript is a reusable block of code designed to perform a specific task. Functions help in organizing code, avoiding repetition, and improving readability.

Ways to Create User-Defined Functions

1. Function Declaration (Named Function)

function greet(name) {
    return "Hello, " + name + "! Welcome to Sikshya Plus.";
}

console.log(greet("Aarav"));
Output: Hello, Aarav! Welcome to Sikshya Plus.

2. Function Expression

var add = function(a, b) {
    return a + b;
};

console.log(add(10, 20)); Output: 30

3. Arrow Function (ES6)

const multiply = (x, y) => x * y;

console.log(multiply(4, 5)); Output: 20

Complete Example — Function with Multiple Parameters

Function to calculate the area of a rectangle
function calculateArea(length, breadth) {
    var area = length * breadth;
    return area;
}

var result = calculateArea(10, 5);
console.log("Area = " + result);
Output: Area = 50
💡 Key Points
  • Functions can accept parameters (inputs) and return values.
  • Functions are invoked (called) using parentheses: functionName().
  • A function without a return statement returns undefined by default.
JS Q8. What is a logical operator in JavaScript? Explain with an example.

Logical operators in JavaScript are used to combine or invert boolean expressions. They are primarily used in conditional statements and loops to make decisions based on multiple conditions.

OperatorNameDescriptionExampleResult
&&Logical ANDReturns true if both operands are truetrue && falsefalse
||Logical ORReturns true if at least one operand is truetrue || falsetrue
!Logical NOTInverts the boolean value of the operand!truefalse

Example — Logical Operators in Action

var age = 20;
var hasID = true;

Logical AND — Both conditions must be true
if (age >= 18 && hasID === true) {
    console.log("Access granted.");
} else {
    console.log("Access denied.");
}
Output: Access granted.

Logical OR — At least one condition must be true
var isStudent = true;
var isTeacher = false;

if (isStudent || isTeacher) {
    console.log("Welcome to Sikshya Plus!");
}
Output: Welcome to Sikshya Plus!

Logical NOT — Inverts the boolean value
var isLoggedIn = false;

if (!isLoggedIn) {
    console.log("Please log in first.");
}
Output: Please log in first.
✅ Truth Table Summary
AND: T && T = T, T && F = F, F && T = F, F && F = F
OR: T || T = T, T || F = T, F || T = T, F || F = F
NOT: !T = F, !F = T
JS Q9. What is a conditional structure? List the different conditional structures used in JavaScript with their syntaxes.

A conditional structure (also called a selection or decision structure) allows a program to execute different blocks of code based on whether a specified condition evaluates to true or false. It enables programs to make decisions dynamically.

1. if Statement

Executes a block of code only if the condition is true.

if (condition) {
    code to execute if condition is true
}

Example:
var marks = 85;
if (marks >= 40) {
    console.log("You passed!");
}

2. if...else Statement

Provides an alternative block when the condition is false.

if (condition) {
    code if true
} else {
    code if false
}

Example:
var marks = 30;
if (marks >= 40) {
    console.log("Passed");
} else {
    console.log("Failed");
}
Output: Failed

3. if...else if...else (Ladder)

Tests multiple conditions in sequence.

if (condition1) {
    code if condition1 is true
} else if (condition2) {
    code if condition2 is true
} else if (condition3) {
    code if condition3 is true
} else {
    code if none of the above are true
}

Example — Grade calculation:
var score = 75;
if (score >= 90) {
    console.log("Grade A");
} else if (score >= 80) {
    console.log("Grade B");
} else if (score >= 70) {
    console.log("Grade C");
} else {
    console.log("Grade F");
}
Output: Grade C

4. switch Statement

Selects one of many code blocks to execute based on the value of an expression.

switch (expression) {
    case value1:
        code
        break;
    case value2:
        code
        break;
    default:
        code if no case matches
}

Example:
var day = "Monday";
switch (day) {
    case "Monday":
        console.log("Start of work week");
        break;
    case "Friday":
        console.log("Almost weekend!");
        break;
    default:
        console.log("Regular day");
}
Output: Start of work week

5. Ternary Operator (Conditional Expression)

A shorthand for if...else in a single line.

var age = 20;
var status = (age >= 18) ? "Adult" : "Minor";
console.log(status); Output: Adult
JS Q10. What is an event handler in JavaScript? Explain the way to use onclick event handler with an example.

An event handler (also called an event listener) in JavaScript is a function that is executed in response to a specific event occurring on an HTML element. Events include user actions like clicking a button, moving the mouse, pressing a key, submitting a form, or loading a page.

Event handlers allow developers to create interactive and responsive web pages by defining what should happen when users interact with page elements.

The onclickEvent Handler

The onclick event handler triggers a function when the user clicks on an HTML element (such as a button, image, link, or div).

Example — Using onclick

<!DOCTYPE html>
<html>
<head>
    <title>onclick Example</title>
    <script>
        function showMessage() {
            alert("Button was clicked! Welcome to Sikshya Plus!");
        }
    </script>
</head>
<body>
    <h2>Event Handler Demo</h2>
    <button onclick="showMessage()">Click Me</button>
</body>
</html>

Other Common Event Handlers

Event HandlerTriggered When
onclickElement is clicked
ondblclickElement is double-clicked
onmouseoverMouse pointer enters the element
onmouseoutMouse pointer leaves the element
onkeydownA keyboard key is pressed down
onkeyupA keyboard key is released
onchangeElement value changes (input, select)
onloadPage or image finishes loading
onsubmitForm is submitted
onfocusElement receives focus
onblurElement loses focus
jQuery Q11. What is jQuery? Why is jQuery used in web development?

jQuery is a fast, small, feature-rich, and cross-platform JavaScript library created by John Resig in 2006. Its motto is "Write less, do more." jQuery simplifies many tasks that are verbose or complex in plain JavaScript.

It is included in a web page via a <script> tag, either from a local file or a CDN (Content Delivery Network):

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Why jQuery is Used in Web Development

  • DOM Manipulation: Easily select, traverse, and modify HTML elements using CSS-style selectors.
    $("#myDiv").css("color", "blue");
    $(".highlight").hide();
  • Event Handling: Simplifies attaching event listeners to elements.
    $("#btn").click(function() {
        alert("Clicked!");
    });
  • AJAX Support: Makes asynchronous server requests simple for loading data without page reload.
    $.get("data.php", function(response) {
        $("#result").html(response);
    });
  • Animations & Effects: Built-in methods like fadeIn(), fadeOut(), slideUp(), animate().
  • Cross-Browser Compatibility: jQuery handles browser inconsistencies internally so code works uniformly across all major browsers.
  • Plugin Ecosystem: Thousands of community-built plugins extend jQuery's functionality (datepickers, sliders, charts).
  • Chaining: Multiple methods can be chained together for concise code.
    $("#box").css("background", "red").fadeIn().slideUp();
JS Q12. What is form validation? Write the codes to verify the password in a form.

Form validation is the process of checking whether the data entered by a user in an HTML form meets certain criteria or rules before it is submitted to the server. This can be done on the client side (using JavaScript) and/or the server side (using PHP).

Client-side validation provides instant feedback, improves user experience, and reduces unnecessary server requests.

Code — Password Verification Form

<!DOCTYPE html>
<html>
<head>
    <title>Password Validation</title>
    <script>
        function validatePassword() {
            var password = document.getElementById("pwd").value;
            var confirmPwd = document.getElementById("confirmPwd").value;

            Check minimum length
            if (password.length < 6) {
                alert("Password must be at least 6 characters long.");
                return false;
            }

            Check if passwords match
            if (password !== confirmPwd) {
                alert("Passwords do not match!");
                return false;
            }

            alert("Password validated successfully!");
            return true;
        }
    </script>
</head>
<body>
    <h2>Registration Form</h2>
    <form onsubmit="return validatePassword()">
        <label>Password:</label><br>
        <input type="password" id="pwd"><br><br>

        <label>Confirm Password:</label><br>
        <input type="password" id="confirmPwd"><br><br>

        <input type="submit" value="Register">
    </form>
</body>
</html>
PHP Q13. What is PHP? What are the requirements of PHP?

PHP stands for "PHP: Hypertext Preprocessor" (a recursive acronym). It is a widely-used, open-source, server-side scripting language designed specifically for web development. PHP code is executed on the server, and the result (usually HTML) is sent to the client's browser.

PHP was created by Rasmus Lerdorf in 1994 and is now maintained by The PHP Group. It can be embedded directly within HTML code.

Key Characteristics of PHP

  • PHP scripts are enclosed within <?php ... ?> tags.
  • PHP is platform-independent — runs on Windows, Linux, macOS.
  • PHP supports a wide range of databases (MySQL, PostgreSQL, Oracle, SQLite).
  • PHP files have the extension .php.

Requirements to Run PHP

  • Web Server: A web server such as Apache, Nginx, or IIS is required to process PHP requests and serve web pages. The web server receives the client's request, passes the PHP code to the interpreter, and sends the output back to the browser.
  • PHP Interpreter: The PHP parser/interpreter is the engine that reads and executes PHP code. It converts PHP scripts into HTML output that the web server can deliver to the browser.
  • Database Server (Optional but commonly needed): For dynamic web applications, a database server like MySQL, MariaDB, or PostgreSQL is needed to store and retrieve data.
  • Web Browser: A standard web browser (Chrome, Firefox, Edge, Safari) to view the output.
  • Development Environment: Software packages like XAMPP, WAMP, LAMP, or MAMP bundle the web server, PHP interpreter, and MySQL together for easy local development.
PHP Q14. Write the uses of echo and print statements of PHP. Write code to show their use.

echo and print are both language constructs (not functions) in PHP used to output data to the browser. They are the primary ways to display text, variables, and HTML content.

Uses of echo

  • Can output one or more strings separated by commas.
  • Does not return a value (slightly faster).
  • Can be used with or without parentheses.
  • Supports multiple parameters: echo "Hello", " ", "World";

Uses of print

  • Can output only one string at a time.
  • Returns the value 1, so it can be used in expressions.
  • Can be used with or without parentheses.
  • Slightly slower than echo because it returns a value.

Code Example

<?php
    Using echo
    echo "Hello, Welcome to Sikshya Plus!<br>";
    echo "Learning PHP is fun!<br>";

    echo with multiple parameters
    echo "Subject: ", "Computer Science", "<br>";

    Using print
    print "This is printed using print statement.<br>";

    print returns 1 — can be used in expressions
    echo print("Return value demo");  Outputs: Return value demo1

    Variables with echo and print
    $name = "Aarav";
    $grade = "XII";
    echo "Student: $name, Grade: $grade<br>";
    print "Student: $name, Grade: $grade<br>";
?>

Output

Hello, Welcome to Sikshya Plus!
Learning PHP is fun!
Subject: Computer Science
This is printed using print statement.
Return value demo1
Student: Aarav, Grade: XII
Student: Aarav, Grade: XII
PHP Q15. Write the difference between PHP GET and PHP POST methods.

GET and POST are the two most common HTTP request methods used in HTML forms to send data from the client to the server.

CriteriaGET MethodPOST Method
Data VisibilityData is appended to the URL as query string (visible in address bar)Data is sent in the HTTP request body (not visible in URL)
Data SizeLimited to about 2048 characters (URL length limit)No size limitation (can send large amounts of data)
SecurityLess secure — data is exposed in the URL and browser historyMore secure — data is hidden in the request body
BookmarkingCan be bookmarked (data is in URL)Cannot be bookmarked with data
CachingCan be cached by the browserNot cached by default
Data TypeOnly ASCII characters allowedNo restriction — supports binary data, file uploads
Use CaseRetrieving data (search queries, page navigation)Submitting sensitive data (login forms, registration, file uploads)
PHP Access$_GET['key']$_POST['key']
IdempotentYes — multiple identical requests produce the same resultNot idempotent — may produce different results each time
PHP Q16. How to use PHP GET and POST methods in a page? Explain with examples.

Using the GET Method

Data sent via GET is appended to the URL and accessed in PHP using the $_GET superglobal array.

HTML Form (form_get.html):

<form action="process_get.php" method="GET">
    <label>Name:</label>
    <input type="text" name="username"><br><br>

    <label>City:</label>
    <input type="text" name="city"><br><br>

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

PHP Processing (process_get.php):

<?php
    $name = $_GET['username'];
    $city = $_GET['city'];

    echo "Name: $name <br>";
    echo "City: $city <br>";
?>

Resulting URL: process_get.php?username=Aarav&city=Kathmandu

Using the POST Method

Data sent via POST is included in the HTTP request body and accessed using the $_POST superglobal array.

HTML Form (form_post.html):

<form action="process_post.php" method="POST">
    <label>Username:</label>
    <input type="text" name="username"><br><br>

    <label>Password:</label>
    <input type="password" name="password"><br><br>

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

PHP Processing (process_post.php):

<?php
    $username = $_POST['username'];
    $password = $_POST['password'];

    echo "Welcome, $username!<br>";
    echo "Your password has been received securely.";
?>
PHP Q17. What is the purpose of the mysqli_connect() function? Describe its usage and parameters.

The mysqli_connect() function is used to open a new connection to a MySQL database server. It is part of the MySQL Improved (mysqli) extension in PHP, which provides a more secure and feature-rich interface compared to the older mysql_* functions.

Syntax

mysqli_connect($server, $username, $password, $database);

Parameters

  • $server (string): The hostname or IP address of the MySQL server. Typically "localhost" when the database is on the same machine.
  • $username (string): The MySQL username for authentication. Default in XAMPP/WAMP is usually "root".
  • $password (string): The password for the MySQL user. Often an empty string "" in local development.
  • $database (string, optional): The name of the database to connect to. If omitted, you can select it later with mysqli_select_db().

Return Value

  • Returns a connection object (procedural) or mysqli object (OOP) on success.
  • Returns FALSE on failure.

Example

<?php
    $server   = "localhost";
    $username = "root";
    $password = "";
    $database = "studentDB";

    Establish connection
    $conn = mysqli_connect($server, $username, $password, $database);

    Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    } else {
        echo "Connected successfully to MySQL!";
    }
?>
PHP Q18. Write the PHP code for connecting server-side script to MySQL database through the procedural mysqli extension.

PHP Code — MySQL Database Connection (Procedural Style)

<?php
    Database configuration
    $server   = "localhost";
    $username = "root";
    $password = "";
    $database = "studentDB";

    Create connection using mysqli_connect()
    $conn = mysqli_connect($server, $username, $password, $database);

    Verify connection
    if ($conn === false) {
        die("ERROR: Could not connect. "
            . mysqli_connect_error());
    }

    echo "Connected successfully to the database server!<br>";
    echo "Server Info: " . mysqli_get_server_info($conn);

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

Step-by-Step Explanation

  • Define credentials: Store the server hostname, username, password, and database name in variables.
  • Call mysqli_connect(): This function attempts to establish a connection to the MySQL server using the provided credentials.
  • Check the result: If the connection fails, die() terminates the script and displays the error message from mysqli_connect_error().
  • Use the connection: If successful, you can run queries using mysqli_query().
  • Close the connection: Always close the connection with mysqli_close() when finished to free resources.
SQL Q19. What is SQL? Write the SQL commands to create a database, table, and add data.

SQL (Structured Query Language) is a standard programming language used to manage, manipulate, and query relational databases. It allows users to create, read, update, and delete (CRUD) data stored in database tables.

SQL Commands

1. Create a Database

CREATE DATABASE studentDB;

2. Select/Use the Database

USE studentDB;

3. Create a Table

CREATE TABLE students (
    id         INT PRIMARY KEY AUTO_INCREMENT,
    firstname  VARCHAR(50) NOT NULL,
    lastname   VARCHAR(50) NOT NULL,
    mark       INT,
    email      VARCHAR(100)
);

4. Insert Data into the Table

INSERT INTO students (firstname, lastname, mark, email)
VALUES ('Aarav', 'Sharma', 85, 'aarav@example.com');

INSERT INTO students (firstname, lastname, mark, email)
VALUES ('Sita', 'Thapa', 92, 'sita@example.com');

5. Retrieve Data

SELECT * FROM students;
SELECT firstname, mark FROM students WHERE mark > 80;

Types of SQL Commands

CategoryCommandsPurpose
DDLCREATE, ALTER, DROPDefine/modify database structure
DMLINSERT, UPDATE, DELETEManipulate data in tables
DQLSELECTRetrieve/query data
DCLGRANT, REVOKEControl access permissions
TCLCOMMIT, ROLLBACKManage transactions
PHP Q20. Define syntax for database connectivity. Write a server-side code to insert data into the student table.

Database Connectivity Syntax

mysqli_connect(server, username, password, database)

Where:

  • server: Hostname (e.g., "localhost")
  • username: MySQL username (e.g., "root")
  • password: MySQL password (e.g., "")
  • database: Database name (e.g., "studentDB")

Complete PHP Code — Insert Data into Student Table

<?php
    Step 1: Database connection parameters
    $server   = "localhost";
    $username = "root";
    $password = "";
    $database = "studentDB";

    Step 2: Establish connection
    $conn = mysqli_connect($server, $username,
                            $password, $database);

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

    Step 4: Define the INSERT query
    $sql = "INSERT INTO student
             (firstname, lastname, mark, email)
           VALUES
             ('Aarav', 'Sharma', 85, 'aarav@mail.com')";

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

    Step 6: Close the connection
    mysqli_close($conn);
?>

Insert Data from a Form (Dynamic)

<?php
    $conn = mysqli_connect("localhost", "root",
                            "", "studentDB");

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

    Capture form data
    $fname  = $_POST['firstname'];
    $lname  = $_POST['lastname'];
    $mark   = $_POST['mark'];
    $email  = $_POST['email'];

    Prepared statement (safer against SQL injection)
    $stmt = mysqli_prepare($conn,
        "INSERT INTO student
         (firstname, lastname, mark, email)
         VALUES (?, ?, ?, ?)");

    mysqli_stmt_bind_param($stmt, "ssis",
        $fname, $lname, $mark, $email);

    if (mysqli_stmt_execute($stmt)) {
        echo "Record inserted successfully!";
    } else {
        echo "Error: " . mysqli_error($conn);
    }

    mysqli_stmt_close($stmt);
    mysqli_close($conn);
?>
PHP Q21. Write the procedural style of fetching data using mysqli_fetch_row().

The mysqli_fetch_row() function fetches one row of data from the result set as a numerically indexed array. Each call returns the next row, or NULL when there are no more rows.

Syntax

mysqli_fetch_row(result)

Complete Example — Fetch and Display Data

<?php
    Step 1: Connect to database
    $conn = mysqli_connect("localhost", "root",
                            "", "studentDB");

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

    Step 2: Write the SELECT query
    $sql = "SELECT id, firstname, lastname, mark, email
            FROM student";

    Step 3: Execute the query
    $result = mysqli_query($conn, $sql);

    Step 4: Check if result has rows
    if (mysqli_num_rows($result) > 0) {
        Step 5: Display as HTML table
        echo "<table border='1' cellpadding='8'>";
        echo "<tr><th>ID</th><th>First Name</th>"
           . "<th>Last Name</th><th>Mark</th>"
           . "<th>Email</th></tr>";

        Step 6: Fetch each row
        while ($row = mysqli_fetch_row($result)) {
            echo "<tr>";
            echo "<td>" . $row[0] . "</td>";  id
            echo "<td>" . $row[1] . "</td>";  firstname
            echo "<td>" . $row[2] . "</td>";  lastname
            echo "<td>" . $row[3] . "</td>";  mark
            echo "<td>" . $row[4] . "</td>";  email
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "No records found.";
    }

    Step 7: Free result and close connection
    mysqli_free_result($result);
    mysqli_close($conn);
?>
💡 Note
mysqli_fetch_row() returns a numerically indexed array (0, 1, 2...). For associative arrays (accessed by column name), use mysqli_fetch_assoc(). For both, use mysqli_fetch_array().
📝

Section C — Long Answer Questions

7 descriptive questions with in-depth explanations and code examples

JS Q1. Describe the looping structures that can be used in JavaScript with examples.

A looping structure (also called an iteration structure) allows a block of code to be executed repeatedly as long as a specified condition remains true. Loops are essential for tasks like processing arrays, generating repetitive output, and automating repetitive operations.

JavaScript provides the following looping structures:

1. forLoop

The for loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and increment/decrement.

for (initialization; condition; update) { // code block }
Print numbers 1 to 5
for (var i = 1; i <= 5; i++) {
    console.log("Number: " + i);
}
Output: Number: 1, Number: 2, ... Number: 5

Calculate sum of first 10 natural numbers
var sum = 0;
for (var i = 1; i <= 10; i++) {
    sum += i;
}
console.log("Sum = " + sum); Sum = 55

2. whileLoop

The while loop executes a block of code as long as the condition is true. The condition is checked before each iteration. Used when the number of iterations is not known in advance.

while (condition) { // code block }
Print numbers 1 to 5
var i = 1;
while (i <= 5) {
    console.log("Count: " + i);
    i++;
}

Read input until user enters 'stop'
var input = "";
while (input !== "stop") {
    input = prompt("Enter text (type 'stop' to end):");
}

3. do...whileLoop

Similar to while, but the condition is checked after each iteration. This guarantees that the code block is executed at least once, even if the condition is initially false.

do { // code block } while (condition);
Print numbers 1 to 5
var i = 1;
do {
    console.log("Value: " + i);
    i++;
} while (i <= 5);

Executed at least once even if condition is false
var x = 10;
do {
    console.log("x = " + x);  This will run once
} while (x < 5);
Output: x = 10

4. for...inLoop

Iterates over the enumerable properties (keys) of an object. Can also iterate over array indices.

Iterate over object properties
var student = {
    name: "Aarav",
    grade: "XII",
    marks: 85
};

for (var key in student) {
    console.log(key + ": " + student[key]);
}
Output: name: Aarav, grade: XII, marks: 85

5. for...ofLoop (ES6)

Iterates over iterable objects like arrays, strings, Maps, and Sets. Returns the values directly.

Iterate over array values
var fruits = ["Apple", "Banana", "Cherry"];

for (var fruit of fruits) {
    console.log(fruit);
}
Output: Apple, Banana, Cherry
💡 Comparison Summary
  • for — Best when iteration count is known.
  • while — Best when condition depends on dynamic factors.
  • do...while — Use when code must execute at least once.
  • for...in — Use for iterating object properties/keys.
  • for...of — Use for iterating over array/string values.
JS Q2. What is event handling in JavaScript? Describe the different event handlers.

Event handling in JavaScript is the mechanism by which the program listens for and responds to events that occur on HTML elements. An event is any action that happens in the browser — such as a user clicking a button, typing in a text field, moving the mouse, loading a page, or submitting a form.

An event handler is a JavaScript function that is automatically invoked when a specific event occurs on a specific element. This enables web pages to be interactive and responsive.

How Event Handling Works

  • An HTML element is assigned an event handler (e.g., onclick, onchange).
  • The user performs an action (e.g., clicks the element).
  • The browser detects the event and calls the associated JavaScript function.
  • The function executes, producing the desired response (e.g., showing an alert, validating input, changing content).

Categories of Event Handlers

Mouse Events

Event HandlerDescription
onclickFires when the user clicks on an element
ondblclickFires on double-click
onmouseoverFires when the mouse pointer enters the element
onmouseoutFires when the mouse pointer leaves the element
onmousedownFires when a mouse button is pressed down
onmouseupFires when a mouse button is released
onmousemoveFires when the mouse pointer moves within the element

Keyboard Events

Event HandlerDescription
onkeydownFires when a key is pressed down
onkeyupFires when a key is released
onkeypressFires when a key is pressed (deprecated)

Form Events

Event HandlerDescription
onsubmitFires when a form is submitted
onresetFires when a form is reset
onchangeFires when the value of an element changes
onfocusFires when an element receives focus
onblurFires when an element loses focus
onselectFires when text is selected in an input

Window/Page Events

Event HandlerDescription
onloadFires when the page or image finishes loading
onunloadFires when the user leaves the page
onresizeFires when the browser window is resized
onscrollFires when the user scrolls the page

Example — Multiple Event Handlers

<!DOCTYPE html>
<html>
<head>
    <title>Event Handling Demo</title>
    <script>
        function handleClick() {
            document.getElementById("output").innerHTML
                = "Button was clicked!";
        }
        function handleOver() {
            document.getElementById("box").style.backgroundColor
                = "lightblue";
        }
        function handleOut() {
            document.getElementById("box").style.backgroundColor
                = "lightgray";
        }
    </script>
</head>
<body>
    <div id="box"
         style="width:200px;height:100px;background:lightgray;"
         onmouseover="handleOver()"
         onmouseout="handleOut()">
        Hover over me!
    </div>
    <br>
    <button onclick="handleClick()">Click Me</button>
    <p id="output"></p>
</body>
</html>
PHP Q3. Describe the data types used in PHP with examples.

PHP supports several built-in data types that can be broadly categorized into scalar types, compound types, and special types.

Scalar Data Types

  • String — A sequence of characters enclosed in single quotes (' ') or double quotes (" ").
    <?php
        $name = "Sikshya Plus";
        $greeting = 'Hello, World!';
        echo $name;   Output: Sikshya Plus
    ?>
  • Integer — A whole number without a decimal point (can be positive, negative, or zero).
    <?php
        $age = 20;
        $temp = -5;
        $hex = 0x1A;    hexadecimal = 26
        $oct = 073;     octal = 59
        echo gettype($age); integer
    ?>
  • Float (Double) — A number with a decimal point or in exponential form.
    <?php
        $price = 99.99;
        $pi = 3.14159;
        $scientific = 2.5e3;  2500
        echo gettype($price); double
    ?>
  • Boolean — Represents two possible states: true or false.
    <?php
        $isActive = true;
        $isDeleted = false;
    
        if ($isActive) {
            echo "Account is active.";
        }
    ?>

Compound Data Types

  • Array — Stores multiple values in a single variable. Can be indexed or associative.
    <?php
        Indexed array
        $colors = array("Red", "Green", "Blue");
        echo $colors[0]; Red
    
        Associative array
        $student = array(
            "name"  => "Aarav",
            "grade" => "XII",
            "marks" => 85
        );
        echo $student["name"]; Aarav
    ?>
  • Object — An instance of a class. Stores data and methods.
    <?php
        class Student {
            public $name;
            public $marks;
    
            function display() {
                echo "$this->name scored $this->marks";
            }
        }
    
        $s = new Student();
        $s->name = "Sita";
        $s->marks = 92;
        $s->display(); Sita scored 92
    ?>

Special Data Types

  • NULL — A variable with no value assigned. It is the only possible value of type NULL.
    <?php
        $data = null;
        echo is_null($data); 1 (true)
    ?>
  • Resource — A special variable that holds a reference to an external resource (e.g., database connection, file handle).
    <?php
        $file = fopen("data.txt", "r");
        echo gettype($file); resource
        fclose($file);
    ?>
PHP Q4. Describe the operators in PHP with examples.

Operators are symbols that perform operations on variables and values. PHP supports the following categories of operators:

1. Arithmetic Operators

OperatorNameExampleResult
+Addition10 + 515
-Subtraction10 - 55
*Multiplication10 * 550
/Division10 / 52
%Modulus10 % 31
**Exponentiation2 ** 38
<?php
    $a = 20; $b = 6;
    echo $a + $b;   26
    echo $a % $b;   2
?>

2. Assignment Operators

OperatorExampleEquivalent
=$x = 10Assigns 10 to $x
+=$x += 5$x = $x + 5
-=$x -= 3$x = $x - 3
*=$x *= 2$x = $x * 2
/=$x /= 4$x = $x / 4
.=$x .= "text"$x = $x . "text"

3. Comparison Operators

OperatorNameExampleResult
==Equal (value)5 == "5"true
===Identical (value + type)5 === "5"false
!=Not equal5 != 3true
!==Not identical5 !== "5"true
<Less than3 < 5true
>Greater than5 > 3true
<=Less than or equal5 <= 5true
>=Greater than or equal5 >= 3true

4. Logical Operators

OperatorNameExample
&&AND$a && $b — true if both are true
||OR$a || $b — true if at least one is true
!NOT!$a — inverts the boolean value
andAND (lower precedence)$a and $b
orOR (lower precedence)$a or $b
<?php
    $age = 20;
    $hasID = true;

    if ($age >= 18 && $hasID) {
        echo "Access granted";
    }
?>

5. String (Concatenation) Operator

<?php
    $first = "Hello";
    $second = "World";
    echo $first . " " . $second; Hello World
?>

6. Increment/Decrement Operators

<?php
    $x = 5;
    $x++;    $x is now 6
    $x--;    $x is now 5 again
    ++$x;    pre-increment: $x is now 6
?>

7. Ternary Operator

<?php
    $marks = 75;
    $result = ($marks >= 40) ? "Pass" : "Fail";
    echo $result; Pass
?>
JS Q5. What is form validation in JavaScript? Write code to validate name, password, and email.

Form validation is the process of verifying that user input in a form meets the required criteria before the data is submitted to the server. Client-side validation using JavaScript provides instant feedback, improves user experience, and prevents unnecessary server requests.

Types of Validation

  • Required field validation: Ensures fields are not empty.
  • Length validation: Checks minimum/maximum character count.
  • Pattern/Format validation: Ensures data matches a pattern (e.g., email format).
  • Match validation: Confirms two fields match (e.g., password confirmation).

Complete Code — Name, Password, and Email Validation

<!DOCTYPE html>
<html>
<head>
    <title>Form Validation</title>
    <style>
        body { font-family: Arial; margin: 40px; }
        .error { color: red; font-size: 13px; }
        input { padding: 8px; margin: 5px 0; width: 250px; }
    </style>
    <script>
        function validateForm() {
            Get form values
            var name = document.getElementById("name").value;
            var email = document.getElementById("email").value;
            var pwd = document.getElementById("pwd").value;
            var confirmPwd = document.getElementById("confirmPwd").value;

            Clear previous errors
            document.getElementById("nameErr").innerHTML = "";
            document.getElementById("emailErr").innerHTML = "";
            document.getElementById("pwdErr").innerHTML = "";

            var isValid = true;

            Validate Name (not empty, min 3 chars)
            if (name === "") {
                document.getElementById("nameErr").innerHTML
                    = "Name is required.";
                isValid = false;
            } else if (name.length < 3) {
                document.getElementById("nameErr").innerHTML
                    = "Name must be at least 3 characters.";
                isValid = false;
            }

            Validate Email (regex pattern)
            var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (email === "") {
                document.getElementById("emailErr").innerHTML
                    = "Email is required.";
                isValid = false;
            } else if (!emailPattern.test(email)) {
                document.getElementById("emailErr").innerHTML
                    = "Invalid email format.";
                isValid = false;
            }

            Validate Password (min 6 chars, match)
            if (pwd.length < 6) {
                document.getElementById("pwdErr").innerHTML
                    = "Password must be at least 6 characters.";
                isValid = false;
            } else if (pwd !== confirmPwd) {
                document.getElementById("pwdErr").innerHTML
                    = "Passwords do not match.";
                isValid = false;
            }

            if (isValid) {
                alert("Form submitted successfully!");
            }
            return isValid;
        }
    </script>
</head>
<body>
    <h2>Registration Form</h2>
    <form onsubmit="return validateForm()">
        <label>Full Name:</label><br>
        <input type="text" id="name">
        <span class="error" id="nameErr"></span><br><br>

        <label>Email:</label><br>
        <input type="text" id="email">
        <span class="error" id="emailErr"></span><br><br>

        <label>Password:</label><br>
        <input type="password" id="pwd"><br><br>

        <label>Confirm Password:</label><br>
        <input type="password" id="confirmPwd">
        <span class="error" id="pwdErr"></span><br><br>

        <input type="submit" value="Register">
    </form>
</body>
</html>
PHP Q6. Describe connecting server-side script to a database server with examples.

Connecting a PHP script to a MySQL database involves using the MySQLi (MySQL Improved) extension, which provides a secure and efficient interface. The process involves four key steps: connect → query → process → close.

Step 1: Establish Connection

<?php
    $server   = "localhost";
    $username = "root";
    $password = "";
    $database = "studentDB";

    $conn = mysqli_connect($server, $username,
                            $password, $database);

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

Step 2: Create Database and Table

<?php
    Create database
    $sql = "CREATE DATABASE IF NOT EXISTS studentDB";
    mysqli_query($conn, $sql);

    Select database
    mysqli_select_db($conn, "studentDB");

    Create table
    $sql = "CREATE TABLE IF NOT EXISTS students (
        id INT AUTO_INCREMENT PRIMARY KEY,
        firstname VARCHAR(50) NOT NULL,
        lastname VARCHAR(50) NOT NULL,
        marks INT,
        email VARCHAR(100)
    )";

    if (mysqli_query($conn, $sql)) {
        echo "Table created successfully!<br>";
    } else {
        echo "Error creating table: "
            . mysqli_error($conn);
    }
?>

Step 3: Insert Data

<?php
    $sql = "INSERT INTO students
            (firstname, lastname, marks, email)
           VALUES
            ('Sita', 'Thapa', 92, 'sita@mail.com')";

    if (mysqli_query($conn, $sql)) {
        echo "Record inserted! ID: "
            . mysqli_insert_id($conn);
    } else {
        echo "Error: " . mysqli_error($conn);
    }
?>

Step 4: Retrieve/Display Data

<?php
    $result = mysqli_query($conn,
        "SELECT * FROM students");

    if (mysqli_num_rows($result) > 0) {
        echo "<table border='1' cellpadding='8'>";
        echo "<tr><th>ID</th><th>Name</th>"
           . "<th>Marks</th><th>Email</th></tr>";

        while ($row = mysqli_fetch_assoc($result)) {
            echo "<tr>";
            echo "<td>" . $row["id"] . "</td>";
            echo "<td>" . $row["firstname"]
               . " " . $row["lastname"] . "</td>";
            echo "<td>" . $row["marks"] . "</td>";
            echo "<td>" . $row["email"] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "No records found.";
    }
?>

Step 5: Close Connection

<?php
    mysqli_close($conn);
?>
⚠️ Security Note
Always use prepared statements (mysqli_prepare()) when accepting user input to prevent SQL injection attacks. Never directly embed user input into SQL queries.
SQL Q7. Describe SQL queries used in PHP.

SQL (Structured Query Language) queries are used within PHP scripts to interact with MySQL databases. PHP uses the mysqli_query() function to execute SQL statements. Below are the most commonly used SQL operations in PHP.

1. CREATE — Creating Database and Table

<?php
    Create database
    mysqli_query($conn,
        "CREATE DATABASE IF NOT EXISTS schoolDB");

    Create table
    $sql = "CREATE TABLE IF NOT EXISTS students (
        id INT AUTO_INCREMENT PRIMARY KEY,
        firstname VARCHAR(50) NOT NULL,
        lastname VARCHAR(50),
        marks INT DEFAULT 0,
        email VARCHAR(100) UNIQUE
    )";

    if (mysqli_query($conn, $sql)) {
        echo "Table created successfully.";
    }
?>

2. INSERT — Adding Data

<?php
    $sql = "INSERT INTO students
            (firstname, lastname, marks, email)
           VALUES
            ('Aarav', 'Sharma', 85, 'aarav@mail.com')";

    if (mysqli_query($conn, $sql)) {
        echo "New record inserted. ID: "
            . mysqli_insert_id($conn);
    } else {
        echo "Error: " . mysqli_error($conn);
    }
?>

3. SELECT — Retrieving Data

<?php
    Fetch all records
    $result = mysqli_query($conn,
        "SELECT * FROM students");

    while ($row = mysqli_fetch_assoc($result)) {
        echo $row["firstname"] . " - "
            . $row["marks"] . "<br>";
    }

    Fetch with WHERE condition
    $result = mysqli_query($conn,
        "SELECT * FROM students WHERE marks >= 80");

    Fetch specific columns
    $result = mysqli_query($conn,
        "SELECT firstname, marks FROM students
         ORDER BY marks DESC");
?>

4. UPDATE — Modifying Data

<?php
    $sql = "UPDATE students
            SET marks = 95
            WHERE firstname = 'Aarav'";

    if (mysqli_query($conn, $sql)) {
        echo mysqli_affected_rows($conn)
            . " record(s) updated.";
    }
?>

5. DELETE — Removing Data

<?php
    $sql = "DELETE FROM students
            WHERE marks < 40";

    if (mysqli_query($conn, $sql)) {
        echo mysqli_affected_rows($conn)
            . " record(s) deleted.";
    }
?>

6. ALTER — Modifying Table Structure

<?php
    Add a new column
    mysqli_query($conn,
        "ALTER TABLE students
         ADD COLUMN phone VARCHAR(15)");

    Modify column type
    mysqli_query($conn,
        "ALTER TABLE students
         MODIFY COLUMN marks DECIMAL(5,2)");
?>

7. DROP — Deleting Database or Table

<?php
    Drop table
    mysqli_query($conn,
        "DROP TABLE IF EXISTS students");

    Drop database
    mysqli_query($conn,
        "DROP DATABASE IF EXISTS schoolDB");
?>

8. Using Prepared Statements (Recommended for Security)

<?php
    Prepared statement with parameters
    $stmt = mysqli_prepare($conn,
        "INSERT INTO students
         (firstname, lastname, marks, email)
         VALUES (?, ?, ?, ?)");

    Bind parameters (s=string, i=integer)
    mysqli_stmt_bind_param($stmt, "ssis",
        $fname, $lname, $marks, $email);

    Set values and execute
    $fname = "Ram";
    $lname = "Bahadur";
    $marks = 88;
    $email = "ram@mail.com";

    mysqli_stmt_execute($stmt);
    echo "Record inserted with prepared statement!";

    mysqli_stmt_close($stmt);
?>
✅ Best Practices
  • Always use prepared statements when handling user input to prevent SQL injection.
  • Check the return value of mysqli_query() for error handling.
  • Use mysqli_real_escape_string() as a fallback for sanitizing input.
  • Always close the database connection after operations with mysqli_close().
  • Use mysqli_affected_rows() to confirm UPDATE/DELETE operations.
↑

Frequently asked questions

What is Web technology ll about?

This chapter provides a comprehensive overview of Web Technology, covering both client-side and server-side scripting. It delves into JavaScript, jQuery, PHP, and MySQL, offering detailed explanations and practical examples for Class 12 Computer Science students.

Which topics are covered in Web technology ll?

Class 12 Computer Science “Web technology ll” covers: Web Technology; Client-Side Scripting; Server-Side Scripting; JavaScript; jQuery; PHP; MySQL; SQL.

What should I focus on in Web technology ll for the exam?

Students should focus on understanding the differences between client-side and server-side scripting, the core concepts of JavaScript (data types, functions, events), and the basics of PHP for web development and database interaction with MySQL.

What are the key formulas or definitions in Web technology ll?

Client-Side Scripting: Executed in user's browser, code visible, e.g., JavaScript.; Server-Side Scripting: Executed on web server, code invisible, e.g., PHP, Python.; JavaScript <script> tag: Used to embed JavaScript in HTML.; PHP script delimiters: <?php ... ?>; mysqli_connect(): Function to establish a MySQL database connection..

Where can I read the Class 12 Computer Science “Web technology ll” solutions?

Right on this page. They are free and you do not need to sign up. For chapter quizzes and the AI tutor, install the Sikshya Plus app.

Study tips

Free for Class 9 to 12

Do not just read it. Practice it.

You have read the solutions for Web technology ll. Now test yourself, ask the AI tutor and keep your streak going.

Sikshya Plus chapter quiz screen with class, subject and difficulty options
Sikshya AI personal tutor chat inside the app
Sikshya Plus AI tools screen: question assistant, summarizer, translator, grammar checker
Chapter list with Past Q, materials, posts and books tabs
  • AI quizzes for this chapterTest yourself with instant feedback and explanations after every answer.
  • AI tutor, free, 24/7Stuck on a question? Ask in your own words and get a step-by-step explanation.
  • 14 AI tools in one appSummarizer, grammar checker, flashcards, essay help, math solver and more.
  • Past questions and notesPast papers and your own notes organized chapter by chapter.
Download free on Google Play Scan with your phone to install