Webbserverprogrammering 1

Källkod

Välj en PHP-fil för att visa dess källkod.

exercises/index1.php


dbtestforfattare.php
Sida
1
/
1
100 %
<?php

// ===============================
// ANSLUTNING TILL DATABASEN
// ===============================

$host = "localhost";
$dbname = "mindatabas";
$username = "root";
$password = "";

try {
    
$pdo = new PDO(
        
"mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        
$username,
        
$password
    
);

    
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (
PDOException $e) {
    die(
"Kunde inte ansluta till databasen.");
}


// Funktion som skyddar text när den skrivs ut i HTML
function h($text) {
    return 
htmlspecialchars($text, ENT_QUOTES, "UTF-8");
}


// Meddelande som kan visas efter en operation
$message = "";


// ==========================================
// LÄGG TILL FÖRFATTARE
// ==========================================

if (isset($_POST["add_author"])) {

    
$namn = trim($_POST["namn"]);

    if (
$namn !== "") {

        
$sql = "INSERT INTO forfattare (namn)
                VALUES (:namn)"
;

        
$stmt = $pdo->prepare($sql);

        
$stmt->execute([
            
"namn" => $namn
        
]);

        
header("Location: index1.php?message=author_added");
        exit;
    }
}


// ==========================================
// UPPDATERA FÖRFATTARE
// ==========================================

if (isset($_POST["update_author"])) {

    
$id = $_POST["id"];
    
$namn = trim($_POST["namn"]);

    
$sql = "UPDATE forfattare
            SET namn = :namn
            WHERE id = :id"
;

    
$stmt = $pdo->prepare($sql);

    
$stmt->execute([
        
"namn" => $namn,
        
"id" => $id
    
]);

    
header("Location: index1.php?message=author_updated");
    exit;
}


// ==========================================
// TA BORT FÖRFATTARE
// ==========================================

if (isset($_POST["delete_author"])) {

    
$id = $_POST["id"];

    try {

        
$sql = "DELETE FROM forfattare
                WHERE id = :id"
;

        
$stmt = $pdo->prepare($sql);

        
$stmt->execute([
            
"id" => $id
        
]);

        
header("Location: index1.php?message=author_deleted");
        exit;

    } catch (
PDOException $e) {

        
// Om författaren används av en bok kommer FOREIGN KEY
        // normalt att stoppa borttagningen.
        
header("Location: index1.php?message=author_in_use");
        exit;
    }
}


// ==========================================
// LÄGG TILL BOK
// ==========================================

if (isset($_POST["add_book"])) {

    
$titel = trim($_POST["titel"]);
    
$utgivningsar = $_POST["utgivningsar"];
    
$forfattare_id = $_POST["forfattare_id"];

    
$sql = "INSERT INTO bocker
            (titel, utgivningsar, forfattare_id)
            VALUES
            (:titel, :utgivningsar, :forfattare_id)"
;

    
$stmt = $pdo->prepare($sql);

    
$stmt->execute([
        
"titel" => $titel,
        
"utgivningsar" => $utgivningsar,
        
"forfattare_id" => $forfattare_id
    
]);

    
header("Location: index1.php?message=book_added");
    exit;
}


// ==========================================
// UPPDATERA BOK
// ==========================================

if (isset($_POST["update_book"])) {

    
$id = $_POST["id"];
    
$titel = trim($_POST["titel"]);
    
$utgivningsar = $_POST["utgivningsar"];
    
$forfattare_id = $_POST["forfattare_id"];

    
$sql = "UPDATE bocker
            SET titel = :titel,
                utgivningsar = :utgivningsar,
                forfattare_id = :forfattare_id
            WHERE id = :id"
;

    
$stmt = $pdo->prepare($sql);

    
$stmt->execute([
        
"titel" => $titel,
        
"utgivningsar" => $utgivningsar,
        
"forfattare_id" => $forfattare_id,
        
"id" => $id
    
]);

    
header("Location: index1.php?message=book_updated");
    exit;
}


// ==========================================
// TA BORT BOK
// ==========================================

if (isset($_POST["delete_book"])) {

    
$id = $_POST["id"];

    
$sql = "DELETE FROM bocker
            WHERE id = :id"
;

    
$stmt = $pdo->prepare($sql);

    
$stmt->execute([
        
"id" => $id
    
]);

    
header("Location: index1.php?message=book_deleted");
    exit;
}


// ==========================================
// HÄMTA ALLA FÖRFATTARE
// ==========================================

$sql = "SELECT *
        FROM forfattare
        ORDER BY namn"
;

$stmt = $pdo->query($sql);
$authors = $stmt->fetchAll(PDO::FETCH_ASSOC);


// ==========================================
// HÄMTA ALLA BÖCKER + FÖRFATTARNAMN
// ==========================================

$sql = "SELECT
            bocker.id,
            bocker.titel,
            bocker.utgivningsar,
            bocker.forfattare_id,
            forfattare.namn AS forfattare
        FROM bocker
        JOIN forfattare
        ON bocker.forfattare_id = forfattare.id
        ORDER BY bocker.titel"
;

$stmt = $pdo->query($sql);
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);


// ==========================================
// MEDDELANDEN
// ==========================================

if (isset($_GET["message"])) {

    switch (
$_GET["message"]) {

        case 
"book_added":
            
$message = "Boken har lagts till.";
            break;

        case 
"book_updated":
            
$message = "Boken har uppdaterats.";
            break;

        case 
"book_deleted":
            
$message = "Boken har tagits bort.";
            break;

        case 
"author_added":
            
$message = "Författaren har lagts till.";
            break;

        case 
"author_updated":
            
$message = "Författaren har uppdaterats.";
            break;

        case 
"author_deleted":
            
$message = "Författaren har tagits bort.";
            break;

        case 
"author_in_use":
            
$message = "Författaren kan inte tas bort eftersom det finns böcker kopplade till författaren.";
            break;
    }
}

?>

<!DOCTYPE html>
<html lang="sv">

<head>

    <meta charset="UTF-8">

    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">

    <title>Mitt bibliotek</title>

    <style>

        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background: white;
            color: #222;
        }

        header {
            background: #eeeeee;
            padding: 15px;
            margin-bottom: 20px;
        }

        header h1 {
            margin: 0;
        }

        main {
            max-width: 900px;
            margin: auto;
        }

        h2 {
            margin-top: 0;
        }

        .message {
            background: #e8ffe8;
            border: 1px solid #999;
            padding: 10px;
            margin-bottom: 15px;
        }

        .grid {
            display: block;
        }

        .card {
            border: 1px solid #cccccc;
            padding: 15px;
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-top: 10px;
            margin-bottom: 4px;
        }

        input,
        select {
            padding: 5px;
        }

        button {
            padding: 6px;
            margin-top: 8px;
        }

        .primary {
            margin-top: 10px;
        }

        .save {
            background: #eeeeee;
        }

        .delete {
            background: #eeeeee;
        }

        .book {
            padding: 10px;
            border: 1px solid #cccccc;
            margin: 10px 0;
        }

        .book h3 {
            margin-top: 0;
        }

        .book-info {
            color: #555555;
        }

        .edit-row {
            display: block;
            margin-bottom: 10px;
        }

        .author-row {
            margin-bottom: 10px;
        }

        .author-row form {
            display: block;
        }

        .danger-info {
            font-size: 14px;
            color: #555555;
            margin-top: 15px;
        }

        footer {
            margin-top: 25px;
            color: #555555;
        }

    </style>

</head>

<body>

<header>

    <div>

        <h1>Mitt bibliotek</h1>

        <p>
            Här kan jag lägga till och ändra böcker och författare.
        </p>

    </div>

</header>

<main>

    <?php if ($message !== ""): ?>

        <div class="message">
            <?= h($message) ?>
        </div>

    <?php endif; ?>


    <div class="grid">

        <!-- ========================= -->
        <!-- FÖRFATTARE -->
        <!-- ========================= -->

        <section>

            <div class="card">

                <h2>Lägg till författare</h2>

                <form method="post">

                    <label for="namn">
                        Namn
                    </label>

                    <input
                        type="text"
                        id="namn"
                        name="namn"
                        required
                    >

                    <button
                        type="submit"
                        name="add_author"
                        class="primary"
                    >
                        Lägg till
                    </button>

                </form>

            </div>


            <div class="card">

                <h2>Författare</h2>

                <?php foreach ($authors as $author): ?>

                    <div class="author-row">

                        <form method="post">

                            <input
                                type="hidden"
                                name="id"
                                value="<?= $author["id"] ?>"
                            >

                            <input
                                type="text"
                                name="namn"
                                value="<?= h($author["namn"]) ?>"
                            >

                            <button
                                type="submit"
                                name="update_author"
                                class="save"
                            >
                                Spara
                            </button>

                            <button
                                type="submit"
                                name="delete_author"
                                class="delete"
                                onclick="return confirm('Vill du verkligen ta bort författaren?')"
                            >
                                Ta bort
                            </button>

                        </form>

                    </div>

                <?php endforeach; ?>

                <p class="danger-info">
                    En författare som har böcker kan inte tas bort
                    eftersom FOREIGN KEY skyddar relationen.
                </p>

            </div>

        </section>


        <!-- ========================= -->
        <!-- BÖCKER -->
        <!-- ========================= -->

        <section>

            <div class="card">

                <h2>Lägg till bok</h2>

                <form method="post">

                    <label for="titel">
                        Titel
                    </label>

                    <input
                        type="text"
                        id="titel"
                        name="titel"
                        required
                    >


                    <label for="utgivningsar">
                        Utgivningsår
                    </label>

                    <input
                        type="number"
                        id="utgivningsar"
                        name="utgivningsar"
                        required
                    >


                    <label for="forfattare_id">
                        Författare
                    </label>

                    <select
                        id="forfattare_id"
                        name="forfattare_id"
                        required
                    >

                        <?php foreach ($authors as $author): ?>

                            <option value="<?= $author["id"] ?>">
                                <?= h($author["namn"]) ?>
                            </option>

                        <?php endforeach; ?>

                    </select>


                    <button
                        type="submit"
                        name="add_book"
                        class="primary"
                    >
                        Lägg till bok
                    </button>

                </form>

            </div>


            <div class="card">

                <h2>Böcker</h2>

                <div class="books">

                    <?php foreach ($books as $book): ?>

                        <div class="book">

                            <h3>
                                <?= h($book["titel"]) ?>
                            </h3>

                            <div class="book-info">

                                <?= h($book["forfattare"]) ?>

                                ·

                                <?= h($book["utgivningsar"]) ?>

                            </div>


                            <form
                                method="post"
                                class="edit-row"
                            >

                                <input
                                    type="hidden"
                                    name="id"
                                    value="<?= $book["id"] ?>"
                                >


                                <input
                                    type="text"
                                    name="titel"
                                    value="<?= h($book["titel"]) ?>"
                                >


                                <input
                                    type="number"
                                    name="utgivningsar"
                                    value="<?= h($book["utgivningsar"]) ?>"
                                >


                                <select name="forfattare_id">

                                    <?php foreach ($authors as $author): ?>

                                        <option
                                            value="<?= $author["id"] ?>"

                                            <?php
                                            
if ($author["id"] == $book["forfattare_id"]) {
                                                echo 
"selected";
                                            }
                                            
?>
                                        >

                                            <?= h($author["namn"]) ?>

                                        </option>

                                    <?php endforeach; ?>

                                </select>


                                <button
                                    type="submit"
                                    name="update_book"
                                    class="save"
                                >
                                    Spara
                                </button>


                                <button
                                    type="submit"
                                    name="delete_book"
                                    class="delete"
                                    onclick="return confirm('Vill du verkligen ta bort boken?')"
                                >
                                    Ta bort
                                </button>

                            </form>

                        </div>

                    <?php endforeach; ?>

                </div>

            </div>

        </section>

    </div>

</main>


<footer>

    PHP + MySQL – dynamiska webbsidor

</footer>

</body>
</html>
Visar dbtestforfattare.php.