← CAPE IT library  ·  Keys, ERDs & building the database  ·  Next: Sweet Escape Goes Live

STUDENT
CAPE IT · UNIT 2 · MINI-PRACTICAL · MODULE 1 OBJ. 13 · MODULE 2 OBJ. 10

Book Swap: Your First Database Website

In one lesson you will build a MySQL database yourself in phpMyAdmin, then connect a two-page website to it: a list of books and a form that adds new books.

Form 6 students want to swap their old textbooks. You are building the Book Swap site: anyone can see what books are on offer, and add a book they are willing to swap.

Watch the walkthrough first (6 min)

Every step on real phpMyAdmin and Book Swap screens, with captions. Use the chapters to jump back to a step while you work.

TimeWorkYou will need
About 60–70 minutesIndividually or in pairsA Windows PC with WampServer, a code editor (Notepad++ or VS Code) and the starter kit
⬇ Download the starter kit (.zip)

Hand in

  1. A screenshot of your books table’s Structure tab in phpMyAdmin.
  2. Your three SQL queries from Part B, each with a screenshot of its result.
  3. A screenshot of your website listing your books, including one you added through the form.
  4. Your answers to the five check-up questions at the end.

Part A · Create the database (15 min)

  1. Start WampServer. Wait until its tray icon is green.
  2. Open http://localhost/phpmyadmin. Log in as root with no password and choose the MySQL server.
  3. Click the Databases tab. Under Create database, type bookswap, choose the collation utf8mb4_unicode_ci, and click Create.
  4. phpMyAdmin opens the new database and asks you to create a table. Name it books, set Number of columns to 6, and click Create (or Go).
  5. Fill in the six columns exactly as shown, then click Save.
NameTypeLength/ValuesDefaultNullIndexA_IWhat it stores
book_idINTNonePRIMARY✓A unique number for each book
titleVARCHAR100NoneBook title (required)
authorVARCHAR80NULL✓Author (optional, so Null is ticked)
subjectVARCHAR40Nonee.g. Biology
ownerVARCHAR60NoneStudent lending the book
availableTINYINT1As defined: 11 = available, 0 = swapped

Tips. Ticking A_I (auto increment) on book_id also makes it the PRIMARY key, so MySQL numbers each new book for you. For available, choose As defined under Default and type 1.

Check: open the table’s Structure tab. You should see six columns, a key icon beside book_id, and AUTO_INCREMENT in its Extra column. Take your screenshot.

Part B · Add data and ask questions (10 min)

  1. Click the Insert tab. Add three books of your own. Leave book_id empty, because MySQL numbers it. available is already filled in with 1 (its default), so leave that too. Click Go after each book.
  2. Click Browse to see your rows. Each book should have its own book_id and available = 1.
  3. Open the SQL tab and write a query for each task below. Record each query and screenshot its result.
#Task
1List the title and owner of every book in one subject you entered (e.g. Biology).
2Count how many books there are in each subject.
3Mark one of your books as swapped (set available to 0) using its book_id.

Part C · Connect the website (25 min)

  1. Unzip the starter kit into C:\wamp64\www\, so that you have C:\wamp64\www\bookswap\index.php.
  2. Open http://localhost/bookswap/. The page loads but says 0 book(s) listed. It is connected, but not reading anything yet. (A connection error? Check WAMP is green and the database is named bookswap. If you used MariaDB, change the port in includes/db.php to 3307.)
  3. Open the bookswap folder in your editor and complete the three TODOs.

How the files fit together: includes/db.php opens the connection to MySQL (it is finished; read it). index.php lists the books. add.php shows the form and saves new books. style.css styles both pages.

Two patterns you will need:

// Reading rows: run a query, then fetch every row into an array
$rows = $pdo->query('SELECT title FROM books')->fetchAll();
foreach ($rows as $r) { echo e($r['title']); }

// Using anything the visitor typed: a prepared statement with ? placeholders
$stmt = $pdo->prepare('SELECT * FROM books WHERE owner = ?');
$stmt->execute([$owner]);
TODO 1 · index.php
Read the books from the database, newest first, into $books. If $subject is not empty, only read books for that subject (use a prepared statement).

Hint: copy the reading pattern for the “all books” case, and use ORDER BY book_id DESC for newest first. For a chosen subject, use the prepared-statement pattern with WHERE subject = ?.

TODO 2 · index.php
Print one table row per book in $books. Show title, author, subject and owner (use e() on each), and "Available" or "Swapped" in the last column. Give swapped books the class "swapped".

Hint: use <?php foreach ($books as $b): ?> … <?php endforeach; ?> around one <tr>. Print each value with <?= e($b['title']) ?>.

TODO 3 · add.php
Check the form (title and owner must not be empty; subject must be in $subjects). If it is fine, INSERT the book with a prepared statement and send the visitor to index.php?added=1. Otherwise put a message in $error.

Hint: INSERT INTO books (title, author, subject, owner) VALUES (?, ?, ?, ?), then $stmt->execute([...]). You don’t insert book_id or available, because the database fills them in. After saving, send the visitor back with header('Location: index.php?added=1'); exit;

Part D · Test it (5 min)

#TestExpected✓/✗
1Open the home pageYour three books are listed, newest first, and the swapped one shows “Swapped”
2Add a book with all fields filled in“Your book was added”, and the book appears at the top
3Add a book with no titleAn error message appears and nothing is saved
4Add a book called O’Brien’s NotesSaved and shown correctly (the apostrophe doesn’t break anything)
5Type a subject in the “Show subject” box and press EnterOnly that subject’s books are listed
6Refresh phpMyAdmin’s Browse tabThe books you added through the website are in the table

Extension · Mark a book as swapped

TODO 4 · swap.php
Read book_id from the form (it must be a whole number), then UPDATE that book so available = 0, using a prepared statement.

Then add this button to the last cell of each row in TODO 2, so every available book can be marked as swapped:

<form method="post" action="swap.php" style="display:inline">
  <input type="hidden" name="book_id" value="<?= e($b['book_id']) ?>">
  <button class="small" type="submit">Mark swapped</button>
</form>

Check-up questions

  1. Why is book_id the primary key, and why is it set to AUTO_INCREMENT?
  2. What is the difference between MySQL and phpMyAdmin?
  3. Why does add.php use a prepared statement instead of putting the visitor’s text straight into the SQL?
  4. Why is the connection code kept in one file, includes/db.php, which every page includes?
  5. What do the letters W, A, M and P in WAMP stand for, and what does each one do when you open index.php?

Finished early? Try the full practical, Sweet Escape Goes Live, with a menu, an order form with validation and a staff report.