0% found this document useful (0 votes)
5 views7 pages

REG: T22-03-10577 Name: Paulo Michael Lukwaro Course: Bsc. Computer Science

The document contains PHP code examples for creating a Product and Book class, including methods for setting attributes and saving book information to a database. It also includes front-end JavaScript code for fetching books from an API and back-end PHP code for handling the request and returning book data in JSON format. Additionally, it outlines the SQL table structure for storing book information.

Uploaded by

Paul Programmer
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)
5 views7 pages

REG: T22-03-10577 Name: Paulo Michael Lukwaro Course: Bsc. Computer Science

The document contains PHP code examples for creating a Product and Book class, including methods for setting attributes and saving book information to a database. It also includes front-end JavaScript code for fetching books from an API and back-end PHP code for handling the request and returning book data in JSON format. Additionally, it outlines the SQL table structure for storing book information.

Uploaded by

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

REG: T22-03-10577

NAME: PAULO MICHAEL LUKWARO


COURSE: BSC. COMPUTER SCIENCE

Question 1:
<?php
class Product {
public $name;
public $description;
public $price;
}

$product1 = new Product();


$product1->name = 'iPhone 12';
$product1->description = 'Apple product';
$product1->price = 'Tsh 2,000,000';

echo $product1->name . "\n";


echo $product1->description . "\n";
echo $product1->price . "\n";
?>

Question 2:
<?php
class Book {
private $title;
private $author;
private $price;

public function setTitle($title) {


$this->title = $title;
}

public function setAuthor($author) {


$this->author = $author;
}

public function setPrice($price) {


$this->price = $price;
}

public function getTitle() {


return $this->title;
}

public function getAuthor() {


return $this->author;
}

public function getPrice() {


return $this->price;
}
public function saveToDatabase() {
$servername = "10.10.10.8";
$username = "bookUser";
$password = "book123";
$dbname = "bookApp";

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

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

$stmt = $conn->prepare("INSERT INTO books (title, author, price)


VALUES (?, ?, ?)");
$stmt->bind_param("ssd", $this->title, $this->author, $this->price);

if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $stmt->error;
}

$stmt->close();
$conn->close();
}
}
$book = new Book();
$book->setTitle("Sample Title");
$book->setAuthor("Sample Author");
$book->setPrice(19.99);
$book->saveToDatabase();
?>

TABLE STRUCTURE
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL
);

Question 3:
 Front-End (JavaScript with Ajax)

function fetchBooks() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://library.example.com/api/books", true);
xhr.setRequestHeader("Authorization", "Bearer LibraryBearerToken123");
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log(response);
} else {
console.error("Error:", xhr.status, xhr.statusText);
}
}
};

const data = JSON.stringify({


requester: "library_user",
action: "fetch_books"
});

xhr.send(data);
}
fetchBooks();

 Back-End (PHP)

<?php
header("Content-Type: application/json");

$bearerToken = "LibraryBearerToken123";
$requester = "library_user";
$validActions = ["fetch_books"];

$headers = getallheaders();
$token = isset($headers['Authorization']) ? str_replace('Bearer ', '',
$headers['Authorization']) : '';

if ($token !== $bearerToken) {


http_response_code(401);
echo json_encode(["error" => "Unauthorized: Invalid Bearer Token"]);
exit;
}

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

if (!isset($data['requester']) || $data['requester'] !== $requester) {


http_response_code(400);
echo json_encode(["error" => "Invalid Requester"]);
exit;
}

if (!isset($data['action']) || !in_array($data['action'], $validActions)) {


http_response_code(400);
echo json_encode(["error" => "Invalid Action"]);
exit;
}
$books = [
[
"title" => "Book 1",
"author" => "Author 1",
"genre" => "Fiction",
"year" => 2020,
"ISBN" => "1234567890"
],
[
"title" => "Book 2",
"author" => "Author 2",
"genre" => "Non-Fiction",
"year" => 2019,
"ISBN" => "0987654321"
]
];

echo json_encode($books);
?>

You might also like