Initial Commit

This commit is contained in:
Yannic 2025-09-25 17:35:18 +02:00
commit 9ad6876181
5 changed files with 786 additions and 0 deletions

12
db/bootstrap.php Normal file
View file

@ -0,0 +1,12 @@
<?php
$dbhost = "localhost";
$dbname = "library";
$dbuser = "root";
$dbpw = "";
try{
$pdo = new PDO("mysql:host=$dbhost; dbname=$dbname; charset=utf8", $dbuser, $dbpw);
}catch(PDOException $e){
die("Connection failed: " . $e->getMessage());
}
?>

190
db/functions.php Normal file
View file

@ -0,0 +1,190 @@
<?php
include "bootstrap.php";
/////////GET BOOKS/////////
function getBooks($pdo){
$stmt = $pdo->query("SELECT bookID, title, author FROM books ORDER BY title ASC");
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $books;
}
/////////GET BORROWERS/////////
function getBorrowers($pdo){
$stmt = $pdo->query("SELECT * FROM borrowers ORDER BY lastName ASC");
$borrowers = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $borrowers;
}
/////////GET AVAILABLE COPIES OF BOOK/////////
function getAvailableCopiesOfBook($pdo, $bookID){
$stmt = $pdo->query("SELECT * FROM copies WHERE bookID = $bookID AND isBorrowed = 0 ORDER BY copyID ASC");
$copies = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $copies;
}
/////////GET BORROWED COPIES OF BORROWER/////////
function getBorrowedCopiesOfBorrower($pdo, $borrowerID){
$stmt = $pdo->query("SELECT
loans.loanID,
loans.copyID,
copies.bookCondition as bookCondition,
books.title as bookTitle,
books.author as bookAuthor
FROM loans
INNER JOIN copies ON loans.copyID = copies.copyID
INNER JOIN books ON copies.bookID = books.bookID
WHERE borrowerID = $borrowerID AND returnedDate IS NULL
ORDER BY copyID ASC");
$copies = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $copies;
}
/////////GET ACTIVE LOANS/////////
function getActiveLoans($pdo){
$stmt = $pdo->query("SELECT
loans.*,
books.title as bookTitle,
books.author as bookAuthor,
borrowers.firstName as firstName,
borrowers.lastName as lastName,
borrowers.role as borrowerRole
FROM loans
INNER JOIN copies ON loans.copyID = copies.copyID
INNER JOIN books ON copies.bookID = books.bookID
INNER JOIN borrowers on loans.borrowerID = borrowers.borrowerID
WHERE loans.returnedDate IS NULL
ORDER BY dueDate ASC");
$activeLoans = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $activeLoans;
}
/////////GET LATE LOANS/////////
function getLateLoans($pdo){
$currentDate = date("Y-m-d");
$sql = "SELECT
loans.*,
books.title as bookTitle,
books.author as bookAuthor,
borrowers.firstName as firstName,
borrowers.lastName as lastName,
borrowers.role as borrowerRole
FROM loans
INNER JOIN copies ON loans.copyID = copies.copyID
INNER JOIN books ON copies.bookID = books.bookID
INNER JOIN borrowers on loans.borrowerID = borrowers.borrowerID
WHERE loans.dueDate < ? AND loans.returnedDate IS NULL
ORDER BY dueDate ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute([$currentDate]);
$lateLoans = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $lateLoans;
}
/////////ADD COPIES/////////
function addCopies($pdo, $bookID, $amount, $copyCondition){
for($i=0; $i<$amount; $i++){
$sql = "INSERT INTO copies (bookID, bookCondition) VALUES (:bookID, :bookCondition)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':bookID', $bookID);
$stmt->bindParam(':bookCondition', $copyCondition);
try {
$stmt->execute();
$successfullyAdded = true;
} catch (PDOException $e) {
echo "<p>Error: " . $e->getMessage() . "</p>";
}
}
if($successfullyAdded){
if($amount > 1)
{
echo $amount . " Copies added successfully!";
}else{
echo "Copy added successfully!";
}
}
}
/////////ADD BOOK/////////
function addBook($pdo, $title, $author, $area){
$sql = "INSERT INTO books (title, author, areaOfStudy) VALUES (:title, :author, :area)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':author', $author);
$stmt->bindParam(':area', $area);
try {
$stmt->execute();
echo "<p>Book added successfully!</p>";
} catch (PDOException $e) {
echo "<p>Error: " . $e->getMessage() . "</p>";
}
}
/////////ADD BORROWER/////////
function addBorrower($pdo, $firstname, $lastname, $role){
$sql = "INSERT INTO borrowers (firstname, lastname, role) VALUES (:firstname, :lastname, :role)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":firstname", $firstname);
$stmt->bindParam(":lastname", $lastname);
$stmt->bindParam(":role", $role);
try{
$stmt->execute();
echo "<p>Borrowers added!</p>";
}catch(PDOException $e){
echo "<p>Error: " . $e->getMessage() . "</p>";
}
}
/////////ADD LOAN/////////
function addLoan($pdo, $copyID, $borrowerID, $borrowedDate, $dueDate){
$sql = "INSERT INTO loans (copyID, borrowerID, borrowedDate, dueDate) VALUES (:copyID, :borrowerID, :borrowedDate, :dueDate)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":copyID", $copyID);
$stmt->bindParam("borrowerID", $borrowerID);
$stmt->bindParam("borrowedDate", $borrowedDate);
$stmt->bindParam(":dueDate", $dueDate);
try{
$stmt->execute();
echo "<p>Loan added!</p>";
}catch(PDOException $e){
echo "<p>Error: " . $e->getMessage() . "</p>";
}
$sql = "UPDATE copies SET isBorrowed=? WHERE copyID=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([1, $copyID]);
}
/////////REMOVE LOAN/////////
function removeLoan($pdo, $copyID, $loanID, $dateReturned){
$sql = "UPDATE loans SET returnedDate = ? WHERE copyID = ? AND loanID = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$dateReturned, $copyID, $loanID]);
$sql = "UPDATE copies SET isBorrowed=? WHERE copyID=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([0, $copyID]);
}
/////////SELECT REQUEST/////////
function selectRequest($pdo, $selectRequest){
$stmt = $pdo -> query("SELECT " . $selectRequest);
$results = $stmt -> fetchAll(PDO::FETCH_ASSOC);
foreach($results as $result){
echo '<pre>'; print_r($result); echo '</pre>';
}
}
?>

449
index.php Normal file
View file

@ -0,0 +1,449 @@
<!DOCTYPE html>
<html>
<?php
include "db/bootstrap.php";
include "db/functions.php";
session_start();
if(empty($_SESSION['csrf_token'])){
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$books = getBooks($pdo);
$borrowers = getBorrowers($pdo);
$activeLoans = getActiveLoans($pdo);
$lateLoans = getLateLoans($pdo);
?>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Bücherei Verwaltung</title>
</head>
<body>
<h1>Bücherei Verwaltung</h1>
<br>
<table>
<td>
<h2>Neues Buch hinzufügen</h2>
<form id="bookForm">
<label>Titel
<br>
<input type="text" name="title" required>
</label>
<br>
<br>
<label>Autor
<br>
<input type="text" name="author" required>
</label>
<br>
<br>
<label>Lernfeld
<br>
<input type="text" name="area" required>
</label>
<input type="hidden" name="submissionType" value="book">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<br>
<br>
<button type="submit">Buch hinzufügen</button>
</form>
</td>
<td>
<h2>Neue Exemplare hinzufügen</h2>
<form id="copyForm">
<label>Buch
<br>
<select name="book" required>
<option value="">Wähle ein Buch</option>
<?php foreach ($books as $book): ?>
<option value="<?= htmlspecialchars($book['bookID'])?>">
<?= htmlspecialchars($book['title'] . " by " . $book['author'])?>
</option>
<?php endforeach; ?>
</select>
</label>
<br>
<br>
<label>Anzahl
<br>
<input type="number" name="amount" value="1" required>
</label>
<br>
<br>
<label>Zustand
<br>
<input type="text" name="condition" required>
</label>
<input type="hidden" name="submissionType" value="copy">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<br>
<br>
<button type="submit">Exemplare hinzufügen</button>
</form>
</td>
<td>
<h2>Ausleiher hinzufügen</h2>
<form id="borrowerForm">
<label>Vorname
<br>
<input type="name" name="firstname" required>
</label>
<br>
<br>
<label>Nachname
<br>
<input type="name" name="lastname" required>
</label>
<br>
<br>
<label>Klasse/Funktion
<br>
<input type="text" name="role" required>
</label>
<input type="hidden" name="submissionType" value="borrower">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<br>
<br>
<button type="submit">Ausleiher hinzufügen</button>
</form>
</td>
<td>
<h2>Buch verleihen</h2>
<form id="loanForm">
<label>Ausleiher
<br>
<select name="borrowerID" required>
<option value="">Wähle einen Ausleiher</option>
<?php foreach ($borrowers as $borrower): ?>
<option value="<?= htmlspecialchars($borrower['borrowerID'])?>">
<?= htmlspecialchars($borrower['lastName'] . ", " . $borrower['firstName'] . " (" . $borrower['role'] . ")")?>
</option>
<?php endforeach; ?>
</select>
</label>
<br>
<br>
<label>Buch
<br>
<select id="bookSelect" name="book" required>
<option value="">Wähle ein Buch</option>
<?php foreach ($books as $book): ?>
<option value="<?= htmlspecialchars($book['bookID'])?>">
<?= htmlspecialchars($book['title'] . " von " . $book['author'])?>
</option>
<?php endforeach; ?>
</select>
</label>
<br>
<br>
<label>Exemplar
<br>
<select id="copySelect" name="copyID">
<option value="">Bitte zuerst ein Buch wählen</option>
</select>
</label>
<br>
<br>
<label>Ausleihdatum
<br>
<input type="date" name="borrowedDate" value="<?=date("Y-m-d");?>">
</label>
<br>
<br>
<label>Rückgabedatum
<br>
<input type="date" name="dueDate" value="<?=date_add(date_create(date('Y-m-d')), date_interval_create_from_date_string('14 days'))->format('Y-m-d');?>">
</label>
<input type="hidden" name="submissionType" value="loan">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<br>
<br>
<button type="submit">Buch verleihen</button>
</form>
</td>
<td>
<h2>Buch einsammeln</h2>
<form id="checkInForm">
<label>Ausleiher wählen
<br>
<select id="borrowerSelect">
<option value="">Wähle einen Ausleiher</option>
<?php foreach ($borrowers as $borrower): ?>
<option value="<?= htmlspecialchars($borrower['borrowerID'])?>">
<?= htmlspecialchars($borrower['firstName'] . " " . $borrower['lastName'])?>
</option>
<?php endforeach; ?>
</select>
</label>
<br>
<br>
<label>Wähle ein Exemplar
<br>
<select id="copyReturnSelect" name="copyID-loanID">
<option>Bitte zuerst einen Ausleiher wählen</option>
</select>
</label>
<br>
<br>
<label>Zurückgegeben am
<br>
<input type="date" name="returnedDate" value=<?= date("Y-m-d") ?>>
</label>
<br>
<br>
<button type="submit">Buch einsammeln</button>
<input type="hidden" name="submissionType" value="return">
<input type="hidden" name="csrf_token" value=<?= $_SESSION['csrf_token'] ?>>
</form>
</td>
<table>
<td>
<h2>Verliehene Bücher</h2>
<table>
<th>Vorname</th><th>Nachname</th><th>Klasse/Funktion</th><th>Buch</th><th>Exemplar</th><th>Ausleihdatum</th><th>Rückgabe fällig</th>
<?php foreach ($activeLoans as $loan): ?>
<tr>
<td><?= htmlspecialchars($loan['firstName'])?></td>
<td><?= htmlspecialchars($loan['lastName'])?></td>
<td><?= htmlspecialchars($loan['borrowerRole'])?></td>
<td><?= htmlspecialchars($loan['bookTitle'])?></td>
<td>#<?= htmlspecialchars($loan['copyID'])?></td>
<td><?= date_create($loan['borrowedDate'])->format("d.m.Y")?></td>
<td><?= date_create($loan['dueDate'])->format("d.m.Y")?></td>
</tr>
<?php endforeach; ?>
</table>
</td>
<td>
<h2>Versäumte Rückgaben</h2>
<table>
<th>Vorname</th><th>Nachname</th><th>Klasse/Funktion</th><th>Buch</th><th>Exemplar</th><th>Ausleihdatum</th><th>Rückgabe fällig</th>
<?php foreach ($lateLoans as $lateLoan): ?>
<tr>
<td><?= htmlspecialchars($lateLoan['firstName'])?></td>
<td><?= htmlspecialchars($lateLoan['lastName'])?></td>
<td><?= htmlspecialchars($lateLoan['borrowerRole'])?></td>
<td><?= htmlspecialchars($lateLoan['bookTitle'])?></td>
<td>#<?= htmlspecialchars($lateLoan['copyID'])?></td>
<td><?= date_create($lateLoan['borrowedDate'])->format("d.m.Y")?></td>
<td><?= date_create($lateLoan['dueDate'])->format("d.m.Y")?></td>
</tr>
<?php endforeach; ?>
</table>
</td>
</table>
<table>
<td>
<h2>Datenbank durchsuchen</h2>
<form id="sqlSelectInputForm">
<label>
SELECT <input style="width: 500px;" type="text" name="sqlSelectTextarea" placeholder="* FROM books WHERE bookID = 5" required></input>
</label>
<input type="hidden" name="submissionType" value="selectRequest">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<br>
<br>
<button type="submit">Abschicken</button>
</form>
</td>
</table>
</table>
<br>
<div id="result"></div>
<script>
document.getElementById('bookForm').addEventListener('submit', function(e) {
e.preventDefault(); // prevent normal form submission
const formData = new FormData(this);
fetch('submission.php', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('result').innerHTML = data; // show success/error
this.reset(); // reset form after success
})
.catch(error => {
document.getElementById('result').innerHTML = 'Error: ' + error;
});
});
document.getElementById('copyForm').addEventListener('submit', function(e) {
e.preventDefault(); // prevent normal form submission
const formData = new FormData(this);
fetch('submission.php', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('result').innerHTML = data; // show success/error
this.reset(); // optional: reset form after success
})
.catch(error => {
document.getElementById('result').innerHTML = 'Error: ' + error;
});
});
document.getElementById('borrowerForm').addEventListener('submit', function(e) {
e.preventDefault(); // prevent normal form submission
const formData = new FormData(this);
fetch('submission.php', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('result').innerHTML = data; // show success/error
this.reset(); // optional: reset form after success
})
.catch(error => {
document.getElementById('result').innerHTML = 'Error: ' + error;
});
});
document.getElementById('loanForm').addEventListener('submit', function(e) {
e.preventDefault(); // prevent normal form submission
const formData = new FormData(this);
fetch('submission.php', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('result').innerHTML = data; // show success/error
this.reset(); // optional: reset form after success
})
.catch(error => {
document.getElementById('result').innerHTML = 'Error: ' + error;
});
location.reload();
});
document.getElementById('checkInForm').addEventListener('submit', function(e) {
e.preventDefault(); // prevent normal form submission
const formData = new FormData(this);
fetch('submission.php', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('result').innerHTML = data; // show success/error
this.reset(); // optional: reset form after success
})
.catch(error => {
document.getElementById('result').innerHTML = 'Error: ' + error;
});
location.reload();
});
document.getElementById('sqlSelectInputForm').addEventListener('submit', function(e) {
e.preventDefault(); // prevent normal form submission
const formData = new FormData(this);
fetch('submission.php', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
const container = document.getElementById('result');
container.innerHTML = data; // show success/error
this.reset(); // optional: reset form after success
// scroll after the new content is in place
if (container) {
container.scrollIntoView({behavior: 'smooth'});
}
})
.catch(error => {
document.getElementById('result').innerHTML = 'Error: ' + error;
});
});
document.querySelector("#bookSelect").addEventListener("change", function() {
const csrf_token = "<?= $_SESSION['csrf_token'] ?>";
const bookID = this.value;
const copySelect = document.querySelector("#copySelect");
// reset exemplar list
copySelect.innerHTML = '<option value="">Lade Exemplare...</option>';
if (bookID) {
fetch("submission.php?submissionType=" + encodeURI("getCopies") + "&bookID=" + encodeURIComponent(bookID) + "&csrf_token=" + encodeURIComponent(csrf_token))
.then(response => response.json())
.then(copies => {
copySelect.innerHTML = "";
if (copies.length === 0) {
copySelect.innerHTML = '<option value="">Keine Exemplare verfügbar</option>';
} else {
copies.forEach(copy => {
const opt = document.createElement("option");
opt.value = copy.copyID;
opt.textContent = "Exemplar #" + copy.copyID + " (" + copy.bookCondition + ")";
copySelect.appendChild(opt);
});
}
})
.catch(err => {
copySelect.innerHTML = '<option value="">Fehler beim Laden</option>';
console.error(err);
});
} else {
copySelect.innerHTML = '<option value="">Bitte zuerst ein Buch wählen</option>';
}
});
document.querySelector("#borrowerSelect").addEventListener("change", function() {
const csrf_token = "<?= $_SESSION['csrf_token'] ?>";
const borrowerID = this.value;
const copySelect = document.querySelector("#copyReturnSelect");
// reset copy list
copySelect.innerHTML = '<option value="">Lade Exemplare...</option>';
if (borrowerID) {
fetch("submission.php?submissionType=" + encodeURI("getReturnCopies") + "&borrowerID=" + encodeURIComponent(borrowerID) + "&csrf_token=" + encodeURIComponent(csrf_token))
.then(response => response.json())
.then(copies => {
copySelect.innerHTML = "";
if (copies.length === 0) {
copySelect.innerHTML = '<option value="">Keine Exemplare ausgeliehen</option>';
} else {
copies.forEach(copy => {
const opt = document.createElement("option");
opt.value = copy.copyID + "-" + copy.loanID;
opt.textContent = copy.bookTitle + " von " + copy.bookAuthor + " Exemplar #" + copy.copyID + " (" + copy.bookCondition + ")";
copySelect.appendChild(opt);
});
}
})
.catch(err => {
copySelect.innerHTML = '<option value="">Fehler beim Laden</option>';
console.error(err);
});
} else {
copySelect.innerHTML = '<option value="">Bitte zuerst einen Ausleiher wählen</option>';
}
});
</script>
</body>
</html>

9
style.css Normal file
View file

@ -0,0 +1,9 @@
*{
font-family: arial;
}
td, th{
border: 1px solid black;
vertical-align: top;
padding: 10px;
}

126
submission.php Normal file
View file

@ -0,0 +1,126 @@
<?php
include "db/bootstrap.php";
include "db/functions.php";
session_start();
if(empty($_SESSION['csrf_token'])){
die("Invalid request: No token supplied.");
}
$sessionToken = (string)($_SESSION['csrf_token'] ?? '');
$postToken = (string)($_POST['csrf_token'] ?? '');
$getToken = (string)($_GET['csrf_token'] ?? '');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if(!hash_equals($sessionToken, $postToken)){
die("Invalid request: Token mismatch.");
}
//Book Submission
if($_POST['submissionType'] == "book"){
$title = $_POST['title'] ?? '';
$author = $_POST['author'] ?? '';
$area = $_POST['area'] ?? '';
if ($title && $author && $area) {
addBook($pdo, $title, $author, $area);
} else {
echo "<p>Please fill in all fields.</p>";
}
}
//Copy Submission
if($_POST['submissionType'] == "copy"){
$bookID = $_POST['book'] ?? '';
$amount = $_POST['amount'] ?? '';
$copyCondition = $_POST['condition'] ?? '';
if ($bookID && $amount && $copyCondition) {
addCopies($pdo, $bookID, $amount, $copyCondition);
} else {
echo "<p>Please fill in all fields.</p>";
}
}
//Borrower Submission
if($_POST['submissionType'] == "borrower"){
$firstname = $_POST['firstname'] ?? '';
$lastname = $_POST['lastname'] ?? '';
$role = $_POST['role'] ?? '';
if($firstname && $lastname && $role){
addBorrower($pdo, $firstname, $lastname, $role);
}else{
echo "<p>Please fill in all fields.</p>";
}
}
if($_POST['submissionType'] == "loan"){
$copyID = $_POST['copyID'] ?? '';
$borrowerID = $_POST['borrowerID'] ?? '';
$borrowedDate = $_POST['borrowedDate'] ?? '';
$dueDate = $_POST['dueDate'];
if($copyID && $borrowerID && $borrowedDate && $dueDate){
addLoan($pdo, $copyID, $borrowerID, $borrowedDate, $dueDate);
}else{
echo "<p>Please fill in all fields.</p>";
}
}
if($_POST['submissionType'] == "return"){
$copyIDLoanID = explode("-", $_POST['copyID-loanID'], 2);
$copyID = $copyIDLoanID[0];
$loanID = $copyIDLoanID[1];
$returnedDate = $_POST['returnedDate'];
if($copyID && $loanID){
removeLoan($pdo, $copyID, $loanID, $returnedDate);
}else{
echo "<p>Please fill in all fields</p>";
}
}
if($_POST['submissionType'] == "selectRequest"){
$selectRequest = $_POST['sqlSelectTextarea'];
if($selectRequest){
selectRequest($pdo, $selectRequest);
}else{
echo "<p>Please fill in all fields</p>";
}
}
}
if($_SERVER['REQUEST_METHOD'] == 'GET'){
if(!hash_equals($sessionToken, $getToken)){
die("Invalid request: Token mismatch.");
}
if($_GET['submissionType'] == "getCopies"){
$bookID = $_GET['bookID'];
if($bookID){
$copies = getAvailableCopiesOfBook($pdo, $bookID);
echo json_encode($copies);
}else{
echo json_encode([]);
}
}
if($_GET['submissionType'] == "getReturnCopies"){
$borrowerID = $_GET['borrowerID'];
if($borrowerID){
$copies = getBorrowedCopiesOfBorrower($pdo, $borrowerID);
echo json_encode($copies);
}else{
echo json_encode([]);
}
}
}
?>