[go: up one dir, main page]

0% found this document useful (0 votes)
18 views15 pages

Labsession 10 Webengineering

Uploaded by

Ayesha Asad
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)
18 views15 pages

Labsession 10 Webengineering

Uploaded by

Ayesha Asad
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/ 15

Web Engineering

Department of CS and SE

Lab Session 10: RESTful API using PHP and MySQL


RESTful API:
RESTful APIs (Representational State Transfer APIs) are a set of architectural principles for designing
networked applications. Here's an overview of the key concepts:
Resources: In a RESTful API, everything is treated as a resource. A resource can be any information that
can be named, such as a user, a product, or an order.
Uniform Interface: RESTful APIs have a uniform interface, which means that the communication
between the client and the server is standardized. This is typically achieved through HTTP methods like
GET, POST, PUT, DELETE, and PATCH.
HTTP Methods:
1. GET: Used to retrieve a resource from the server.
2. POST: Used to create a new resource on the server.
3. PUT: Used to update an existing resource on the server.
4. DELETE: Used to delete a resource from the server.
5. PATCH: Used to partially update a resource on the server.
Resource Representation: Resources in RESTful APIs are represented in different formats such as
JSON, XML, or HTML.
Stateless: RESTful APIs are stateless, meaning that each request from the client to the server must
contain all the information necessary to understand the request. The server does not store any client state
between requests.
Following is the guideline for creation of RESTful APIs for user creation, deletion and update.

 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

 It converts the response body to JSON using the .json() method.


 It then displays an alert with the message returned from the server.
 Finally, it calls a function fetchUsers() to fetch and display the updated list of users after creating
a new user.
Front End:

<!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);
});
});
}

// Function to handle form submission for creating user

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();
});
});

// Function to handle form submission for updating user

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();
});
});

// Function to handle form submission for deleting user

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();
});
});

// Fetch users on page load


fetchUsers();
</script>
</body>
</html>
Web Engineering

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");

Sets the content type of the response to JSON.


2. Retrieve Data from Request Body

$data = json_decode(file_get_contents("php://input"), true);

Retrieves JSON data from the request body and decodes it into a PHP associative array.
3. Database Connection

$conn = new mysqli("localhost", "root", "", "my_database");


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Checks if the database connection was successful. If not, terminates the script and prints an error
message.
4. Prepare SQL Statement

$stmt = $conn->prepare("INSERT INTO users (username, email, password) VALUES


(?, ?, ?)");
$stmt->bind_param("sss", $data['username'], $data['email'],
$data['password']);

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

if ($stmt->execute() === TRUE) {


echo json_encode(array("message" => "User created successfully"));
} else {
echo json_encode(array("error" => "Error: " . $conn->error));
}
Executes the prepared SQL statement. If successful, returns a JSON response indicating that the user was
created successfully. If there's an error, returns a JSON response with the error message.
6. Close Statement and Connection

$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

// Prepare and bind parameters


$stmt = $conn->prepare("DELETE FROM users WHERE id=?");
$stmt->bind_param("i", $data['id']);

// 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>

<input type="submit" name="submit" value="Add Product">


</form>

<?php
// Database configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "inventory";

// Create a database connection


$conn = new mysqli($servername, $username, $password, $dbname);
Web Engineering

Department of CS and SE

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

// Check if the form is submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$price = $_POST["price"];
$description = $_POST["description"];

// SQL query to insert new product into the "products" table


$sql = "INSERT INTO products (name, price, description) VALUES
('$name', '$price', '$description')";

// Execute the query


if ($conn->query($sql) === TRUE) {
echo "<p style='color: green;'>New product added
successfully!</p>";
} else {
echo "<p style='color: red;'>Error: " . $conn->error .
"</p>";
}
}

// Close the database connection


$conn->close();
?>
</div>
</body>
</html>

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

font-family: Arial, sans-serif;


background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
.container {
max-width: 800px;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
margin: 0 auto;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #4CAF50;
color: white;
}
.edit-btn, .delete-btn {
padding: 6px 12px;
margin-right: 5px;
text-decoration: none;
color: #fff;
border-radius: 4px;
cursor: pointer;
}
.edit-btn {
background-color: #007bff;
}
.delete-btn {
background-color: #dc3545;
}
input[type="text"],
Web Engineering

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";

// Create a database connection


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

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

// Check if edit or delete actions are triggered


if (isset($_GET['action']) && isset($_GET['id'])) {
Web Engineering

Department of CS and SE

$action = $_GET['action'];
$id = $_GET['id'];

if ($action === 'edit') {


// Display edit form
$sql = "SELECT * FROM products WHERE id = $id";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$name = $row['name'];
$price = $row['price'];
$description = $row['description'];

echo "<form method='post' action=''>


<input type='hidden' name='id' value='$id'>
<label for='name'>Product Name:</label>
<input type='text' id='name' name='name'
value='$name' required>

<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>

<input type='submit' name='update' value='Update


Product'>
</form>";
} else {
echo "<p>Product not found.</p>";
}
} elseif ($action === 'delete') {
// Delete product from the database
$sql = "DELETE FROM products WHERE id = $id";

if ($conn->query($sql) === TRUE) {


echo "<p>Product deleted successfully!</p>";
} else {
echo "Error deleting product: " . $conn->error;
Web Engineering

Department of CS and SE

}
}
}

// Check if update form is submitted


if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];

// Update product in the database


$sql = "UPDATE products SET name = '$name', price = '$price',
description = '$description' WHERE id = $id";

if ($conn->query($sql) === TRUE) {


echo "<p>Product updated successfully!</p>";
} else {
echo "Error updating product: " . $conn->error;
}
}

// Display all products in a table


$sql = "SELECT * FROM products";
$result = $conn->query($sql);

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>";

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


echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>$" . $row['price'] . "</td>";
echo "<td>" . $row['description'] . "</td>";
Web Engineering

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>";
}

// Close the database connection


$conn->close();
?>

</div>
</body>
</html>

You might also like