0% found this document useful (0 votes)
21 views32 pages

Answer of Web

The document outlines the development of a webpage for a news organization and a student enrollment application using HTML, CSS, and PHP. It includes specifications for layout, styling, and functionality, such as displaying news sections and fetching student data from a MySQL database. Additionally, it describes the implementation of a user registration feature with client-side validation using JavaScript.

Uploaded by

Sharan Sha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views32 pages

Answer of Web

The document outlines the development of a webpage for a news organization and a student enrollment application using HTML, CSS, and PHP. It includes specifications for layout, styling, and functionality, such as displaying news sections and fetching student data from a MySQL database. Additionally, it describes the implementation of a user registration feature with client-side validation using JavaScript.

Uploaded by

Sharan Sha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Winter Semester 2024-2025 Assessment Test Lab School of Computer Science

Engineering and Information Systems

1. A) Create the HTMI structure for this webpage using basic HTML tags with float layout.
You are developing a website for a news organization. The homepage needs to divided into
different sections, such "Technology." Implement the HTML structure using the tag to
organize these conten "Breaking News," "Politics," VIT News should be center-text
background is Green, Text is bold, italic red color. Divide the sections -Bold and italic and
green color, it should be highlighted. If you click any section it goes to display descriptio
Use click event: Include Section and article in the item of Technology. Footer Display
@copy right 2024 VIT Vellore. Highlight yellow and text color

<!DOCTYPE html>

<html>

<head>

<title>News Homepage</title>

<style>

body {

font-family: Arial, sans-serif;

header {

text-align: center;

background-color: green;

font-weight: bold;

font-style: italic;

color: red;

padding: 10px;

font-size: 24px;

}
.section {

float: left;

width: 30%;

margin: 1%;

padding: 10px;

border: 1px solid #ccc;

font-weight: bold;

font-style: italic;

color: green;

background-color: #f0f0f0;

cursor: pointer;

.clear {

clear: both;

#description {

margin-top: 20px;

padding: 10px;

border: 1px solid black;

footer {

margin-top: 20px;
background-color: yellow;

color: blue;

text-align: center;

padding: 10px;

</style>

<script>

function showDescription(sectionName) {

let desc = {

"Breaking News": "Latest updates from around the world...",

"Politics": "Updates from political world...",

"Technology": "New innovations and tech updates."

};

document.getElementById("description").innerText = desc[sectionName] || "No


information available.";

</script>

</head>

<body>

<header>VIT News</header>

<div class="section" onclick="showDescription('Breaking News')">Breaking News</div>

<div class="section" onclick="showDescription('Politics')">Politics</div>

<div class="section" onclick="showDescription('Technology')">

Technology

<section>
<article>

Click to learn about the latest tech trends and updates.

</article>

</section>

</div>

<div class="clear"></div>

<div id="description"></div>

<footer>&copy; 2024 VIT Vellore</footer>

</body>

</html>

B) You've been tasked with creating a simple Student Enrolment application that fetches
student data from a Mysql table studen info and displays it to the user using PHP. The
application should allow enter a student name in an input field and display the information.
1. Display an input field and a button labeled "Get Student Info". 2. When the user enters a
Student ID in the input field and clicks the "Get Student Info" button, the application should
fetch student info from a Mysal table. 3. Display the details for the entered ID. 4. Handle
errors gracefully. If the city name is not found or there's an issue with Mysql request,
display an appropriate message to the user.

<!DOCTYPE html>

<html>

<head>

<title>Student Enrolment</title>

</head>

<body>

<h2>Student Information Lookup</h2>


<form method=”post” action=””>

<label>Enter Student ID: </label>

<input type=”text” name=”student_id” required pattern=”[0-9]{1,10}” title=”Enter a


valid numeric ID (up to 10 digits)”>

<button type=”submit” name=”get_info”>Get Student Info</button>

</form>

<?php

If (isset($_POST[‘get_info’])) {

$student_id = trim($_POST[‘student_id’]);

// Backend validation: check if input is numeric and not empty

If (empty($student_id)) {

Echo “<p style=’color:red;’>Student ID is required.</p>”;

} elseif (!ctype_digit($student_id)) {

Echo “<p style=’color:red;’>Invalid Student ID. Please enter numeric digits only.</p>”;

} else {

// Database connection

$conn = new mysqli(“localhost”, “root”, “”, “college”);

If ($conn->connect_error) {

Echo “<p style=’color:red;’>Connection failed: “ . $conn->connect_error . “</p>”;

} else {

$sql = “SELECT * FROM student_info WHERE student_id = ?”;

$stmt = $conn->prepare($sql);
If ($stmt) {

$stmt->bind_param(“s”, $student_id);

$stmt->execute();

$result = $stmt->get_result();

If ($result->num_rows > 0) {

Echo “<h3>Student Details:</h3>”;

While ($row = $result->fetch_assoc()) {

Echo “Name: “ . htmlspecialchars($row[‘name’]) . “<br>”;

Echo “Email: “ . htmlspecialchars($row[‘email’]) . “<br>”;

Echo “Department: “ . htmlspecialchars($row[‘department’]) . “<br>”;

} else {

Echo “<p style=’color:orange;’>No student found with ID: $student_id</p>”;

$stmt->close();

} else {

Echo “<p style=’color:red;’>Query preparation failed.</p>”;

$conn->close();

?>
</body>

</html>

2. A) You are tasked with deaigning the user interface for an c-commerce website. The
design team has provided specific guidelines for borders and margins to create a visually
appealing and user-friendly layout. Here are the details: 1. Product Cards: Apply a subtle 1-
pixel solid border with a light gray color (#dedede) to all product cards. Set the margin
around each product card to 15 pixels on all sides for a consistent spacing. Buttons: Give
the category buttons a 2-pixel solid border with a border-radius of 5 pixels and a color of
#3498db. 2. Category Apply a margin of 10 pixels on the top and bottom, and 15 pixels on
the left and right to ensure proper spacing 3. Checkout Form: Create a 3-pixel dashed
border with a color of #27ae60 for the entire checkout form. Set the margin to 20 pixels on
the top, 10 pixels on the right, 20 pixels on the bottom, and 10 pixels on the left. Apply a 2-
pixel solid border with a color of #39e12 to the footer. Set the margin for the footer to 30
pixels on all sides. Footer Section

<!DOCTYPE html>

<html>

<head>

<title>E-Commerce UI</title>

<style>

Body {

Font-family: Arial, sans-serif;

/* Product Cards */

.product-card {

Border: 1px solid #dedede;

Margin: 15px;

Padding: 10px;
Width: 200px;

Display: inline-block;

/* Category Buttons */

.category-button {

Border: 2px solid #3498db;

Border-radius: 5px;

Padding: 8px 12px;

Margin: 10px 15px;

Background-color: white;

Color: #3498db;

Cursor: pointer;

/* Checkout Form */

.checkout-form {

Border: 3px dashed #27ae60;

Margin: 20px 10px 20px 10px;

Padding: 15px;

/* Footer */

Footer {

Border: 2px solid #39e112;

Margin: 30px;
Padding: 10px;

Text-align: center;

/* Registration Form */

.registration-form {

Margin: 40px 15px;

Padding: 20px;

Border: 1px solid #ccc;

Width: 300px;

.registration-form input {

Width: 100%;

Margin-bottom: 10px;

Padding: 8px;

.error {

Color: red;

Font-size: 0.9em;

Margin-bottom: 10px;

.success {

Color: green;
Font-size: 1em;

</style>

</head>

<body>

<h2>Products</h2>

<div class=”product-card”>

<h4>Product 1</h4>

<p>$19.99</p>

</div>

<div class=”product-card”>

<h4>Product 2</h4>

<p>$29.99</p>

</div>

<h2>Categories</h2>

<button class=”category-button”>Electronics</button>

<button class=”category-button”>Fashion</button>

<h2>Checkout</h2>

<form class=”checkout-form”>

<label>Shipping Address</label><br>

<input type=”text” placeholder=”Enter address”><br><br>

<label>Payment Method</label><br>
<input type=”text” placeholder=”Enter payment details”>

</form>

<h2>User Registration</h2>

<form id=”registrationForm” class=”registration-form”


onsubmit=”handleSubmit(event)”>

<input type=”text” name=”username” placeholder=”Username”


oninput=”handleChange(event)”>

<div class=”error” id=”usernameError”></div>

<input type=”email” name=”email” placeholder=”Email”


oninput=”handleChange(event)”>

<div class=”error” id=”emailError”></div>

<input type=”password” name=”password” placeholder=”Password”


oninput=”handleChange(event)”>

<div class=”error” id=”passwordError”></div>

<input type=”password” name=”confirmPassword” placeholder=”Confirm Password”


oninput=”handleChange(event)”>

<div class=”error” id=”confirmPasswordError”></div>

<button type=”submit”>Register</button>

<div id=”formSuccess” class=”success”></div>

</form>

<footer>
&copy; 2024 My E-Commerce

</footer>

<script>

Let formData = {

Username: ‘’,

Email: ‘’,

Password: ‘’,

confirmPassword: ‘’

};

Function handleChange(event) {

Const { name, value } = event.target;

formData[name] = value;

Function isValidEmail(email) {

Const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

Return regex.test(email);

Function validateForm(data) {

Const errors = {};

If (!data.username.trim()) {

Errors.username = “Username is required.”;


}

If (!data.email.trim()) {

Errors.email = “Email is required.”;

} else if (!isValidEmail(data.email)) {

Errors.email = “Invalid email format.”;

If (!data.password) {

Errors.password = “Password is required.”;

} else if (data.password.length < 6) {

Errors.password = “Password must be at least 6 characters.”;

If (!data.confirmPassword) {

Errors.confirmPassword = “Please confirm your password.”;

} else if (data.password !== data.confirmPassword) {

Errors.confirmPassword = “Passwords do not match.”;

Return errors;

Function handleSubmit(event) {

Event.preventDefault();

Const errors = validateForm(formData);


// Clear previous errors

Document.querySelectorAll(“.error”).forEach(e => e.textContent = “”);

Document.getElementById(“formSuccess”).textContent = “”;

If (Object.keys(errors).length === 0) {

Document.getElementById(“formSuccess”).textContent = “Form submitted


successfully!”;

Document.getElementById(“registrationForm”).reset();

formData = { username: ‘’, email: ‘’, password: ‘’, confirmPassword: ‘’ };

} else {

For (let key in errors) {

Document.getElementById(`${key}Error`).textContent = errors[key];

</script>

</body>

</html>

: B) You are developing a user registration feature for a web application. The registration
form includes fields for username, email, password, and password confirmation. Your task
is to implement client-side validation to ensure that users enter valid information before
submitting the form. Additionally, you need to provide clear error messages for each
validation rule and prevent form submission if there are any errors. Write code to validate
the form inputs on the elient side using JavaScript, checking for the following conditions:
Use formData state is used to manage form input values. Use handleChange function
updates the formData state when input values change Use handleSubmit function is called
when the form is submitted. It validates the form data and either submits the form or sets
validation errors. Use validateForm function performs validation on form data and returns
an object containing validation errors. Use is ValidEmail function checks if the email format
is valid using a regular expression.

<!DOCTYPE html>

<html>

<head>

<title>Registration Form</title>

<style>

body {

font-family: Arial, sans-serif;

margin: 30px;

h2 {

color: #333;

input {

width: 300px;

padding: 8px;

margin-bottom: 10px;

display: block;

border: 1px solid #ccc;


border-radius: 4px;

button {

padding: 10px 20px;

background-color: #3498db;

color: white;

border: none;

border-radius: 4px;

cursor: pointer;

button:hover {

background-color: #2980b9;

.error {

color: red;

font-size: 0.9em;

margin-bottom: 10px;

.success {

color: green;

font-size: 1em;

margin-top: 15px;
}

</style>

</head>

<body>

<h2>User Registration</h2>

<form id="registrationForm" onsubmit="handleSubmit(event)">

<input type="text" name="username" placeholder="Username"


oninput="handleChange(event)">

<div class="error" id="usernameError"></div>

<input type="email" name="email" placeholder="Email"


oninput="handleChange(event)">

<div class="error" id="emailError"></div>

<input type="password" name="password" placeholder="Password"


oninput="handleChange(event)">

<div class="error" id="passwordError"></div>

<input type="password" name="confirmPassword" placeholder="Confirm Password"


oninput="handleChange(event)">

<div class="error" id="confirmPasswordError"></div>

<button type="submit">Register</button>

<div id="formSuccess" class="success"></div>

</form>
<script>

let formData = {

username: '',

email: '',

password: '',

confirmPassword: ''

};

function handleChange(event) {

const { name, value } = event.target;

formData[name] = value;

function isValidEmail(email) {

const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

return regex.test(email);

function validateForm(data) {

const errors = {};

if (!data.username.trim()) {

errors.username = "Username is required.";

if (!data.email.trim()) {
errors.email = "Email is required.";

} else if (!isValidEmail(data.email)) {

errors.email = "Invalid email format.";

if (!data.password) {

errors.password = "Password is required.";

} else if (data.password.length < 6) {

errors.password = "Password must be at least 6 characters.";

if (!data.confirmPassword) {

errors.confirmPassword = "Please confirm your password.";

} else if (data.password !== data.confirmPassword) {

errors.confirmPassword = "Passwords do not match.";

return errors;

function handleSubmit(event) {

event.preventDefault();

const errors = validateForm(formData);

// Clear previous error and success messages

document.querySelectorAll(".error").forEach(e => e.textContent = "");


document.getElementById("formSuccess").textContent = "";

if (Object.keys(errors).length === 0) {

document.getElementById("formSuccess").textContent = "Form submitted


successfully!";

document.getElementById("registrationForm").reset();

formData = { username: '', email: '', password: '', confirmPassword: '' };

} else {

for (let key in errors) {

document.getElementById(`${key}Error`).textContent = errors[key];

</script>

</body>

</html>

6. A) You're tasked with developing a web page featuring a text box where users can input a
4-digit OTP generated randomly. The entered vakue must match with the generated value,
when clicks a button. Here's a breakdown of the scenario and associated tasks: Designing
the User Interface: Create an HTML. file (home.html) to serve as the main page. Design the
layout with a text box for entering the 4-digit OTP value and a submit button. Implementing
JavaScript String: code to generate random value and validate the value. Write JavaScript
string function

<!DOCTYPE html>

<html>

<head>

<title>OTP Verification</title>
<style>

Body {

Font-family: Arial, sans-serif;

Padding: 50px;

Background-color: #f0f0f0;

.container {

Background: white;

Padding: 20px;

Width: 300px;

Margin: auto;

Border-radius: 8px;

Box-shadow: 0 0 10px #ccc;

Text-align: center;

Input {

Padding: 10px;

Margin: 10px 0;

Width: 100%;

Font-size: 16px;

Button {

Padding: 10px;

Background-color: #2ecc71;

Color: white;

Border: none;
Font-size: 16px;

Width: 100%;

Cursor: pointer;

#message {

Margin-top: 10px;

Font-weight: bold;

</style>

</head>

<body>

<div class=”container”>

<h2>Enter OTP</h2>

<input type=”text” id=”otpInput” placeholder=”Enter 4-digit OTP” maxlength=”4”>

<button onclick=”validateOTP()”>Verify OTP</button>

<div id=”message”></div>

</div>

<script>

// Generate a 4-digit OTP when page loads

Let generatedOTP = Math.floor(1000 + Math.random() * 9000).toString();

Console.log(“Generated OTP (for testing):”, generatedOTP);

Function validateOTP() {

Const userInput = document.getElementById(“otpInput”).value;


Const messageBox = document.getElementById(“message”);

If (userInput === generatedOTP) {

messageBox.style.color = “green”;

messageBox.textContent = “OTP Verified Successfully!”;

} else {

messageBox.style.color = “red”;

messageBox.textContent = “Invalid OTP. Please try again.”;

</script>

</body>

</html>

B) You are tasked with creating a simple Todo search application. The application should
allow users to search for Todo list by entering a keyword in an input field. Upon searching,
the application should fetch data from a Mysql table name Todo info and display a list of
events matching the search criteria. Requirements: Display an input field and a button
labelled "Search" 2. When the user enters a keyword in the input field and clicks the
"Search" button, the application should fetch data from Mysql table. 3. Display a list of
events matching the search criteria, showing at least the event name and time created
date. 4. Handle errors gracefully. If there's an issue with the request or no events are found
the given keyword, display an appropriate error message to the user. 5. Write a PHP
program to handle this request, populate and fetch the details from the table manually
using Mysql command

### MySQL Table Setup


```sql

CREATE DATABASE todo_app;

USE todo_app;

CREATE TABLE todo_info (

Id INT AUTO_INCREMENT PRIMARY KEY,

Event_name VARCHAR(255),

Created_at DATETIME DEFAULT CURRENT_TIMESTAMP

);

◼ Sample data

INSERT INTO todo_info (event_name) VALUES

(‘Buy groceries’),

(‘Meeting with client’),

(‘Complete assignment’);

```

### PHP Backend (`search_todo.php`)

```php

<?php

$host = “localhost”; // Change if needed

$user = “root”; // Your MySQL username

$password = “”; // Your MySQL password


$database = “todo_app”;

$conn = new mysqli($host, $user, $password, $database);

If ($conn->connect_error) {

Die(“Connection failed: “ . $conn->connect_error);

$keyword = isset($_GET[‘keyword’]) ? trim($_GET[‘keyword’]) : ‘’;

If ($keyword === ‘’) {

Echo json_encode([“error” => “Please enter a search keyword.”]);

Exit;

$stmt = $conn->prepare(“SELECT event_name, created_at FROM todo_info WHERE


event_name LIKE ?”);

$likeKeyword = “%$keyword%”;

$stmt->bind_param(“s”, $likeKeyword);

$stmt->execute();

$result = $stmt->get_result();

$events = [];

While ($row = $result->fetch_assoc()) {

$events[] = $row;
}

If (count($events) === 0) {

Echo json_encode([“error” => “No events found.”]);

} else {

Echo json_encode($events);

$stmt->close();

$conn->close();

?>

```

### HTML Frontend (`todo_search.html`)

```html

<!DOCTYPE html>

<html>

<head>

<title>Todo Search</title>

<style>

Body {

Font-family: Arial, sans-serif;

Padding: 30px;

}
Input, button {

Padding: 10px;

Font-size: 16px;

Margin: 5px;

.event {

Margin-top: 10px;

Padding: 8px;

Border-bottom: 1px solid #ccc;

</style>

</head>

<body>

<h2>Search Todo Events</h2>

<input type=”text” id=”keyword” placeholder=”Enter keyword”>

<button onclick=”searchTodo()”>Search</button>

<div id=”results”></div>

<script>

Function searchTodo() {

Const keyword = document.getElementById(“keyword”).value;

Const resultsDiv = document.getElementById(“results”);

resultsDiv.innerHTML = “Searching…”;
fetch(`search_todo.php?keyword=${encodeURIComponent(keyword)}`)

.then(response => response.json())

.then(data => {

resultsDiv.innerHTML = “”;

if (data.error) {

resultsDiv.textContent = data.error;

} else {

Data.forEach(event => {

Const div = document.createElement(“div”);

div.className = “event”;

div.innerHTML =
`<strong>${event.event_name}</strong><br><small>${event.created_at}</small>`;

resultsDiv.appendChild(div);

});

})

.catch(error => {

resultsDiv.textContent = “Error fetching data.”;

console.error(error);

});

</script>

</body>

</html>

```
3B

** Question:**

Design a webpage for the above registration form, validate the form using HTML, and
validate the following criteria using PHP with regular expressions:

1. All the fields are mandatory.

2. Check that the UserId is exactly 5 to 12 numerics.

3. Check that the phone number is exactly 7 to 12 numerics.

4. Check whether the sex and language are selected or not.

5. Check that the email is a valid email address.

- false if the email has fewer than 6 characters.

- false if the email does not contain an `@` symbol.

- false if the email does not contain a period (`.`).

- true otherwise

** Answer:**

**HTML (registration.html):**

```html

<!DOCTYPE html>

<html>

<head>

<title>Registration Form</title>

</head>

<body>

<h2>Registration Form</h2>
<form method=”POST” action=”validate.php”>

User Id: <input type=”text” name=”userid” required><br><br>

Phone Number: <input type=”text” name=”phone” required><br><br>

Email: <input type=”text” name=”email” required><br><br>

Sex:

<input type=”radio” name=”sex” value=”Male”>Male

<input type=”radio” name=”sex” value=”Female”>Female<br><br>

Language:

<input type=”checkbox” name=”language[]” value=”English”>English

<input type=”checkbox” name=”language[]” value=”Non-English”>Non-


English<br><br>

<input type=”submit” value=”Submit”>

</form>

</body>

</html>

```

**PHP (validate.php):**

```php

<?php

$errors = [];

If ($_SERVER[“REQUEST_METHOD”] == “POST”) {

$userid = $_POST[‘userid’];

$phone = $_POST[‘phone’];

$email = $_POST[‘email’];
$sex = isset($_POST[‘sex’]) ? $_POST[‘sex’] : ‘’;

$language = isset($_POST[‘language’]) ? $_POST[‘language’] : [];

If (!preg_match(‘/^\d{5,12}$/’, $userid)) {

$errors[] = “User ID must be 5 to 12 digits.”;

If (!preg_match(‘/^\d{7,12}$/’, $phone)) {

$errors[] = “Phone number must be 7 to 12 digits.”;

If (strlen($email) < 6 || strpos($email, ‘@’) === false || strpos($email, ‘.’) === false) {

$errors[] = “Invalid email format.”;

If (empty($sex)) {

$errors[] = “Please select your sex.”;

If (empty($language)) {

$errors[] = “Please select at least one language.”;

If (empty($errors)) {

Echo “<h2>Registration successful!</h2>”;

} else {
Echo “<h3>Validation Errors:</h3><ul>”;

Foreach ($errors as $error) {

Echo “<li style=’color:red;’>$error</li>”;

Echo “</ul>”;

?>

```

You might also like