Labsession 10 Webengineering
Labsession 10 Webengineering
Department of CS and SE
The HTML code sets up a form for creating a user, containing input fields for username, email,
and password, along with a submit button.
The JavaScript code adds an event listener to the form with the id "createUserForm". It listens for
the form submission event.
When the form is submitted, the event listener function is triggered.
The function prevents the default form submission behavior using event.preventDefault() to avoid
the page from refreshing.
It creates a new FormData object from the form data, which includes the username, email, and
password entered by the user. the FormData object is a built-in JavaScript object that allows you
to easily construct a set of key/value pairs representing form fields and their values. When you
pass a form element to the FormData constructor, it automatically collects all the form's input
fields and their values.
It uses the Fetch API to send an HTTP POST request to the server-side script "create_user.php".
The request includes the form data converted to JSON using JSON.stringify().
It sets the content type of the request to "application/json".
Once the server processes the request and sends back a response, the JavaScript code handles the
response.
Web Engineering
Department of CS and SE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>User Management</title>
</head>
<body>
<h1>User Management</h1>
<h2>Create User</h2>
<form id="createUserForm">
Username: <input type="text" name="username"><br>
Email: <input type="email" name="email"><br>
Password: <input type="password" name="password"><br>
<button type="submit">Create User</button>
</form>
<h2>Update User</h2>
<form id="updateUserForm">
User ID: <input type="number" name="id"><br>
Username: <input type="text" name="username"><br>
Email: <input type="email" name="email"><br>
Password: <input type="password" name="password"><br>
<button type="submit">Update User</button>
</form>
<h2>Delete User</h2>
<form id="deleteUserForm">
User ID: <input type="number" name="id"><br>
<button type="submit">Delete User</button>
</form>
<h2>Users</h2>
<ul id="userList"></ul>
Web Engineering
Department of CS and SE
<script>
// Function to fetch and display users
function fetchUsers() {
fetch('get_users.php')
.then(response => response.json())
.then(users => {
const userList =
document.getElementById('userList');
userList.innerHTML = '';
users.forEach(user => {
const li = document.createElement('li');
li.textContent = `${user.username} - $
{user.email}`;
userList.appendChild(li);
});
});
}
document.getElementById('createUserForm').addEventListener('submit',
function(event) {
const formData = new FormData(this);
fetch('create_user.php', {
method: 'POST',
body: JSON.stringify(Object.fromEntries(formData)),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
alert(data.message);
fetchUsers();
});
});
document.getElementById('updateUserForm').addEventListener('submit',
function(event) {
Web Engineering
Department of CS and SE
event.preventDefault();
const formData = new FormData(this);
fetch('update_user.php', {
method: 'PUT',
body: JSON.stringify(Object.fromEntries(formData)),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
alert(data.message);
fetchUsers();
});
});
document.getElementById('deleteUserForm').addEventListener('submit',
function(event) {
event.preventDefault();
const formData = new FormData(this);
fetch('delete_user.php', {
method: 'DELETE',
body: JSON.stringify(Object.fromEntries(formData)),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
alert(data.message);
fetchUsers();
});
});
Department of CS and SE
User Creation:
Create create_user.php endpoint for creation of user.
1. Setting Content Type
header("Content-Type: application/json");
Retrieves JSON data from the request body and decodes it into a PHP associative array.
3. Database Connection
Prepares an SQL statement for inserting a new user into the database. Binds parameters to the prepared
statement to prevent SQL injection attacks.
5. Execute Statement
$stmt->close();
$conn->close();
Web Engineering
Department of CS and SE
Closes the prepared statement and the database connection to free up resources.
This script is designed to handle HTTP POST requests containing JSON data representing a new user. It
inserts the user into a MySQL database table named users. If successful, it returns a JSON response
indicating success; otherwise, it returns an error message.
Similar approach can be used for deleting and updating user info.
Updating User
<?php
header("Content-Type: application/json");
$data = json_decode(file_get_contents("php://input"), true);
$conn = new mysqli("localhost", "root", "", "my_database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("UPDATE users SET username=?, email=?, password=?
WHERE id=?");
$stmt->bind_param("sssi", $data['username'], $data['email'],
$data['password'], $data['id']);
if ($stmt->execute() === TRUE) {
echo json_encode(array("message" => "User updated successfully"));
} else {
echo json_encode(array("error" => "Error: " . $stmt->error));
}
$stmt->close();
$conn->close();
?>
User Deletion
// delete_user.php
<?php
header("Content-Type: application/json");
$data = json_decode(file_get_contents("php://input"), true);
// Connect to MySQL
$conn = new mysqli("localhost", "root", "", "my_database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Web Engineering
Department of CS and SE
// Execute statement
if ($stmt->execute() === TRUE) {
echo json_encode(array("message" => "User deleted successfully"));
} else {
echo json_encode(array("error" => "Error: " . $stmt->error));
}
$stmt->close();
$conn->close();
?>
Web Engineering
Department of CS and SE
Exercise
1. Implement the PHP script to create a MySQL database named "products" with a table
named "products" having fields for id, name, description, price, and quantity.
<!DOCTYPE html>
<html>
<head>
<title>Add New Product</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
.container {
max-width: 600px;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
margin: 0 auto;
}
h2 {
text-align: center;
color: #333;
}
label {
display: block;
font-weight: bold;
margin-bottom: 8px;
}
input[type="text"],
input[type="submit"],
textarea {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 5px;
box-sizing: border-box;
font-size: 16px;
Web Engineering
Department of CS and SE
}
textarea {
height: 100px;
}
input[type="submit"] {
background-color: #4CAF50;
color: #fff;
border: none;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h2>Add New Product</h2>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="name">Product Name:</label>
<input type="text" id="name" name="name" required>
<label for="price">Price:</label>
<input type="text" id="price" name="price" required>
<label for="description">Description:</label>
<textarea id="description" name="description" rows="4"
required></textarea>
<?php
// Database configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "inventory";
Department of CS and SE
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
2. Write PHP scripts to handle RESTful API endpoints for CRUD operations (Create, Read,
Update, Delete) to interact with the "products" table.
<!DOCTYPE html>
<html>
<head>
<title>Manage Products</title>
<style>
body {
Web Engineering
Department of CS and SE
Department of CS and SE
textarea,
input[type="submit"] {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 5px;
box-sizing: border-box;
font-size: 16px;
}
input[type="submit"] {
background-color: #4CAF50;
color: #fff;
border: none;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h2>Manage Products</h2>
<?php
// Database configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "inventory";
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Department of CS and SE
$action = $_GET['action'];
$id = $_GET['id'];
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$name = $row['name'];
$price = $row['price'];
$description = $row['description'];
<label for='price'>Price:</label>
<input type='text' id='price' name='price'
value='$price' required>
<label for='description'>Description:</label>
<textarea id='description' name='description'
required>$description</textarea>
Department of CS and SE
}
}
}
if ($result->num_rows > 0) {
echo "<table>";
echo "<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Description</th>
<th>Action</th>
</tr>";
Department of CS and SE
echo "<td>
<a href='?action=edit&id=" . $row['id'] . "'
class='edit-btn'>Edit</a>
<a href='?action=delete&id=" . $row['id'] . "'
class='delete-btn'>Delete</a>
</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "<p>No products found.</p>";
}
</div>
</body>
</html>