0% found this document useful (0 votes)
26 views37 pages

Web Solutions

Web solutions

Uploaded by

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

Web Solutions

Web solutions

Uploaded by

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

Paper 1:

Q1:
a) What are the key characteristics of different web generations?
Web 1.0:
 Static Pages: Mostly read-only web with static HTML pages.
 Limited Interaction: Users could view information but had minimal interaction.
 Content Delivery: Information was delivered in a top-down approach.
 Technology: HTML, CSS, basic JavaScript, GIFs, and other basic multimedia elements.
Web 2.0:
 Dynamic Content: Interactive and user-generated content.
 Social Media: Rise of platforms like Facebook, Twitter, and blogs.
 Rich User Experience: AJAX for asynchronous data loading, making web applications
faster.
 Technologies: HTML, CSS, JavaScript (with frameworks like jQuery), AJAX, and APIs.
Web 3.0 (Semantic Web):
 Data Interconnection: Data is interconnected, enabling machines to understand and
process web content.
 AI and Machine Learning: Enhanced user experience through personalized content.
 Decentralization: Use of blockchain and decentralized applications (dApps).
 Technologies: RDF, SPARQL, OWL, and other semantic web technologies, along with AI
and machine learning algorithms.
b) What is responsive web design, and why is it important in modern web development?
Responsive Web Design (RWD):
 Definition: An approach to web design that makes web pages render well on a variety of
devices and window or screen sizes.
 Techniques: Utilizes flexible grids and layouts, CSS media queries, and responsive
images.
Importance:
 User Experience: Ensures optimal viewing and interaction experience across different
devices (desktops, tablets, smartphones).
 SEO: Improves search engine ranking as search engines prefer mobile-friendly websites.
 Cost-Effectiveness: Reduces the need for separate mobile and desktop versions of a
website.
c) How does XHTML differ from HTML in terms of syntax and rules?
XHTML vs. HTML:
 Syntax: XHTML is stricter and more XML-based. It requires:
o Well-formed documents.
o Lowercase tags and attributes.
o Quotes around attribute values.
o Closing all tags properly (self-closing tags like <br />).
 Rules: XHTML documents must be well-formed and valid XML documents, ensuring
better compatibility and stricter parsing by browsers.
 Error Handling: XHTML enforces stricter error handling, while HTML is more forgiving of
mistakes.
Q2:
a) Contrast block-level and inline elements, providing an example of each.
Block-Level Elements:
 Behavior: Occupy the full width available and start on a new line.
 Example: <div>, <h1>, <p>.
Inline Elements:
 Behavior: Only occupy the width necessary and do not start on a new line.
 Example: <span>, <a>, <img>.
b) Implement an HTML5 form with at least three different input types, and validate the inputs
using HTML5 attributes.
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML5 Form</title>
</head>
<body>
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>

<label for="age">Age:</label>
<input type="number" id="age" name="age" min="18" max="100" required>

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


</form>
</body>
</html>
c) How does the Bootstrap grid system assist in the creation of responsive layouts? Write
Bootstrap code for the specified layout.
Bootstrap Grid System:
 Flexibility: Uses a 12-column grid system to create responsive layouts.
 Responsiveness: Adjusts the layout based on screen size using breakpoints.
 Ease of Use: Simplifies the creation of complex layouts with predefined classes.
Bootstrap Code for Specified Layout:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bootstrap Grid Layout</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<!-- First row with 2 columns -->
<div class="row">
<div class="col-md-8">Column 1 (bigger)</div>
<div class="col-md-4">Column 2 (smaller)</div>
</div>
<!-- Second row with 4 columns -->
<div class="row">
<div class="col-md-2">Column 1</div>
<div class="col-md-2">Column 2</div>
<div class="col-md-2">Column 3</div>
<div class="col-md-6">Column 4 (equal to 3 combined)</div>
</div>
<!-- Third row with 4 columns -->
<div class="row">
<div class="col-md-4">Column 1 (bigger)</div>
<div class="col-md-4">Column 2 (bigger)</div>
<div class="col-md-2">Column 3 (smaller)</div>
<div class="col-md-2">Column 4 (smaller)</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></
script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></
script>
</body>
</html>
Q3:
a) Write a JavaScript function that displays a question in a prompt box and gets its answer. If
the answer is correct, it shows a success message; otherwise, it displays an error message.
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Prompt</title>
<script>
function askQuestion() {
var answer = prompt("What is the capital of France?");
if (answer.toLowerCase() === "paris") {
alert("Correct! Success.");
} else {
alert("Incorrect. The correct answer is Paris.");
}
}
</script>
</head>
<body onload="askQuestion()">
</body>
</html>
b) Create an HTML page that accepts an email and password from the user. Use regular
expressions to validate the email format and ensure the password meets specific criteria.
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Validation</title>
<style>
.hidden {
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function() {
$(this).hide();
});
});

function validateForm() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;

var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;


var passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;

if (!emailPattern.test(email)) {
alert("Invalid email format.");
return false;
}
if (!passwordPattern.test(password)) {
alert("Password must be at least 8 characters long and contain both letters and
numbers.");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return validateForm()">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>

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


</form>

<div class="hidden">Click me to hide</div>


<div class="hidden">Click me to hide</div>
<div class="hidden">Click me to hide</div>
</body>
</html>

HTML and jQuery for Clickable Divs to Hide

Here’s the HTML layout with jQuery code to hide the elements when they are clicked:

html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hide Elements on Click</title>
<style>
.hideable {
border: 1px solid black;
padding: 10px;
margin: 10px;
cursor: pointer;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$(".hideable").click(function() {
$(this).hide();
});
});
</script>
</head>
<body>
<div class="hideable">Click me to hide</div>
<div class="hideable">Click me to hide</div>
<div class="hideable">Click me to hide</div>
</body>
</html>

Explanation:

1. HTML Layout:
o Each clickable element is contained within a div with the class hideable.
o The style section provides basic styling for the div elements to make them
distinguishable with borders and padding.
2. jQuery:
o The script includes the jQuery library from a CDN.
o When the document is fully loaded ($(document).ready()), an event listener is
attached to elements with the class hideable.
o When any of these elements is clicked, the click event triggers the hide
function, making the clicked element disappear.

This setup ensures that the specified div elements will hide themselves when clicked, providing
the desired interactive behavior.

Q3 (d): Difference Between find and filter Methods in jQuery with Examples
find Method:
 Purpose: The find method searches for descendant elements that match the specified
selector.
 Usage: It is used to filter elements within the children of the matched set.
Example:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery find vs filter</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// Example using find
$("#container").find(".child").css("background-color", "yellow");
});
</script>
</head>
<body>
<div id="container">
<div class="child">Child 1</div>
<div class="child">Child 2</div>
<div class="other">Not a child</div>
</div>
</body>
</html>
 Explanation: This code will find all .child elements within the #container and change
their background color to yellow.
filter Method:
 Purpose: The filter method reduces the set of matched elements to those that match
the selector.
 Usage: It is used to filter the elements in the current set.
Example:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery find vs filter</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// Example using filter
$("#container .child").filter(":first").css("background-color", "blue");
});
</script>
</head>
<body>
<div id="container">
<div class="child">Child 1</div>
<div class="child">Child 2</div>
<div class="child">Child 3</div>
</div>
</body>
</html>
 Explanation: This code will filter the first .child element within #container and change its
background color to blue.
Q4:
a) PHP Super Global Variables with Examples
$_SERVER:
 Definition: $_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations.
 Example:
php
Copy code
<?php
echo $_SERVER['SERVER_NAME']; // Outputs the name of the server
echo $_SERVER['REQUEST_METHOD']; // Outputs the request method (GET, POST, etc.)
?>
$_POST:
 Definition: $_POST is used to collect form data after submitting an HTML form with
method="post".
 Example:
php
Copy code
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo "Name: $name";
}
?>
$_GET:
 Definition: $_GET is used to collect form data after submitting an HTML form with
method="get".
 Example:
php
Copy code
<form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$name = $_GET['name'];
echo "Name: $name";
}
?>
b) PHP Code to Connect to MySQL Database and Display Data
php
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Customer Info</title>
</head>
<body>
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "customer";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Query to retrieve data


$sql = "SELECT CID, Name, Address, OrderNo FROM customer_info";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// Display data in table
echo "<table
border='1'><tr><th>CID</th><th>Name</th><th>Address</th><th>OrderNo</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["CID"] . "</td><td>" . $row["Name"] . "</td><td>" .
$row["Address"] . "</td><td>" . $row["OrderNo"] . "</td></tr>";
}
echo "</table>";
} else {
echo "No records found.";
}

// Close connection
$conn->close();
?>
</body>
</html>
Q5:
a) Purpose of Routing in Laravel and Difference Between Named and Anonymous Routes
Purpose of Routing:
 Definition: Routing in Laravel is used to define the routes or URLs for the application.
 Functionality: Routes map URLs to specific controllers or views, enabling a clean and
organized URL structure.
Named Routes:
 Definition: Named routes allow you to refer to routes when generating URLs or
redirects.
 Usage:
php
Copy code
Route::get('/user/profile', 'UserController@showProfile')->name('profile');
// Usage
$url = route('profile');
return redirect()->route('profile');
Anonymous Routes:
 Definition: Anonymous routes do not have a name and are referred to by their URL.
 Usage:
php
Copy code
Route::get('/user/profile', 'UserController@showProfile');
// Usage
$url = url('/user/profile');
return redirect('/user/profile');
b) Route Parameters and Constraints in Laravel
Route Parameters:
 Definition: Route parameters are placeholders in route URLs.
 Usage:
php
Copy code
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
});
Accessing Parameters:
 In Controller:
php
Copy code
Route::get('/user/{id}', 'UserController@show');
// UserController.php
public function show($id) {
return 'User '.$id;
}
Constraints:
 Numeric Constraint:
php
Copy code
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
})->where('id', '[0-9]+');
 Alphabetic Constraint:
php
Copy code
Route::get('/user/{name}', function ($name) {
return 'User '.$name;
})->where('name', '[A-Za-z]+');
c) Blade Templating and Usage of forelse Directive
Blade Templating:
 Definition: Blade is Laravel's templating engine that provides syntax for common tasks
like loops and conditionals.
 Example Using forelse:
php
Copy code
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
d) Simple Laravel Program for Calculating Factorial in Blade
welcome.blade.php:
php
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Factorial Calculation</title>
</head>
<body>
@php
$number = 5;
$factorial = 1;
for ($i = 1; $i <= $number; $i++) {
$factorial *= $i;
}
@endphp
<p>The factorial of {{ $number }} is {{ $factorial }}.</p>
</body>
</html>
Explanation:
1. Blade Templating:
o Usage: Blade templates are stored in the resources/views directory and use
the .blade.php file extension.
2. Factorial Calculation:
o PHP Block: The @php directive allows embedding PHP code within Blade
templates.
o Calculation: A loop calculates the factorial of the specified number.
o Output: The result is displayed within a paragraph.

Paper 2:

Integration of CSS in a Web Page


CSS can be integrated into a web page in three different ways:
1. Inline CSS: Directly within HTML elements using the style attribute.
2. Internal CSS: Within the <style> tag in the <head> section of the HTML document.
3. External CSS: Using the <link> tag to reference an external CSS file.
Examples
Inline CSS:
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS Example</title>
</head>
<body>
<h1 style="color: blue;">Hello, World!</h1>
<p style="font-size: 16px; color: green;">This is a paragraph with inline CSS.</p>
</body>
</html>
Internal CSS:
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Internal CSS Example</title>
<style>
h1 {
color: blue;
}
p{
font-size: 16px;
color: green;
}
</style>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph with internal CSS.</p>
</body>
</html>
External CSS:
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>External CSS Example</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph with external CSS.</p>
</body>
</html>
styles.css:
css
Copy code
h1 {
color: blue;
}

p{
font-size: 16px;
color: green;
}
Best Type for Web
External CSS is generally considered the best practice for web development. It separates the
content (HTML) from the presentation (CSS), making the code more maintainable, reusable,
and easier to read. This separation allows multiple HTML files to share the same CSS file,
reducing redundancy and improving the efficiency of updates.
Bootstrap Grid System
The Bootstrap grid system uses a series of containers, rows, and columns to layout and align
content. It's built with flexbox and is fully responsive. The system is based on a 12-column
layout, where you can define how many columns an element should span.
HTML Code with Bootstrap
To create a layout with 2 rows, where the first row has 2 columns and the second row has 6
columns, you can use the following HTML code:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap Grid Example</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">Column 1</div>
<div class="col-md-6">Column 2</div>
</div>
<div class="row">
<div class="col-md-2">Column 1</div>
<div class="col-md-2">Column 2</div>
<div class="col-md-2">Column 3</div>
<div class="col-md-2">Column 4</div>
<div class="col-md-2">Column 5</div>
<div class="col-md-2">Column 6</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></
script>
</body>
</html>
Difference between include and require in PHP
Both include and require are used to include the contents of one PHP file into another PHP file
before the server executes it. The key difference between the two is how they handle errors:
 include: If the file cannot be found, a warning (E_WARNING) is issued, but the script
continues execution.
 require: If the file cannot be found, a fatal error (E_COMPILE_ERROR) is issued, and the
script stops execution.
Examples
Using include:
php
Copy code
<?php
include 'non_existent_file.php';
echo "This will be printed even if the file is not found.";
?>
Output:
vbnet
Copy code
Warning: include(non_existent_file.php): failed to open stream: No such file or directory
This will be printed even if the file is not found.
Using require:
php
Copy code
<?php
require 'non_existent_file.php';
echo "This will not be printed if the file is not found.";
?>
Output:
lua
Copy code
Fatal error: require(): Failed opening required 'non_existent_file.php'
Laravel Blade Syntax
In Laravel Blade, you use double curly braces {{ }} to output variables, and the @ symbol for
directives such as loops and conditionals. For example:
php
Copy code
// In your controller
$data = ['item1' => 'Value 1', 'item2' => 'Value 2', 'item3' => 'Value 3'];
return view('example', compact('data'));
blade
Copy code
<!-- In your Blade view (example.blade.php) -->
@foreach ($data as $key => $value)
<p>{{ $key }}: {{ $value }}</p>
@endforeach
Defining a Route in Laravel
To define a route in Laravel, you edit the routes/web.php file. Here is an example of a basic
route:
php
Copy code
Route::get('/greeting', function () {
return 'Hello, World!';
});
PHP Sessions
Sessions in PHP allow you to store data across multiple pages for a user. You start a session
using session_start(), set session variables, and retrieve them on subsequent pages.
Example of Storing and Deleting Session Data
Starting a Session and Storing Data:
php
Copy code
<?php
session_start();
$_SESSION['username'] = 'JohnDoe';
echo "Session variable is set.";
?>
Deleting a Session Variable:
php
Copy code
<?php
session_start();
unset($_SESSION['username']);
echo "Session variable is deleted.";
?>
Laravel Blade Templating Engine
Blade is Laravel’s templating engine that provides a simple way to structure your views. It
supports template inheritance and includes many directives for loops, conditionals, and more.
Passing Data from Controller to View
Controller Method:
php
Copy code
public function show()
{
$data = [
'item1' => 'Value 1',
'item2' => 'Value 2',
'item3' => 'Value 3'
];
return view('example')->with('data', $data);
}
Blade View:
blade
Copy code
@foreach ($data as $key => $value)
<p>{{ $key }}: {{ $value }}</p>
@endforeach
Purpose of Migrations in Laravel
Migrations are a type of version control for your database. They allow you to define your
database schema, and easily share and apply these changes. They make it easy to roll back
changes, ensuring that your database schema can be consistently applied across different
environments.
Creating a Table
To create a table using a migration:
php
Copy code
public function up()
{
Schema::create('example_table', function (Blueprint $table) {
$table->id();
$table->string('column1');
$table->string('column2');
$table->timestamps();
});
}
HTML Form and Storing Data in Laravel
HTML Form:
html
Copy code
<form action="/store" method="POST">
@csrf
<label for="field1">Field 1:</label>
<input type="text" id="field1" name="field1">
<label for="field2">Field 2:</label>
<input type="text" id="field2" name="field2">
<button type="submit">Submit</button>
</form>
Controller Method to Store Data:
php
Copy code
public function store(Request $request)
{
$data = $request->validate([
'field1' => 'required|string',
'field2' => 'required|string'
]);

$example = new Example();


$example->field1 = $data['field1'];
$example->field2 = $data['field2'];
$example->save();

return redirect()->back()->with('message', 'Data successfully saved!');


}
Displaying Success Message:
blade
Copy code
@if (session('message'))
<p>{{ session('message') }}</p>
@endif
This detailed guide covers the main aspects of integrating CSS, using Bootstrap, and working
with Laravel for various common tasks.

Paper 3:
Q1: Difference between require, require_once, include, and include_once in PHP
 require: This statement includes and evaluates a specified file. If the file is not found, it
causes a fatal error and stops the execution of the script.
 require_once: Similar to require, but it checks if the file has already been included, and
if so, does not include it again. This is useful to avoid function redefinitions or variable
redeclarations.
 include: Includes and evaluates a specified file. If the file is not found, it causes a
warning, but the script continues to execute.
 include_once: Similar to include, but it checks if the file has already been included, and
if so, does not include it again.
Example:
php
Copy code
// require.php
require 'header.php'; // Causes a fatal error if header.php does not exist
echo "This will not be executed if header.php is missing.";

// require_once.php
require_once 'header.php'; // Will include header.php only once

// include.php
include 'header.php'; // Causes a warning if header.php does not exist
echo "This will be executed even if header.php is missing.";
// include_once.php
include_once 'header.php'; // Will include header.php only once
Q2: Use of header() function in PHP
The header() function is used to send raw HTTP headers to the browser. It must be called
before any actual output is sent.
Example:
php
Copy code
<?php
// Redirect to another page
header("Location: http://www.example.com/");
exit;

// Set content type to JSON


header("Content-Type: application/json");
echo json_encode(array("name" => "John", "age" => 30));
?>
Q3: Differentiate between Web Server and Database Server
 Web Server: A server that handles HTTP requests from clients (browsers), serving web
pages and other content. Examples include Apache, Nginx.
o Example: Apache serving HTML/CSS/JavaScript files.
 Database Server: A server that provides database services and handles database queries
from clients. Examples include MySQL, PostgreSQL.
o Example: MySQL managing and providing access to a database of user
information.
Q4: Need for Sessions in Websites
Sessions are used to store information about a user across multiple pages of a web application.
They are required for maintaining user state, such as login status, shopping cart contents, etc.
Example:
php
Copy code
<?php
// Start a session
session_start();

// Set session variables


$_SESSION["username"] = "john_doe";
$_SESSION["email"] = "[email protected]";

// Access session variables


echo "Username: " . $_SESSION["username"];
echo "Email: " . $_SESSION["email"];

// Reset session variables


unset($_SESSION["username"]);
session_destroy();
?>
Q5: Main Areas for JavaScript Usage and Form Validation Code
JavaScript can be used for:
1. Client-side validation
2. Dynamic content updates
3. Interactive UI/UX
4. Asynchronous requests (AJAX)
5. Animations
Form Validation Code:
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Student Registration Form</title>
<script>
function validateForm() {
var name = document.forms["registrationForm"]["name"].value;
var age = document.forms["registrationForm"]["age"].value;
var email = document.forms["registrationForm"]["email"].value;
var phone = document.forms["registrationForm"]["phone"].value;
var cnic = document.forms["registrationForm"]["cnic"].value;

if (name == "" || age == "" || email == "" || phone == "" || cnic == "") {
alert("All fields must be filled out");
return false;
}
if (isNaN(age) || age < 1) {
alert("Please enter a valid age");
return false;
}
var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!email.match(emailPattern)) {
alert("Please enter a valid email address");
return false;
}
var phonePattern = /^\d{10}$/;
if (!phone.match(phonePattern)) {
alert("Please enter a valid 10-digit phone number");
return false;
}
var cnicPattern = /^\d{13}$/;
if (!cnic.match(cnicPattern)) {
alert("Please enter a valid 13-digit CNIC number");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="registrationForm" onsubmit="return validateForm()">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
Email: <input type="text" name="email"><br>
Phone: <input type="text" name="phone"><br>
CNIC: <input type="text" name="cnic"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Q6: JavaScript Program to Swap Images and Text
HTML and JavaScript Code:
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Swap Images and Text</title>
<script>
function swapContent() {
var img1 = document.getElementById("image1").src;
var img2 = document.getElementById("image2").src;
var text1 = document.getElementById("text1").innerHTML;
var text2 = document.getElementById("text2").innerHTML;

document.getElementById("image1").src = img2;
document.getElementById("image2").src = img1;
document.getElementById("text1").innerHTML = text2;
document.getElementById("text2").innerHTML = text1;
}
</script>
</head>
<body>
<img id="image1" src="image1.jpg" alt="Image 1">
<p id="text1">Text 1</p>
<img id="image2" src="image2.jpg" alt="Image 2">
<p id="text2">Text 2</p>
<button onclick="swapContent()">Swap</button>
</body>
</html>
Q7: PHP Web Application with Employee Table
i. Code to Connect to MySQL Database:
php
Copy code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

// Check connection
if ($conn->connect_error)
{ die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?>
php
Copy code

**ii. Query to Select Employees with Salary Greater Than 40,000 and Display in HTML Table:**

```php
<?php
$sql = "SELECT emp_id, emp_name, emp_cnic, emp_salary FROM employee WHERE
emp_salary > 40000";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table border='1'><tr><th>ID</th><th>Name</th><th>CNIC</th><th>Salary</th></
tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["emp_id"]. "</td><td>" . $row["emp_name"]. "</td><td>" .
$row["emp_cnic"]. "</td><td>" . $row["emp_salary"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
iii. HTML Form for New Employee and PHP Code to Save Employee Data:
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Add New Employee</title>
</head>
<body>
<form action="save_employee.php" method="post">
Name: <input type="text" name="emp_name"><br>
CNIC: <input type="text" name="emp_cnic"><br>
Salary: <input type="text" name="emp_salary"><br>
<input type="submit" value="Save Employee">
</form>
</body>
</html>
save_employee.php to Handle Form Submission:
php
Copy code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Retrieve form data


$emp_name = $_POST['emp_name'];
$emp_cnic = $_POST['emp_cnic'];
$emp_salary = $_POST['emp_salary'];

// Prepare and bind


$stmt = $conn->prepare("INSERT INTO employee (emp_name, emp_cnic, emp_salary) VALUES
(?, ?, ?)");
$stmt->bind_param("ssi", $emp_name, $emp_cnic, $emp_salary);
// Execute the statement
if ($stmt->execute()) {
echo "New employee record created successfully";
} else {
echo "Error: " . $stmt->error;
}

// Close the statement and connection


$stmt->close();
$conn->close();
?>

You might also like