/////////////////////////////////////////////////////////////////////Task 1(a)////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Index.php
<?php include 'view/header.php'; ?>
<main>
    <h1>Menu</h1>
    <ul>
        <li>
            <a href="product_manager">Product Manager Primary Keys</a>
        </li>
        <li>
            <a href="product_catalog">Product Catalog Foreign Keys</a>
        </li>
    </ul>
</main>
<?php include 'view/footer.php'; ?>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Main.css
/* the styles for the HTML elements */
html {
    background-color: rgb(192, 192, 192);
}
body {
    font-family: Arial, Helvetica, sans-serif;
    width: 760px;
    margin: 0 auto;
    padding: 0 2em;
    background-color: white;
    border: 1px solid black;
}
header {
    border-bottom: 2px solid black;
    padding: .5em 0;
}
header h1 {
    color: black;
}
main {

}
aside {
    float: left;
    width: 150px;
}
section {
    float: left;
    width: 500px;
}
footer {
    clear: both;
    border-top: 2px solid black;
}
footer p {
    text-align: right;
    font-size: 80%;
}
h1 {
    font-size: 150%;
    margin: .5em 0;
}
h2 {
    font-size: 120%;
    margin: .25em 0 .5em;
}
h1, h2 {
    color: rgb(208, 133, 4);
}
ul {
    list-style-type: none;
    margin: 0;
    padding-left: 0;
    padding-bottom: 1em;
}
li {
    padding-bottom: 0.5em;
}
a {
    color: rgb(41, 64, 124);
    font-weight: bold;
}
a:hover {
    color: rgb(208, 133, 4);
}
br {
    clear: left;
}
table {
    border: 1px solid black;
    border-collapse: collapse;
    margin-bottom: 1em;
}
td, th {
    border: 1px dashed black;
    padding: .2em .5em .2em .5em;
    text-align: left;
}
form {

}
/* the styles for classes */
.right {
    text-align: right;
}
.first_paragraph {
    margin-top: 0;	
}
.last_paragraph {
    margin-bottom: 2em;	
}
/* the styles for the div tags that divide the page into sections */
#left_column {
    float: left;
    width: 150px;
    text-align: center;
}
#right_column {
    float: left;
    padding-left: 1em;
    padding-bottom: 2em;
}
/* Additional styles for the Product Manager application */
#add_product_form {
    margin: .5em 0;
}
#add_product_form label {
    width: 6em;
    padding-right: 1em;
    padding-bottom: .5em;
    float: left;
}
#add_product_form input {
    float: left;
}
#add_product_form input[text] {
    width: 15em;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
category_nav.php
        <nav>
            <ul>
                <!-- display links for all categories -->
                <?php foreach($categories as $category) : ?>
                <li>
                    <a href="?category_id=<?php 
                              echo $category['categoryID']; ?>">
                        <?php echo $category['categoryName']; ?>
                    </a>
                </li>
                <?php endforeach; ?>
            </ul>
        </nav>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
footer.php
<footer>
    <p class="copyright">
        &copy; <?php echo date('Y'); ?> Task 1a, assignment 4.
    </p>
</footer>
</body>
</html>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
header.php
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
    <title>Task 1a</title>
    <link rel="stylesheet" type="text/css"
          href="/ex_solutions/ch05_ex1_sol/main.css">
</head>

<!-- the body section -->
<body>
<header><h1>Task 1a</h1></header>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Product Manager
category_list.php
<?php include '../view/header.php'; ?>
<main>

    <h1>Category List</h1>
    <table>
        <tr>
            <th>Name</th>
            <th>&nbsp;</th>
        </tr>
        <?php foreach ($categories as $category) : ?>
        <tr>
            <td><?php echo $category['categoryName']; ?></td>
            <td>
                <form action="index.php" method="post">
                    <input type="hidden" name="action" value="delete_category" />
                    <input type="hidden" name="category_id"
                           value="<?php echo $category['categoryID']; ?>"/>
                    <input type="submit" value="Delete"/>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>

    <h2>Add Category</h2>
    <form id="add_category_form"
          action="index.php" method="post">
        <input type="hidden" name="action" value="add_category" />

        <label>Name:</label>
        <input type="text" name="name" />
        <input type="submit" value="Add"/>
    </form>

    <p><a href="index.php?action=list_products">List Products</a></p>

</main>
<?php include '../view/footer.php'; ?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
index.php
<?php
require('../model/database.php');
require('../model/product_db.php');
require('../model/category_db.php');

$action = filter_input(INPUT_POST, 'action');
if ($action == NULL) {
    $action = filter_input(INPUT_GET, 'action');
    if ($action == NULL) {
        $action = 'list_products';
    }
}

if ($action == 'list_products') {
    $category_id = filter_input(INPUT_GET, 'category_id', 
            FILTER_VALIDATE_INT);
    if ($category_id == NULL || $category_id == FALSE) {
        $category_id = 1;
    }
    $category_name = get_category_name($category_id);
    $categories = get_categories();
    $products = get_products_by_category($category_id);
    include('product_list.php');
} else if ($action == 'delete_product') {
    $product_id = filter_input(INPUT_POST, 'product_id', 
            FILTER_VALIDATE_INT);
    $category_id = filter_input(INPUT_POST, 'category_id', 
            FILTER_VALIDATE_INT);
    if ($category_id == NULL || $category_id == FALSE ||
            $product_id == NULL || $product_id == FALSE) {
        $error = "Missing or incorrect product id or category id.";
        include('../errors/error.php');
    } else { 
        delete_product($product_id);
        header("Location: .?category_id=$category_id");
    }
} else if ($action == 'show_add_form') {
    $categories = get_categories();
    include('product_add.php');    
} else if ($action == 'add_product') {
    $category_id = filter_input(INPUT_POST, 'category_id', 
            FILTER_VALIDATE_INT);
    $code = filter_input(INPUT_POST, 'code');
    $name = filter_input(INPUT_POST, 'name');
    $price = filter_input(INPUT_POST, 'price');
    if ($category_id == NULL || $category_id == FALSE || $code == NULL || 
            $name == NULL || $price == NULL || $price == FALSE) {
        $error = "Invalid product data. Check all fields and try again.";
        include('../errors/error.php');
    } else { 
        add_product($category_id, $code, $name, $price);
        header("Location: .?category_id=$category_id");
    }
} else if ($action == 'list_categories') {
    $categories = get_categories();
    include('category_list.php');
} else if ($action == 'add_category') {
    $name = filter_input(INPUT_POST, 'name');

    // Validate inputs
    if ($name == NULL) {
        $error = "Invalid category name. Check name and try again.";
        include('view/error.php');
    } else {
        add_category($name);
        header('Location: .?action=list_categories');  // display the Category List page
    }
} else if ($action == 'delete_category') {
    $category_id = filter_input(INPUT_POST, 'category_id', 
            FILTER_VALIDATE_INT);
    delete_category($category_id);
    header('Location: .?action=list_categories');      // display the Category List page
}
?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<?php include '../view/header.php'; ?>
<main>
    <h1>Add Product</h1>
    <form action="index.php" method="post" id="add_product_form">
        <input type="hidden" name="action" value="add_product">

        <label>Category:</label>
        <select name="category_id">
        <?php foreach ( $categories as $category ) : ?>
            <option value="<?php echo $category['categoryID']; ?>">
                <?php echo $category['categoryName']; ?>
            </option>
        <?php endforeach; ?>
        </select>
        <br>

        <label>Code:</label>
        <input type="text" name="code" />
        <br>

        <label>Name:</label>
        <input type="text" name="name" />
        <br>

        <label>List Price:</label>
        <input type="text" name="price" />
        <br>

        <label>&nbsp;</label>
        <input type="submit" value="Add Product" />
        <br>
    </form>
    <p class="last_paragraph">
        <a href="?action=list_products">View Product List</a>
    </p>

</main>
<?php include '../view/footer.php'; ?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
product_list
<?php include '../view/header.php'; ?>
<main>
    <h1>Product List</h1>

    <aside>
        <!-- display a list of categories -->
        <h2>Categories</h2>
        <?php include '../view/category_nav.php'; ?>
    </aside>

    <section>
        <!-- display a table of products -->
        <h2><?php echo $category_name; ?></h2>
        <table>
            <tr>
                <th>Code</th>
                <th>Name</th>
                <th class="right">Price</th>
                <th>&nbsp;</th>
            </tr>
            <?php foreach ($products as $product) : ?>
            <tr>
                <td><?php echo $product['productCode']; ?></td>
                <td><?php echo $product['productName']; ?></td>
                <td class="right"><?php echo $product['listPrice']; ?></td>
                <td><form action="." method="post">
                    <input type="hidden" name="action"
                           value="delete_product">
                    <input type="hidden" name="product_id"
                           value="<?php echo $product['productID']; ?>">
                    <input type="hidden" name="category_id"
                           value="<?php echo $product['categoryID']; ?>">
                    <input type="submit" value="Delete">
                </form></td>
            </tr>
            <?php endforeach; ?>
        </table>
        <p><a href="index.php?action=show_add_form">Add Product</a></p>
        <p class="last_paragraph"><a href="?action=list_categories">
                List Categories</a>
        </p>        
    </section>
</main>
<?php include '../view/footer.php'; ?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
product_list.php
<?php include '../view/header.php'; ?>
<main>
    <aside>
        <h1>Categories</h1>
        <?php include '../view/category_nav.php'; ?>
    </aside>
    <section>
        <h1><?php echo $category_name; ?></h1>
        <ul class="nav">
            <!-- display links for products in selected category -->
            <?php foreach ($products as $product) : ?>
            <li>
                <a href="?action=view_product&amp;product_id=<?php 
                          echo $product['productID']; ?>">
                    <?php echo $product['productName']; ?>
                </a>
            </li>
            <?php endforeach; ?>
        </ul>
    </section>
</main>
<?php include '../view/footer.php'; ?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
product_view.php
<?php include '../view/header.php'; ?>
<main>
    <aside>
        <h1>Categories</h1>
        <?php include '../view/category_nav.php'; ?>
    </aside>
    <section>
        <h1><?php echo $name; ?></h1>
        <div id="left_column">
            <p>
                <img src="<?php echo $image_filename; ?>"
                    alt="<?php echo $image_alt; ?>" />
            </p>
        </div>

        <div id="right_column">
            <p><b>List Price:</b> $<?php echo $list_price; ?></p>
            <p><b>Discount:</b> <?php echo $discount_percent; ?>%</p>
            <p><b>Your Price:</b> $<?php echo $unit_price_f; ?>
                 (You save $<?php echo $discount_amount_f; ?>)</p>
            <form action="<?php echo '../cart' ?>" method="post">
                <input type="hidden" name="action" value="add">
                <input type="hidden" name="product_id"
                       value="<?php echo $product_id; ?>">
                <b>Quantity:</b>
                <input id="quantity" type="text" name="quantity" 
                       value="1" size="2">
                <br><br>
                <input type="submit" value="Add to Cart">
            </form>
        </div>
    </section>
</main>
<?php include '../view/footer.php'; ?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
category_db.php
<?php
function get_categories() {
    global $db;
    $query = 'SELECT * FROM categories
              ORDER BY categoryID';
    $statement = $db->prepare($query);
    $statement->execute();
    return $statement;    
}

function get_category_name($category_id) {
    global $db;
    $query = 'SELECT * FROM categories
              WHERE categoryID = :category_id';    
    $statement = $db->prepare($query);
    $statement->bindValue(':category_id', $category_id);
    $statement->execute();    
    $category = $statement->fetch();
    $statement->closeCursor();    
    $category_name = $category['categoryName'];
    return $category_name;
}

function add_category($name) {
    global $db;
    $query = 'INSERT INTO categories (categoryName)
              VALUES (:name)';
    $statement = $db->prepare($query);
    $statement->bindValue(':name', $name);
    $statement->execute();
    $statement->closeCursor();    
}

function delete_category($category_id) {
    global $db;
    $query = 'DELETE FROM categories
              WHERE categoryID = :category_id';
    $statement = $db->prepare($query);
    $statement->bindValue(':category_id', $category_id);
    $statement->execute();
    $statement->closeCursor();
}
?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
database.php
<?php
    $dsn = 'mysql:host=localhost;dbname=my_guitar_shop1';
    $username = 'mgs_user';
    $password = 'pa55word';

    try {
        $db = new PDO($dsn, $username, $password);
    } catch (PDOException $e) {
        $error_message = $e->getMessage();
        include('../errors/database_error.php');
        exit();
    }
?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
product_db.php
<?php
function get_products_by_category($category_id) {
    global $db;
    $query = 'SELECT * FROM products
              WHERE products.categoryID = :category_id
              ORDER BY productID';
    $statement = $db->prepare($query);
    $statement->bindValue(':category_id', $category_id);
    $statement->execute();
    $products = $statement->fetchAll();
    $statement->closeCursor();
    return $products;
}

function get_product($product_id) {
    global $db;
    $query = 'SELECT * FROM products
              WHERE productID = :product_id';
    $statement = $db->prepare($query);
    $statement->bindValue(':product_id', $product_id);
    $statement->execute();
    $product = $statement->fetch();
    $statement->closeCursor();
    return $product;
}

function delete_product($product_id) {
    global $db;
    $query = 'DELETE FROM products
              WHERE productID = :product_id';
    $statement = $db->prepare($query);
    $statement->bindValue(':product_id', $product_id);
    $statement->execute();
    $statement->closeCursor();
}

function add_product($category_id, $code, $name, $price) {
    global $db;
    $query = 'INSERT INTO products
                 (categoryID, productCode, productName, listPrice)
              VALUES
                 (:category_id, :code, :name, :price)';
    $statement = $db->prepare($query);
    $statement->bindValue(':category_id', $category_id);
    $statement->bindValue(':code', $code);
    $statement->bindValue(':name', $name);
    $statement->bindValue(':price', $price);
    $statement->execute();
    $statement->closeCursor();
}
?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<?php include '../view/header.php'; ?>
<div id="main">
    <h1>Database Error</h1>
    <p class="first_paragraph">There was an error connecting to the database.</p>
    <p>The database must be installed as described in the appendix.</p>
    <p>MySQL must be running as described in chapter 1.</p>
    <p class="last_paragraph">Error message: <?php echo $error_message; ?></p>
</div><!-- end main -->
<?php include '../view/footer.php'; ?>


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<?php include '../view/header.php'; ?>
<div id="main">
    <h1 class="top">Error</h1>
    <p class="first_paragraph"><?php echo $error; ?></p>
</div>
<?php include '../view/footer.php'; ?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<?php include '../view/header.php'; ?>

<main>
    <h1>Shopping Cart - under construction</h1>
</main>

<?php include '../view/footer.php'; ?>


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
my_guitar_shop1.sql
-- create and select the database
DROP DATABASE IF EXISTS my_guitar_shop1;
CREATE DATABASE my_guitar_shop1;
USE my_guitar_shop1;  -- MySQL command

-- create the tables
CREATE TABLE categories (
  categoryID artistID      INT(11)        NOT NULL   AUTO_INCREMENT,
  categoryName artistName    VARCHAR(255)   NOT NULL,
  PRIMARY KEY (categoryID)
);

CREATE TABLE products (
  productID    albumID    INT(11)        NOT NULL   AUTO_INCREMENT,
  categoryID     artistID  INT(11)        NOT NULL,
  productCode   albumCode   VARCHAR(10)    NOT NULL   UNIQUE,
  productName    albumName  VARCHAR(255)   NOT NULL,
  listPrice      listPrice  DECIMAL(10,2)  NOT NULL,
  PRIMARY KEY (productID)
);

CREATE TABLE orders (
  orderID     trackID   INT(11)        NOT NULL   AUTO_INCREMENT,
  customerID    customerID INT            NOT NULL,
  orderDate     trackDate    DATETIME       NOT NULL,
  PRIMARY KEY (orderID)
);

-- insert data into the database
INSERT INTO categories VALUES
(1, 'HipHop'),
(2, 'House'),
(3, 'Rave');

INSERT INTO products VALUES
(1, 1, 'strat', 'Fender Stratocaster', '699.00'),
(2, 1, 'les_paul', 'Gibson Les Paul', '1199.00'),
(3, 1, 'sg', 'Gibson SG', '2517.00'),
(4, 1, 'fg700s', 'Yamaha FG700S', '489.99'),
(5, 1, 'washburn', 'Washburn D10S', '299.00'),
(6, 1, 'rodriguez', 'Rodriguez Caballero 11', '415.00'),
(7, 2, 'precision', 'Fender Precision', '799.99'),
(8, 2, 'hofner', 'Hofner Icon', '499.99'),
(9, 3, 'ludwig', 'Ludwig 5-piece Drum Set with Cymbals', '699.99'),
(10, 3, 'tama', 'Tama 5-Piece Drum Set with Cymbals', '799.99');

-- create the users
CREATE USER IF NOT EXISTS mgs_user@localhost 
IDENTIFIED BY 'pa55word';

CREATE USER IF NOT EXISTS mgs_tester@localhost 
IDENTIFIED BY 'pa55word';

-- grant privleges to the users
GRANT SELECT, INSERT, DELETE, UPDATE
ON * 
TO mgs_user@localhost;

GRANT SELECT 
ON products
TO mgs_tester@localhost;


/////////////////////////////////////////////////////////////////////Task 1(b)////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
task.sql
-- create and select the database
DROP DATABASE IF EXISTS task;
CREATE DATABASE task;
USE task;  -- MySQL command

-- create the tables
CREATE TABLE modules (
  modulesID       INT(11)        NOT NULL   AUTO_INCREMENT,
  modulesName     VARCHAR(255)   NOT NULL,
  PRIMARY KEY (modulesID)
);

CREATE TABLE lecturer (
  lecturerID        INT(11)        NOT NULL   AUTO_INCREMENT,
  artistID       INT(11)        NOT NULL,
  albumCode      VARCHAR(10)    NOT NULL   UNIQUE,
  albumName      VARCHAR(255)   NOT NULL,
  listPrice        VARCHAR(255)  NOT NULL,
  PRIMARY KEY (lecturerID)
);

CREATE TABLE moderator (
  moderatorID        INT(11)        NOT NULL   AUTO_INCREMENT,
  orderID     INT            NOT NULL,
  moderatorDate      DATETIME       NOT NULL,
  PRIMARY KEY (moderatorID)
);

-- insert data into the database
INSERT INTO modules VALUES
(1, 'modules'),
(2, 'lecturer'),
(3, 'moderator');

INSERT INTO lecturer VALUES
(1, 1, 'strat', 'Fender Stratocaster', '699.00'),
(2, 1, 'les_paul', 'Gibson Les Paul', '1199.00'),
(3, 1, 'sg', 'Gibson SG', '2517.00'),
(4, 1, 'fg700s', 'Yamaha FG700S', '489.99'),
(5, 1, 'washburn', 'Washburn D10S', '299.00'),
(6, 1, 'rodriguez', 'Rodriguez Caballero 11', '415.00'),
(7, 2, 'precision', 'Fender Precision', '799.99'),
(8, 2, 'hofner', 'Hofner Icon', '499.99'),
(9, 3, 'ludwig', 'Ludwig 5-piece Drum Set with Cymbals', '699.99'),
(10, 3, 'tama', 'Tama 5-Piece Drum Set with Cymbals', '799.99');

-- create the users
CREATE USER IF NOT EXISTS mgs_user@localhost 
IDENTIFIED BY 'pa55word';

CREATE USER IF NOT EXISTS mgs_tester@localhost 
IDENTIFIED BY 'pa55word';

-- grant privleges to the users
GRANT SELECT, INSERT, DELETE, UPDATE
ON * 
TO mgs_user@localhost;

GRANT SELECT 
ON lecturer
TO mgs_tester@localhost;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
main.css
html {
    background-color: rgb(192, 192, 192);
}
body {
    font-family: Arial, Helvetica, sans-serif;
    width: 760px;
    margin: 0 auto;
    padding: 0 2em;
    background-color: white;
    border: 1px solid black;
}
header {
    border-bottom: 2px solid black;
    padding: .5em 0;
}
header h1 {
    color: black;
}
main {

}
aside {
    float: left;
    width: 150px;
}
section {
    float: left;
    width: 500px;
}
footer {
    clear: both;
    border-top: 2px solid black;
}
footer p {
    text-align: right;
    font-size: 80%;
}
h1 {
    font-size: 150%;
    margin: 0;
    padding: .5em 0 .25em;
}
h2 {
    font-size: 120%;
    margin: 0;
    padding: .25em 0 .5em;
}
h1, h2 {
    color: rgb(208, 133, 4);
}
ul {
    margin: 0 0 1em 0;
    padding: 0 0 0 2.5em;
}
li {
    margin: 0;
    padding: 0;
}
a {
    color: rgb(41, 64, 124);
    font-weight: bold;
}
a:hover {
    color: rgb(208, 133, 4);
}
form {
    margin: 0;
}
label {
    width: 5em;
    float: left;
    text-align: right;
    margin-right: 1em;
    margin-top: .25em;
    margin-bottom: .75em;
}
table {
    width: 70%;
    border-collapse: collapse;
}
td, th {
    padding: .25em 0;
}
br {
    clear: both;
}

/* the styles for the table header and footer */
#cart_header th {
    border-bottom: 2px solid black;
}
#cart_footer td {
    text-align: right;
    border-top: 2px solid black;
}
/* the styles for the classes */
.right {
    text-align: right;
}
.left {
    text-align: left;
}

.cart_qty {
    text-align: right;
    width: 3em;
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
index.php
<?php
require_once('cart.php');

// Start session management with a persistent cookie
$lifetime = 60 * 60 * 24 * 14;    // 2 weeks in seconds
session_set_cookie_params($lifetime, '/');
session_start();

// Get the cart array from the session
if (empty($_SESSION['cart13'])) {
    $cart = [];
} else {
    $cart = $_SESSION['cart13'];
}

// Create a table of products
$products = [
    '1MMS-1754' => ['name' => 'Anita Primary Lecturer ', 'cost' => '149.50'],
    '1MMS-6289' => ['name' => 'Mashu Secondary Lecturer', 'cost' => '199.50'],
    '1MMS-3408' => ['name' => 'Percival Moderator', 'cost' => '299.50'],
];



// Get the action to perform
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
    $action = filter_input(INPUT_GET, 'action');
    if ($action === NULL) {
        $action = 'show_add_item';
    }
}

// Add or update cart as needed
switch($action) {
    case 'add':
        $key = filter_input(INPUT_POST, 'productkey');
        $quantity = filter_input(INPUT_POST, 'itemqty');
        $product = $products[$key];
        murach\cart\add_item($cart, $key, $quantity, $product);
        $_SESSION['cart13'] = $cart;
        header('Location: .?action=show_cart');
        break;
    case 'update':
        $new_qty_list = filter_input(INPUT_POST, 'newqty', 
                FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
        foreach($new_qty_list as $key => $qty) {
            if ($cart[$key]['qty'] != $qty) {
                murach\cart\update_item($cart, $key, $qty);
            }
        }
        $_SESSION['cart13'] = $cart;
        header('Location: .?action=show_cart');
        break;
    case 'show_cart':
        include('cart_view.php');
        break;
    case 'show_add_item':
        include('add_item_view.php');
        break;
    case 'empty_cart':
        $cart = [];
        $_SESSION['cart13'] = $cart;
        include('cart_view.php');
        break;
}
?>


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cart_view.php
<!DOCTYPE html>
<html>
<head>
    <title>Task 1b</title>
    <link rel="stylesheet" href="main.css">
</head>
<body>
    <header>
            <h1>Task 1b</h1>
    </header>
    <main>
        <h1>Your Cart</h1>
        <?php if (count($cart) == 0) : ?>
            <p>There are no items in your cart.</p>
        <?php else: ?>
            <form action="." method="post">
                <input type="hidden" name="action" value="update">
                <table>
                    <tr id="cart_header">
                        <th class="left">Lecturers Item Menu</th>
                        <th class="right">Item Cost</th>
                        <th class="right">Quantity</th>
                        <th class="right">Item Total</th>
                    </tr>
                <?php foreach($cart as $key => $item) :
                    $cost  = number_format($item['cost'],  0);
                    $total = number_format($item['total'], 0);
                ?>
                    <tr>
                        <td>
                            <?php echo $item['name']; ?>
                        </td>
                        <td class="right">
                            $<?php echo $cost; ?>
                        </td>
                        <td class="right">
                            <input type="text" class="cart_qty"
                                name="newqty[<?php echo $key; ?>]"
                                value="<?php echo $item['qty']; ?>">
                        </td>
                        <td class="right">
                            $<?php echo $total; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                    <tr id="cart_footer">
                        <td colspan="3"><b>Subtotal</b></td>
                        <td>$<?php echo murach\cart\get_subtotal($cart); ?></td>
                    </tr>
                    <tr>
                        <td colspan="4" class="right">
                            <input type="submit" value="Update Cart">
                        </td>
                    </tr>
                </table>
            <p>Click "Update Cart" to update quantities in your
                cart.<br> Enter a quantity of 0 to remove an item.
            </p>
            </form>
        <?php endif; ?>
        <p><a href=".?action=show_add_item">Add Item</a></p>
        <p><a href=".?action=empty_cart">Empty Cart</a></p>
    </main>
</body>
</html>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cart.php
<?php

namespace murach\cart {

    // Add an item to the cart
    function add_item(array &$cart, string $key, int $quantity, array $product) {
        if ($quantity > 0) {
            // If item already exists in cart, update quantity
            if (isset($cart[$key])) {
                $quantity += $cart[$key]['qty'];
                update_item($cart, $key, $quantity);
            } else { 
                // Add item
                $item = [
                    'name' => $product['name'],
                    'cost' => $cost = $product['cost'],
                    'qty'  => $quantity,
                    'total' => $cost = $product['cost'] * $quantity,
                ];
                $cart[$key] = $item;
            }
        }
    }

    // Update an item in the cart
    function update_item(array &$cart, string $key, int $quantity) {
        if (isset($cart[$key])) {
            if ($quantity <= 0) {
                unset($cart[$key]);
            } else {
                $cart[$key]['qty'] = $quantity;
                $total = $cart[$key]['cost'] *
                         $cart[$key]['qty'];
                $cart[$key]['total'] = $total;
            }
        }
    }

    // Get cart subtotal
    function get_subtotal(array $cart, int $decimals = 2) {
        $subtotal = 0;
        foreach ($cart as $item) {
            $subtotal += $item['total'];
        }
        $subtotal_f = number_format($subtotal, $decimals);
        return $subtotal_f;
    }
}
?>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
add_item_view.php
<!DOCTYPE html>
<html>
<head>
    <title>Task 1b</title>
    <link rel="stylesheet" href="main.css">
</head>
<body>
    <header>
        <h1>Task 1b</h1>
    </header>
    <main>
        <h1>Add Item</h1>
        <form action="." method="post" >
            <input type="hidden" name="action" value="add">

            <label>Name:</label>
            <select name="productkey">
            <?php foreach($products as $key => $product) :
                $cost = number_format($product['cost'], 0);
                $name = $product['name'];
                $item = $name . ' (' . $cost . ')';
            ?>
                <option value="<?php echo $key; ?>">
                    <?php echo $item; ?>
                </option>
            <?php endforeach; ?>
            </select><br>

            <label>Moudles Quantity:</label>
            <select name="itemqty">
            <?php for($i = 1; $i <= 10; $i++) : ?>
                <option value="<?php echo $i; ?>">
                    <?php echo $i; ?>
                </option>
            <?php endfor; ?>
            </select><br>

            <label>&nbsp;</label>
            <input type="submit" value="Add Item">
        </form>
        <p><a href=".?action=show_cart">View Cart</a></p>
    </main>
</body>
</html>


/////////////////////////////////////////////////////////////////////Task 2////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
percy.sql
-- create and select the database
DROP DATABASE IF EXISTS percy;
CREATE DATABASE percy;
USE percy;  -- MySQL command

-- create the tables
CREATE TABLE artist (
  artistID       INT(11)        NOT NULL   AUTO_INCREMENT,
  artistName     VARCHAR(255)   NOT NULL,
  PRIMARY KEY (artistID)
);

CREATE TABLE album (
  albumID        INT(11)        NOT NULL   AUTO_INCREMENT,
  artistID       INT(11)        NOT NULL,
  albumCode      VARCHAR(10)    NOT NULL   UNIQUE,
  albumName      VARCHAR(255)   NOT NULL,
  listPrice        DECIMAL(10,2)  NOT NULL,
  PRIMARY KEY (albumID)
);

CREATE TABLE track (
  trackID        INT(11)        NOT NULL   AUTO_INCREMENT,
  customerID     INT            NOT NULL,
  trackDate      DATETIME       NOT NULL,
  PRIMARY KEY (trackID)
);

-- insert data into the database
INSERT INTO artist VALUES
(1, 'artist'),
(2, 'album'),
(3, 'track');

INSERT INTO album VALUES
(1, 1, 'strat', 'Fender Stratocaster', '699.00'),
(2, 1, 'les_paul', 'Gibson Les Paul', '1199.00'),
(3, 1, 'sg', 'Gibson SG', '2517.00'),
(4, 1, 'fg700s', 'Yamaha FG700S', '489.99'),
(5, 1, 'washburn', 'Washburn D10S', '299.00'),
(6, 1, 'rodriguez', 'Rodriguez Caballero 11', '415.00'),
(7, 2, 'precision', 'Fender Precision', '799.99'),
(8, 2, 'hofner', 'Hofner Icon', '499.99'),
(9, 3, 'ludwig', 'Ludwig 5-piece Drum Set with Cymbals', '699.99'),
(10, 3, 'tama', 'Tama 5-Piece Drum Set with Cymbals', '799.99');

-- create the users
CREATE USER IF NOT EXISTS mgs_user@localhost 
IDENTIFIED BY 'pa55word';

CREATE USER IF NOT EXISTS mgs_tester@localhost 
IDENTIFIED BY 'pa55word';

-- grant privleges to the users
GRANT SELECT, INSERT, DELETE, UPDATE
ON * 
TO mgs_user@localhost;

GRANT SELECT 
ON album
TO mgs_tester@localhost;


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
main.css
/* the styles for the html elements */
html {
    background-color: rgb(192, 192, 192);
}
body {
    margin-top: 0;
    font-family: Arial, Helvetica, sans-serif;
    width: 760px;
    margin: 0 auto;
    background-color: white;
    border: 1px solid black;
    padding: .5em 2em;
}
header {
    margin: 0;
    border-bottom: 2px solid black;
}
header h1 {
    margin: 0;
    padding: .5em 0;
    color: black;
}
main {
    margin: 0;
}
aside {
    float: left;
    width: 150px;
}
nav ul {
    list-style-type: none;
    margin-left: 0;
    padding-left: 0;
}
nav ul li {
    padding-bottom: 0.5em;
}
section {
    float: left;
    width: 500px;
    padding-bottom: 1.5em;
}
footer {
    clear: both;
    margin-top: 1em;
    border-top: 2px solid black;
}
footer p {
    text-align: right;
    font-size: 80%;
    margin: 1em 0;
}
h1 {
    font-size: 150%;
    margin: 0;
    padding: .5em 0 .25em;
}
h2 {
    font-size: 120%;
    margin: 0;
    padding: .25em 0 .5em;
}
h1, h2 {
    color: rgb(208, 133, 4);
}
ul {
    margin: 0 0 1em 0;
    padding: 0 0 0 2.5em;
}
li {
    margin: 0;
    padding: 0;
}
a {
    color: rgb(41, 64, 124);
    font-weight: bold;
}
a:hover {
    color: rgb(208, 133, 4);
}
table {
    border: 1px solid black;
    border-collapse: collapse;
}
td, th {
    border: 1px dashed black;
    padding: .2em .5em .2em .5em;
    vertical-align: top;
    text-align: left;
}
form {
    margin: 0;
}
br {
    clear: left;
}
/* the styles for classes */
.right {
    text-align: right;
}
.last_paragraph {
	margin-bottom: 2em;	
}
.margin_top_increase {
	margin-top: 1em;	
}

/********************************************************************
* Additional styles for the Product Manager application
********************************************************************/
#add_product_form {
    margin: .5em 0 1em;
}
#add_product_form label {
    width: 6em;
    padding-right: 1em;
    padding-bottom: .5em;
    float: left;
}
#add_product_form input {
    float: left;
}
#add_product_form input[text] {
    width: 15em;
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
index.php
<?php
require_once('database.php');

// Get category ID
if (!isset($category_id)) {
    $category_id = filter_input(INPUT_GET, 'category_id', 
            FILTER_VALIDATE_INT);
    if ($category_id == NULL || $category_id == FALSE) {
        $category_id = 1;
    }
}
// Get name for selected category
$queryCategory = 'SELECT * FROM artist
                  WHERE artistID = :category_id';
$statement1 = $db->prepare($queryCategory);
$statement1->bindValue(':category_id', $category_id);
$statement1->execute();
$category = $statement1->fetch();
$category_name = $category['artistName'];
$statement1->closeCursor();


// Get all categories
$query = 'SELECT * FROM artist
          ORDER BY artistID';
$statement = $db->prepare($query);
$statement->execute();
$categories = $statement->fetchAll();
$statement->closeCursor();

// Get album for selected category
$queryProducts = 'SELECT * FROM album
                  WHERE artistID = :category_id
                  ORDER BY albumID';
$statement3 = $db->prepare($queryProducts);
$statement3->bindValue(':category_id', $category_id);
$statement3->execute();
$album = $statement3->fetchAll();
$statement3->closeCursor();
?>
<!DOCTYPE html>
<html>

<!-- the head section -->
<head>
    <title>Task 2</title>
    <link rel="stylesheet" href="main.css" />
</head>

<!-- the body section -->
<body>
<header><h1>Task 2</h1></header>
<main>
    <h1>Product List</h1>

    <aside>
        <!-- display a list of categories -->
        <h2>Categories</h2>
        <nav>
        <ul>
            <?php foreach ($artist as $category) : ?>
            <li><a href=".?category_id=<?php echo $category['artistID']; ?>">
                    <?php echo $category['artistName']; ?>
                </a>
            </li>
            <?php endforeach; ?>
        </ul>
        </nav>          
    </aside>

    <section>
        <!-- display a table of album -->
        <h2><?php echo $category_name; ?></h2>
        <table>
            <tr>
                <th>Code</th>
                <th>Name</th>
                <th class="right">Price</th>
                <th>&nbsp;</th>
            </tr>

            <?php foreach ($album as $product) : ?>
            <tr>
                <td><?php echo $product['albumCode']; ?></td>
                <td><?php echo $product['albumName']; ?></td>
                <td class="right"><?php echo $product['listPrice']; ?></td>
                <td><form action="delete_product.php" method="post">
                    <input type="hidden" name="product_id"
                           value="<?php echo $product['albumID']; ?>">
                    <input type="hidden" name="category_id"
                           value="<?php echo $product['artistID']; ?>">
                    <input type="submit" value="Delete">
                </form></td>
            </tr>
            <?php endforeach; ?>
        </table>
        <p><a href="add_product_form.php">Add Product</a></p>
        <p><a href="category_list.php">List Categories</a></p>        
    </section>
</main>
<footer>
    <p>&copy; <?php echo date("Y"); ?> Task 2, assignment 4.</p>
</footer>
</body>
</html>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
error.php
<!DOCTYPE html>
<html>

<!-- the head section -->
<head>
    <title>Task 2</title>
    <link rel="stylesheet" href="main.css" />
</head>

<!-- the body section -->
<body>
    <header><h1>Task 2</h1></header>

    <main>
        <h2 class="top">Error</h2>
        <p><?php echo $error; ?></p>
    </main>

    <footer>
        <p>&copy; <?php echo date("Y"); ?> Task 2, assignment 4.</p>
    </footer>
</body>
</html>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
delete_product.php
<?php
require_once('database.php');

// Get IDs
$product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
$category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);

// Delete the product from the database
if ($product_id != FALSE && $category_id != FALSE) {
    $query = 'DELETE FROM album
              WHERE albumID = :product_id';
    $statement = $db->prepare($query);
    $statement->bindValue(':product_id', $product_id);
    $success = $statement->execute();
    $statement->closeCursor();    
}

// Display the Product List page
include('index.php');

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<?php
// Get ID
$category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);

// Validate inputs
if ($category_id == NULL || $category_id == FALSE) {
    $error = "Invalid category ID.";
    include('error.php');
} else {
    require_once('database.php');

    // Add the product to the database  
    $query = 'DELETE FROM artist 
              WHERE artistID = :category_id';
    $statement = $db->prepare($query);
    $statement->bindValue(':category_id', $category_id);
    $statement->execute();
    $statement->closeCursor();

    // Display the Category List page
    include('category_list.php');
}
?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
delete_error.php
<!DOCTYPE html>
<html>

<!-- the head section -->
<head>
    <title>Task 1</title>
    <link rel="stylesheet" href="main.css" />
</head>

<!-- the body section -->
<body>
    <header><h1>Task 1</h1></header>

    <main>
        <h1>Database Error</h1>
        <p>There was an error connecting to the database.</p>
        <p>The database must be installed as described in the appendix.</p>
        <p>MySQL must be running as described in chapter 1.</p>
        <p>Error message: <?php echo $error_message; ?></p>
        <p>&nbsp;</p>
    </main>

    <footer>
        <p>&copy; <?php echo date("Y"); ?> Task 2, assignment 4.</p>
    </footer>
</body>
</html>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
database.php
<?php
    $dsn = 'mysql:host=localhost;dbname=percy';
    $username = 'mgs_user';
    $password = 'pa55word';

    try {
        $db = new PDO($dsn, $username, $password);
    } catch (PDOException $e) {
        $error_message = $e->getMessage();
        include('database_error.php');
        exit();
    }
?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
category_list.php
<?php
require_once('database.php');

// Get all artist
$query = 'SELECT * FROM artist
          ORDER BY artistID';
$statement = $db->prepare($query);
$statement->execute();
$artist = $statement->fetchAll();
$statement->closeCursor();
?>
<!DOCTYPE html>
<html>

<!-- the head section -->
<head>
    <title>Task 2</title>
    <link rel="stylesheet" href="main.css" />
</head>

<!-- the body section -->
<body>
<header><h1>Task 2</h1></header>
<main>
    <h1>Category List</h1>
    <table>
        <tr>
            <th>Name</th>
            <th>&nbsp;</th>
        </tr>        
        <?php foreach ($artist as $category) : ?>
        <tr>
            <td><?php echo $category['artistName']; ?></td>
            <td>
                <form action="delete_category.php" method="post">
                    <input type="hidden" name="category_id"
                           value="<?php echo $category['artistID']; ?>"/>
                    <input type="submit" value="Delete"/>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>    
    </table>

    <h2 class="margin_top_increase">Add Category</h2>
    <form action="add_category.php" method="post"
          id="add_category_form">

        <label>Name:</label>
        <input type="text" name="name" />
        <input id="add_category_button" type="submit" value="Add"/>
    </form>
    
    <p><a href="index.php">List Products</a></p>

</main>
<footer>
    <p>&copy; <?php echo date("Y"); ?> Task 2, assignment 4.</p>
</footer>
</body>
</html>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
add_product_form.php
<?php
require('database.php');
$query = 'SELECT *
          FROM artist
          ORDER BY artistID';
$statement = $db->prepare($query);
$statement->execute();
$artist = $statement->fetchAll();
$statement->closeCursor();
?>
<!DOCTYPE html>
<html>

<!-- the head section -->
<head>
    <title>Task 2</title>
    <link rel="stylesheet" href="main.css">
</head>

<!-- the body section -->
<body>
    <header><h1>Task 2</h1></header>

    <main>
        <h1>Add Product</h1>
        <form action="add_product.php" method="post"
              id="add_product_form">

            <label>Category:</label>
            <select name="category_id">
            <?php foreach ($artist as $category) : ?>
                <option value="<?php echo $category['artistID']; ?>">
                    <?php echo $category['artistName']; ?>
                </option>
            <?php endforeach; ?>
            </select><br>

            <label>Code:</label>
            <input type="text" name="code"><br>

            <label>Name:</label>
            <input type="text" name="name"><br>

            <label>List Price:</label>
            <input type="text" name="price"><br>

            <label>&nbsp;</label>
            <input type="submit" value="Add Product"><br>
        </form>
        <p><a href="index.php">View Product List</a></p>
    </main>

    <footer>
        <p>&copy; <?php echo date("Y"); ?> Task 2, assignment 4, Inc.</p>
    </footer>
</body>
</html>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
add_product.php
<?php
// Get the product data
$category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
$code = filter_input(INPUT_POST, 'code');
$name = filter_input(INPUT_POST, 'name');
$price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);

// Validate inputs
if ($category_id == NULL || $category_id == FALSE || $code == NULL || 
        $name == NULL || $price == NULL || $price == FALSE) {
    $error = "Invalid product data. Check all fields and try again.";
    include('error.php');
} else {
    require_once('database.php');

    // Add the product to the database  
    $query = 'INSERT INTO track
                 (artistID, albumCode, albumName, listPrice)
              VALUES
                 (:category_id, :code, :name, :price)';
    $statement = $db->prepare($query);
    $statement->bindValue(':category_id', $category_id);
    $statement->bindValue(':code', $code);
    $statement->bindValue(':name', $name);
    $statement->bindValue(':price', $price);
    $statement->execute();
    $statement->closeCursor();

    // Display the Product List page
    include('index.php');
}
?>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
add_category.php
<?php
// Get the category data
$name = filter_input(INPUT_POST, 'name');

// Validate inputs
if ($name == NULL) {
    $error = "Invalid category data. Check all fields and try again.";
    include('error.php');
} else {
    require_once('database.php');

    // Add the product to the database  
    $query = 'INSERT INTO artist (artistName)
              VALUES (:category_name)';
    $statement = $db->prepare($query);
    $statement->bindValue(':category_name', $name);
    $statement->execute();
    $statement->closeCursor();

    // Display the Category List page
    include('category_list.php');
}
?>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
newfolder
index.php
 <?php
 require 'database.php';
 // Get category ID
 $category_id = $_GET['category_id']; 
if (!isset($category_id)) {
 $category_id = 1;
 }
 // Get name for current category 
$query = "SELECT * FROH artist
 WHERE artistID = $category_id";
 $category = $db->query($query);
 $category = $category->fetch();
 $category_name = $category['artistName'];
 // Get all artist 
$query = 'SELECT * FROM artist 
ORDER BY artistID';
 $artist = $db->query($query);
 // Get album for selected category 
$query = "SELECT * FROH album
 WHERE artistID = $category_id 
ORDER BY albumID";
 $album = $db->query($query);
 ?>
<!D0CTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns = "ht tp://www.w3.org/1999/xhtml">
 <!-- the head section -->
 <head>
 <title>Task 2</title>
 <link rel="stylesheet" type="text/css" href="main.css" /> 
</head>
 <!-- the body section -->
 <body>
 <div id="page">
 <div id="main">
 <hl>Product List</hl>
 <div id="sidebar">
 <!-- display a list of artist -->
 <h2>Categories</h2>
 <ul class="nav">
 <?php foreach ($artist as $category) : ?>
 <li>
 <a href="?category_id=<?php echo $category['artistID']; ?>"> 
<?php echo $category['artistName']; ?>
 </a>
 </li>
 <?php endforeach; ?>
 </ul>
 </div>
 <div id="content">
 <!-- display a table of album -->
 <h2><?php echo $category_name; ?></h2>
 <table>
 <tr>
 <th>Code</th>
 <th>Name</th>
 <th class="right">Price</th>
 </tr>
 <?php foreach ($album as $product) : ?>
 <tr>
 <td><?php echo $product ['albumCode'] ; ?></td>
 <td><?php echo $product ['albumName'] ; ?></td>
 <td class="right"><?php echo Sproduct ['listPrice'] ; ?></td> 
</tr>
 <?php endforeach; ?>
 </table>
 </div>
 </div><!-- end main -->
 <div id=" footer">
  <p>&copy; <?php echo date("Yn); ?> Task 2, assignment 4.</p> 
 </div>
 </div><!-- end page - ->
 </body>
 </html>
 
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 delete_product.php
  <?php
 // Get IDs
 $product_id = $_POST[1product_id1];
 $category_ld = $_POST[1category_id1];
 // Delete the product from the database 
require_once(1 database.php1);
 $query = "DELETE FROM album
 WHERE productID = 1$product_id1";
 $db->exec($query);
 // Display the Product List page 
Include(1 Index.php1);
 ?>
 
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 database_error.php
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns = "ht tp://www.w3.org/19 9 9/xhtml">
 <!-- the head section -->
 <head>
 <title>Task 2</title>
 <link rel="stylesheet" type="text/css" href="main.css" />
 </head>
 <!-- the body section -->
 <body>
 <div id="page">
 <div id="main">
 <hl>Database Error</hl>
 <p>There was an error connecting to the database.</p>
 <p>The database must be installed as described in appendix A.</p> 
<p>The database must be running as described in chapter l.</p> 
<p>Error message: <?php echo $error_message; ?></p>
 </div>
 </div><!-- end page -->
 </body>
 </html>
 
 
 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 database.php
 <?php
 $dsn = 'mysql:host=localhost;dbname=percy'; 
$username = 'mgs_user';
 $password = 'pa55word';
 try {
 $db = new PDO($dsn, $username, $password);
 } catch (PDOException $e) {
 $error_message = $e->getMessage(); 
include('database_error.php'); 
exit() ;
 }
 
 ?>
 
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 add_product_form.php
  <?php
 requireonce(1 database.php1);
 $query = 'SELECT *
 FROH artist 
ORDER BY artistID';
 $artist = $db->query($query);
 ?>
 How to use PHP with MySQL 
<!D0CTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtmll/DTD/xhtmll-transitional.dtd"> 
chtml xmlns="ht tp://www.w3.org/19 9 9/xhtml">
 <!-- the head section -->
 <head>
 <title>Task 2</title>
 clink rel="stylesheet" type="text/css" href="main.css" />
 </head>
 <!-- the body section -->
 <body>
 <div id="page">
 <div id="header">
 <hl>Product Manager</hl>
 </div>
 <div id="main">
 <hl>Add Product</hl>
 <form action="add_product.php" method="post" 
id="add_product_form" >
 <label>Category:</label>
 <select name="category_id">
 <?php foreach ($artist as $category) : ?>
 «option value="<?php echo $category['artistID']; ?>"> 
<?php echo $category['artistName'] ; ?>
 </option>
 <?php endforeach; ?>
 </select>
 <br />
  <label>Code:</label>
 cinput type="input" name="code" />
 <br />
 <label>Name:</label>
 <input type="input" name="name" />
 <br />
 <label>List Price:</label>
 <input type="input" name="price" />
 <br />
 How to use PHP with MySQL 
<label>&nbsp;</label>
 <input type="submit" value="Add Product" />
 <br />
 </form>
 <pxa href="index.php">View Product List</ax/p>
 </div><!-- end main -->
 <div id="footer">
 <p>&copy; <?php echo date("Y"); ?> Task 2, assignment 4.</p> 
</div>
 </div><!-- end page -->
 </body>
 </html>
 
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 add_product.php
  <?php
 // Get the product data 
$category_id = $_POST['category_id'];
 $code = $_POST['code'];
 $name = $_POST['name'];
 $price = $_POST['price'];
 
 // Validate inputs
 if (empty($code) || empty($name) || empty($price) ) {
 $error = "Invalid product data. Check all fields and try again."; 
include('error.php');
 } else {
 // If valid, add the product to the database 
reguire_once('database.php');
 $query = "INSERT INTO album
 (artistID, albumCode, albumName, listPrice) 
VALUES
 ('$category_id', '$code', '$name', '$price')"; 
$db->exec($query);
 // Display the Product List page 
include('index.php');
 }
 ?>
 
 /////////////////////////////////////////////////////////////////////Task 3(a)////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 uploadform.php
 <!DOCTYPE html>
<html>
<head>
    <title>Upload Image</title>
    <link rel="stylesheet" href="main.css"/>
</head>
<body>
    <header>
        <h1>Upload Image</h1>
    </header>
    <main>
        <h2>Images to be uploaded</h2>
        <form id="upload_form"
              action="." method="POST"
              enctype="multipart/form-data">
            <input type="hidden" name="action" value="upload">
            <input type="file" name="file1"><br>
            <input type="file" name="file2"><br>
            <input type="file" name="file3"><br>
            <input id="upload_button" type="submit" value="Upload">
        </form>
        <h2>Images in the directory</h2>
        <?php if (count($files) == 0) : ?>
            <p>No images uploaded.</p>
        <?php else: ?>
            <ul>
            <?php foreach($files as $filename) :
                $file_url = $image_dir . '/' . $filename;
                $delete_url = '.?action=delete&amp;filename=' .
                              urlencode($filename);
            ?>
                <li>
                    <a href="<?php echo $delete_url;?>">
                        <img src="delete.png" alt="Delete"></a>
                    <a href="<?php echo $file_url; ?>">
                        <?php echo $filename; ?></a>
                </li>
            <?php endforeach; ?>
            </ul>
        <?php endif; ?>
    </main>
</body>
</html>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
main.css
/* the styles for the HTML elements */
html {
    background-color: rgb(192, 192, 192);
}
body {
    font-family: Arial, Helvetica, sans-serif;
    width: 760px;
    margin: 0 auto;
    padding: 0 2em;
    background-color: white;
    border: 1px solid black;
}
header {
    border-bottom: 2px solid black;
    padding: .5em 0;
}
header h1 {
    color: black;
}
main {
    margin-bottom: 1em;
}
h1 {
    font-size: 150%;
    margin: .5em 0 .25em;
}
h2 {
    font-size: 120%;
    margin: .5em 0;
}
h1, h2 {
    color: rgb(208, 133, 4);
}
a {
    color: rgb(41, 64, 124);
    font-weight: bold;
}
a:hover {
    color: rgb(208, 133, 4);
}
img {
    border: none;
    vertical-align: middle;
}
br {
    clear: left;
}

ul {
    list-style-type: none;
    margin-bottom: 1em;
    padding-left: 0;
}
li {
    margin-bottom: 0.5em;
}

form {
    margin: .25em 0 .5em;
}

#upload_button {
    margin: .5em 0;
}
#upload_form label {
    padding-left: 1em;
    padding-bottom: .5em;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
index.php
<?php
require_once 'file_util.php';  // the get_file_list function
require_once 'image_util.php'; // the process_image function

$image_dir = 'images';
$image_dir_path = getcwd() . DIRECTORY_SEPARATOR . $image_dir;

$action = filter_input(INPUT_POST, 'action');
if ($action == NULL) {
    $action = filter_input(INPUT_GET, 'action');
    if ($action == NULL) {
        $action = '';
    }
}

function upload_file($name) {
    global $image_dir_path;
    if (isset($_FILES[$name])) {
        $filename = $_FILES[$name]['name'];
        if (!empty($filename)) {
            $source = $_FILES[$name]['tmp_name'];
            $target = $image_dir_path . DIRECTORY_SEPARATOR . $filename;
            move_uploaded_file($source, $target);
            // create the '400', '250', and '100' versions of the image
            process_image($image_dir_path, $filename);
        }
    }
}

switch ($action) {
    case 'upload':
        upload_file('file1');
        upload_file('file2');
        upload_file('file3');
        break;
    case 'delete':
        $filename = filter_input(INPUT_GET, 'filename', 
                FILTER_SANITIZE_STRING);
        $target = $image_dir_path . DIRECTORY_SEPARATOR . $filename;
        if (file_exists($target)) {
            unlink($target);
        }
        break;
}

$files = get_file_list($image_dir_path);
include('uploadform.php');
?>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
image_util.php
<?php
function process_image($dir, $filename) {
    // Set up the variables
    $dir = $dir . DIRECTORY_SEPARATOR;
    $i = strrpos($filename, '.');
    $image_name = substr($filename, 0, $i);
    $ext = substr($filename, $i);

    // Set up the read path
    $image_path = $dir . DIRECTORY_SEPARATOR . $filename;

    // Set up the write paths
    $image_path_400 = $dir . $image_name . '_400' . $ext;
    $image_path_250 = $dir . $image_name . '_250' . $ext;
    $image_path_100 = $dir . $image_name . '_100' . $ext;

    // Create an image that's a maximum of 400x300 pixels
    resize_image($image_path, $image_path_400, 400, 300);

    // Create an image that's a maximum of 250x250 pixels
    resize_image($image_path, $image_path_250, 250, 250);

    // Create a thumbnail image that's a maximum of 100x100 pixels
    resize_image($image_path, $image_path_100, 100, 100);
}

/***************
 * Resize image 
 ***************/
function resize_image($old_image_path, $new_image_path,
        $max_width, $max_height) {

    // Get image type
    $image_info = getimagesize($old_image_path);
    $image_type = $image_info[2];

    // Set up the function names
    switch($image_type) {
        case IMAGETYPE_JPEG:
            $image_from_file = 'imagecreatefromjpeg';
            $image_to_file = 'imagejpeg';
            break;
        case IMAGETYPE_GIF:
            $image_from_file = 'imagecreatefromgif';
            $image_to_file = 'imagegif';
            break;
        case IMAGETYPE_PNG:
            $image_from_file = 'imagecreatefrompng';
            $image_to_file = 'imagepng';
            break;
        default:
            echo 'File must be a JPEG, GIF, or PNG image.';
            exit;
    }

    // Get the old image and its height and width
    $old_image = $image_from_file($old_image_path);
    $old_width = imagesx($old_image);
    $old_height = imagesy($old_image);

    // Calculate height and width ratios
    $width_ratio = $old_width / $max_width;
    $height_ratio = $old_height / $max_height;

    // If image is larger than specified ratio, create the new image
    if ($width_ratio > 1 || $height_ratio > 1) {

        // Calculate height and width for the new image
        $ratio = max($width_ratio, $height_ratio);
        $new_height = round($old_height / $ratio);
        $new_width = round($old_width / $ratio);

        // Create the new image
        $new_image = imagecreatetruecolor($new_width, $new_height);

        // Set transparency according to image type
        if ($image_type == IMAGETYPE_GIF) {
            $alpha = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
            imagecolortransparent($new_image, $alpha);
        }
        if ($image_type == IMAGETYPE_PNG || $image_type == IMAGETYPE_GIF) {
            imagealphablending($new_image, false);
            imagesavealpha($new_image, true);
        }

        // Copy old image to new image - this resizes the image
        $new_x = 0;
        $new_y = 0;
        $old_x = 0;
        $old_y = 0;
        imagecopyresampled($new_image, $old_image,
                           $new_x, $new_y, 
                           $old_x, $old_y,
                           $new_width, $new_height, 
                           $old_width, $old_height);

        // Write the new image to a new file
        $image_to_file($new_image, $new_image_path);

        // Free any memory associated with the new image
        imagedestroy($new_image);
    } else {
        // Write the old image to a new file
        $image_to_file($old_image, $new_image_path);
    }
    // Free any memory associated with the old image
    imagedestroy($old_image);
}

?>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
file_util.php
<?php
function get_file_list($path) {
    $files = [];
    
    if (is_dir($path)) {
        $items = scandir($path);
        foreach ($items as $item) {
            $item_path = $path . DIRECTORY_SEPARATOR . $item;
            if (is_file($item_path)) {
                $files[] = $item;
            }
        }
    }
    return $files;
}
?>


/////////////////////////////////////////////////////////////////////Task 3(b)////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
main.css
/* the styles for the HTML elements */
html {
    background-color: rgb(192, 192, 192);
}
body {
    font-family: Arial, Helvetica, sans-serif;
    width: 760px;
    margin: 0 auto;
    padding: 0 2em;
    background-color: white;
    border: 1px solid black;
}
header {
    border-bottom: 2px solid black;
    padding: .5em 0;
}
header h1 {
    color: black;
}
main {

}
aside {
    float: left;
    width: 150px;
}
section {
    float: left;
    width: 500px;
}
footer {
    clear: both;
    border-top: 2px solid black;
}
footer p {
    text-align: right;
    font-size: 80%;
}
h1 {
    font-size: 150%;
    margin: .5em 0;
}
h2 {
    font-size: 120%;
    margin: .25em 0 .5em;
}
h1, h2 {
    color: rgb(208, 133, 4);
}
ul {
    list-style-type: none;
    margin: 0;
    padding-left: 0;
    padding-bottom: 1em;
}
li {
    padding-bottom: 0.5em;
}
a {
    color: rgb(41, 64, 124);
    font-weight: bold;
}
a:hover {
    color: rgb(208, 133, 4);
}
br {
    clear: left;
}
table {
    border: 1px solid black;
    border-collapse: collapse;
    margin-bottom: 1em;
}
td, th {
    border: 1px dashed black;
    padding: .2em .5em .2em .5em;
    text-align: left;
}
form {

}
/* the styles for classes */
.right {
    text-align: right;
}
.first_paragraph {
    margin-top: 0;	
}
.last_paragraph {
    margin-bottom: 2em;	
}
/* the styles for the div tags that divide the page into sections */
#left_column {
    float: left;
    width: 150px;
    text-align: center;
}
#right_column {
    float: left;
    padding-left: 1em;
    padding-bottom: 2em;
}
/* Additional styles for the Product Manager application */
#add_product_form {
    margin: .5em 0;
}
#add_product_form label {
    width: 6em;
    padding-right: 1em;
    padding-bottom: .5em;
    float: left;
}
#add_product_form input {
    float: left;
}
#add_product_form input[text] {
    width: 15em;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
index.php
<?php include 'view/header.php'; ?>
<div id="main">
    <h1 class="top">Menu</h1>
    <p><a href="product_manager">Product Manager</a></p>
    <p><a href="product_catalog">Product Catalog</a></p>
</div>
<?php include 'view/footer.php'; ?>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
header.php
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
    <title>My Guitar Shop</title>
    <link rel="stylesheet" type="text/css"
          href="/book_apps/ch14_guitar_shop/main.css">
</head>

<!-- the body section -->
<body>
<header><h1>My Guitar Shop</h1></header>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
footer.php
<footer>
    <p class="copyright">
        &copy; <?php echo date("Y"); ?> My Guitar Shop, Inc.
    </p>
</footer>
</body>
</html>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
product manager
index.php
<?php
require('../model/database.php');
require('../model/category.php');
require('../model/category_db.php');
require('../model/product.php');
require('../model/product_db.php');

// create the CategoryDB and ProductDB objects
$categoryDB = new CategoryDB();
$productDB = new ProductDB();

$action = filter_input(INPUT_POST, 'action');
if ($action == NULL) {
    $action = filter_input(INPUT_GET, 'action');
    if ($action == NULL) {
        $action = 'list_products';
    }
}  

switch($action) {
    case 'list_products':
        $category_id = filter_input(INPUT_GET, 'category_id', 
                FILTER_VALIDATE_INT);
        if ($category_id == NULL || $category_id == FALSE) {
            $category_id = 1;
        }

        // Get product and category data
        $current_category = $categoryDB->getCategory($category_id);
        $categories = $categoryDB->getCategories();
        $products = $productDB->getProductsByCategory($category_id);

        // Display the product list
        include('product_list.php');
        break;
    case 'delete_product':
        // Get the IDs
        $product_id = filter_input(INPUT_POST, 'product_id', 
                FILTER_VALIDATE_INT);
        $category_id = filter_input(INPUT_POST, 'category_id', 
                FILTER_VALIDATE_INT);

        // Delete the product
        $productDB->deleteProduct($product_id);

        // Display the Product List page for the current category
        header("Location: .?category_id=$category_id");
        break;
    case 'show_add_form':
        $categories = $categoryDB->getCategories();
        include('product_add.php');
        break;
    case 'add_product':
        $category_id = filter_input(INPUT_POST, 'category_id', 
                FILTER_VALIDATE_INT);
        $code = filter_input(INPUT_POST, 'code');
        $name = filter_input(INPUT_POST, 'name');
        $price = filter_input(INPUT_POST, 'price', 
                FILTER_VALIDATE_FLOAT);
        if ($category_id == NULL || $category_id == FALSE || $code == NULL || 
                $name == NULL || $price == NULL || $price == FALSE) {
            $error = "Invalid product data. Check all fields and try again.";
            include('../errors/error.php');
        } else {
            $current_category = $categoryDB->getCategory($category_id);
            // Create the Product object
            $product = new Product();
            $product->setCategory($current_category);
            $product->setCode($code);
            $product->setName($name);
            $product->setPrice($price);

            // Add the Product object to the database
            $productDB->addProduct($product);

            // Display the Product List page for the current category
            header("Location: .?category_id=$category_id");
        }
        break;
}
?>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
product_add.php
<?php include '../view/header.php'; ?>
<main>
    <h1>Add Product</h1>
    <form action="index.php" method="post" id="add_product_form">
        <input type="hidden" name="action" value="add_product" />

        <label>Category:</label>
        <select name="category_id">
        <?php foreach ($categories as $category) : ?>
            <option value="<?php echo $category->getID(); ?>">
                <?php echo $category->getName(); ?>
            </option>
        <?php endforeach; ?>
        </select>
        <br>

        <label>Code:</label>
        <input type="text" name="code">
        <br>

        <label>Name:</label>
        <input type="text" name="name">
        <br>

        <label>List Price:</label>
        <input type="text" name="price">
        <br>

        <label>&nbsp;</label>
        <input type="submit" value="Add Product">
        <br>
    </form>
    <p><a href="index.php?action=list_products">View Product List</a></p>
</main>
<?php include '../view/footer.php'; ?>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
product_list.php
<?php include '../view/header.php'; ?>
<main>
    <h1>Product List</h1>
    <aside>
        <!-- display a list of categories -->
        <h2>Categories</h2>
        <nav>
        <ul>
        <?php foreach ($categories as $category) : ?>
            <li>
            <a href="?category_id=<?php echo $category->getID(); ?>">
                <?php echo $category->getName(); ?>
            </a>
            </li>
        <?php endforeach; ?>
        </ul>
        </nav>
    </aside>
    <section>
        <!-- display a table of products -->
        <h2><?php echo $current_category->getName(); ?></h2>
        <table>
            <tr>
                <th>Code</th>
                <th>Name</th>
                <th class="right">Price</th>
                <th>&nbsp;</th>
            </tr>
            <?php foreach ($products as $product) : ?>
            <tr>
                <td><?php echo $product->getCode(); ?></td>
                <td><?php echo $product->getName(); ?></td>
                <td class="right"><?php echo $product->getPriceFormatted(); ?>
                </td>
                <td><form action="." method="post"
                          id="delete_product_form">
                    <input type="hidden" name="action"
                           value="delete_product">
                    <input type="hidden" name="product_id"
                           value="<?php echo $product->getID(); ?>">
                    <input type="hidden" name="category_id"
                           value="<?php echo $current_category->getID(); ?>">
                    <input type="submit" value="Delete">
                </form></td>
            </tr>
            <?php endforeach; ?>
        </table>
        <p><a href="?action=show_add_form">Add Product</a></p>
    </section>
</main>
<?php include '../view/footer.php'; ?>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
catalog
index.php
<?php
require('../model/database.php');
require('../model/category.php');
require('../model/category_db.php');
require('../model/product.php');
require('../model/product_db.php');

// create the CategoryDB and ProductDB objects
$categoryDB = new CategoryDB();
$productDB = new ProductDB();

$action = filter_input(INPUT_POST, 'action');
if ($action == NULL) {
    $action = filter_input(INPUT_GET, 'action');
    if ($action == NULL) {
        $action = 'list_products';
    }
}  

switch($action) {
    case 'list_products':
        $category_id = filter_input(INPUT_GET, 'category_id', 
                FILTER_VALIDATE_INT);
        if ($category_id == NULL || $category_id == FALSE) {
            $category_id = 1;
        }

        $current_category = $categoryDB->getCategory($category_id);
        $categories = $categoryDB->getCategories();
        $products = $productDB->getProductsByCategory($category_id);

        include('product_list.php');
        break;
    case 'view_product':
        $categories = $categoryDB->getCategories();

        $product_id = filter_input(INPUT_GET, 'product_id', 
                FILTER_VALIDATE_INT);   
        $product = $productDB->getProduct($product_id);

        include('product_view.php');
        break;
}

?>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
product_list.php
<?php include '../view/header.php'; ?>
<main>
    <aside>
        <h1>Categories</h1>
        <nav>
        <ul>
            <!-- display links for all categories -->            
            <?php foreach($categories as $category) : ?>
            <li>
                <a href="?category_id=<?php echo $category->getID(); ?>">
                    <?php echo $category->getName(); ?>
                </a>
            </li>
            <?php endforeach; ?>
        </ul>
        </nav>
    </aside>
    <section>
        <h1><?php echo $current_category->getName(); ?></h1>
        <nav>
        <ul>
            <?php foreach ($products as $product) : ?>
            <li>
                <a href="?action=view_product&amp;product_id=<?php
                          echo $product->getID(); ?>">
                    <?php echo $product->getName(); ?>
                </a>
            </li>
            <?php endforeach; ?>
        </ul>
        </nav>
    </section>
</main>
<?php include '../view/footer.php'; ?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
product_view.php
<?php include '../view/header.php'; ?>
<main>
    <aside>
        <h1>Categories</h1>
        <nav>
        <ul>
            <!-- display links for all categories -->
            <?php foreach($categories as $category) : ?>
            <li>
                <a href="?category_id=<?php echo $category->getID(); ?>">
                    <?php echo $category->getName(); ?>
                </a>
            </li>
            <?php endforeach; ?>
        </ul>
        </nav>
    </aside>
    <section>
        <h1><?php echo $product->getName(); ?></h1>
        <div id="left_column">
            <p>
                <img src="<?php echo $product->getImagePath(); ?>"
                    alt="<?php echo $product->getImageAltText(); ?>">
            </p>
        </div>
        <div id="right_column">
            <p><b>List Price:</b> $<?php echo $product->getPrice(); ?></p>
            <p><b>Discount:</b> <?php echo $product->getDiscountPercent(); ?>%</p>
            <p><b>Your Price:</b> $<?php echo $product->getDiscountPrice(); ?>
                 (You save $<?php echo $product->getDiscountAmount(); ?>)</p>
            <form action="<?php echo '../cart' ?>" method="post">
                <input type="hidden" name="action" value="add">
                <input type="hidden" name="product_id"
                       value="<?php echo $product->getID(); ?>">
                <b>Quantity:</b>
                <input type="text" name="quantity" value="1" size="2">
                <input type="submit" value="Add to Cart">
            </form>
        </div>
    </section>
</main>
<?php include '../view/footer.php'; ?>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
category.php
<?php
class Category {
    private int $id;
    private string $name;

    public function __construct() {
        $this->id = 0;
        $this->name = '';
    }

    public function getID() {
        return $this->id;
    }

    public function setID(int $value) {
        $this->id = $value;
    }

    public function getName() {
        return $this->name;
    }

    public function setName(string $value) {
        $this->name = $value;
    }
}
?>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
category_db.php
<?php
class CategoryDB {
    public function getCategories() {
        $db = Database::getDB();
        $query = 'SELECT * FROM categories
                  ORDER BY categoryID';
        $result = $db->query($query);
        $categories = [];
        foreach ($result as $row) {
            $category = new Category();
            $category->setID($row['categoryID']);
            $category->setName($row['categoryName']);
            $categories[] = $category;
        }
        return $categories;
    }

    public function getCategory($category_id) {
        $db = Database::getDB();
        $query = "SELECT * FROM categories
                  WHERE categoryID = '$category_id'";
        $statement = $db->query($query);
        $row = $statement->fetch();
        $category = new Category();
        $category->setID($row['categoryID']);
        $category->setName($row['categoryName']);
        return $category;
    }
}
?>


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
database.php
<?php
class Database {
    private static $dsn = 'mysql:host=localhost;dbname=my_guitar_shop1';
    private static $username = 'mgs_user';
    private static $password = 'pa55word';
    private static $db;

    private function __construct() {}

    public static function getDB () {
        if (!isset(self::$db)) {
            try {
                self::$db = new PDO(self::$dsn,
                                     self::$username,
                                     self::$password);
            } catch (PDOException $e) {
                $error_message = $e->getMessage();
                include('../errors/database_error.php');
                exit();
            }
        }
        return self::$db;
    }
}
?>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
product.php
<?php
class Product {
    private ?Category $category;
    private int $id;
    private string $code;
    private string $name;
    private float $price;

    public function __construct() {
        $this->category = null;
        $this->id = 0;
        $this->name = '';
        $this->description = '';
        $this->price = 0;
    }

    public function getCategory() {
        return $this->category;
    }

    public function setCategory(Category $value) {
        $this->category = $value;
    }

    public function getID() {
        return $this->id;
    }

    public function setID(int $value) {
        $this->id = $value;
    }

    public function getCode() {
        return $this->code;
    }

    public function setCode(string $value) {
        $this->code = $value;
    }

    public function getName() {
        return $this->name;
    }

    public function setName(string $value) {
        $this->name = $value;
    }

    public function getPrice() {
        return $this->price;
    }
    
    public function getPriceFormatted() {
        $formatted_price = number_format($this->price, 2);
        return $formatted_price;
    }

    public function setPrice(float $value) {
        $this->price = $value;
    }

    public function getDiscountPercent() {
        $discount_percent = 30;
        return $discount_percent;
    }

    public function getDiscountAmount() {
        $discount_percent = $this->getDiscountPercent() / 100;
        $discount_amount = $this->price * $discount_percent;
        $discount_amount = round($discount_amount, 2);
        $discount_amount = number_format($discount_amount, 2);
        return $discount_amount;
    }

    public function getDiscountPrice() {
        $discount_price = $this->price - $this->getDiscountAmount();
        $discount_price = number_format($discount_price, 2);
        return $discount_price;
    }

    public function getImageFilename() {
        $image_filename = $this->code . '.png';
        return $image_filename;
    }

    public function getImagePath() {
        $image_path = '../images/' . $this->getImageFilename();
        return $image_path;
    }

    public function getImageAltText() {
        $image_alt = 'Image: ' . $this->getImageFilename();
        return $image_alt;
    }
}
?>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
product_db.php
<?php
class ProductDB {

    public function getProductsByCategory($category_id) {
        $db = Database::getDB();

        $categoryDB = new CategoryDB();
        $category = $categoryDB->getCategory($category_id);

        $query = 'SELECT * FROM products
                  WHERE products.categoryID = :category_id
                  ORDER BY productID';
        $statement = $db->prepare($query);
        $statement->bindValue(":category_id", $category_id);
        $statement->execute();
        
        $rows = $statement->fetchAll();
        $statement->closeCursor();
        
        foreach ($rows as $row) {
            $product = new Product();
            $product->setCategory($category);
            $product->setId($row['productID']);
            $product->setCode($row['productCode']);
            $product->setName($row['productName']);
            $product->setPrice($row['listPrice']);

            $products[] = $product;
        }
        return $products;
    }

    public function getProduct($product_id) {
        $db = Database::getDB();
        $query = 'SELECT * FROM products
                  WHERE productID = :product_id';
        $statement = $db->prepare($query);
        $statement->bindValue(":product_id", $product_id);
        $statement->execute();
        
        $row = $statement->fetch();
        $statement->closeCursor();

        $categoryDB = new CategoryDB();
        $category = $categoryDB->getCategory($row['categoryID']);

        $product = new Product();
        $product->setCategory($category);
        $product->setId($row['productID']);
        $product->setCode($row['productCode']);
        $product->setName($row['productName']);
        $product->setPrice($row['listPrice']);

        return $product;
    }

    public function deleteProduct($product_id) {
        $db = Database::getDB();
        $query = 'DELETE FROM products
                  WHERE productID = :product_id';
        $statement = $db->prepare($query);
        $statement->bindValue(':product_id', $product_id);
        $statement->execute();
        $statement->closeCursor();
    }

    public function addProduct($product) {
        $db = Database::getDB();

        $category_id = $product->getCategory()->getID();
        $code = $product->getCode();
        $name = $product->getName();
        $price = $product->getPrice();

        $query = 'INSERT INTO products
                     (categoryID, productCode, productName, listPrice)
                  VALUES
                     (:category_id, :code, :name, :price)';
        $statement = $db->prepare($query);
        $statement->bindValue(':category_id', $category_id);
        $statement->bindValue(':code', $code);
        $statement->bindValue(':name', $name);
        $statement->bindValue(':price', $price);
        $statement->execute();
        $statement->closeCursor();
    }
}
?>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
error.php
<?php include '../view/header.php'; ?>
<div id="main">
    <h1 class="top">Error</h1>
    <p><?php echo $error; ?></p>
</div>
<?php include '../view/footer.php'; ?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
database_error.php
<?php include '../view/header.php'; ?>
<main>
    <h1>Database Error</h1>
    <p class="first_paragraph">There was an error connecting to the database.</p>
    <p>The database must be installed as described in the appendix.</p>
    <p>MySQL must be running as described in chapter 1.</p>
    <p class="last_paragraph">Error message: <?php echo $error_message; ?></p>
</main>
<?php include '../view/footer.php'; ?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cart
index.php
<?php include '../view/header.php'; ?>
<main>
    <h1>Shopping Cart - under construction</h1>
</main>
<?php include '../view/footer.php'; ?>


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
main.css
html {
    background-color: rgb(192, 192, 192);
}
body {
    font-family: Arial, Helvetica, sans-serif;
    width: 760px;
    margin: 0 auto;
    padding: 0 2em;
    background-color: white;
    border: 1px solid black;
}
header {
    border-bottom: 2px solid black;
    padding: .5em 0;
}
header h1 {
    color: black;
}
main {

}
aside {
    float: left;
    width: 150px;
}
section {
    float: left;
    width: 500px;
}
footer {
    clear: both;
    border-top: 2px solid black;
}
footer p {
    text-align: right;
    font-size: 80%;
}
h1 {
    font-size: 150%;
    margin: 0;
    padding: .5em 0 .25em;
}
h2 {
    font-size: 120%;
    margin: 0;
    padding: .75em 0 0;
}
h1, h2 {
    color: rgb(208, 133, 4);
}

/* styles for the form */
fieldset {
    margin: 1em;
    padding-top: 1em;
}

legend {
    font-weight: bold;
    font-size: 85%;
}

label {
    float: left;
    width: 10em;
    text-align: right;
    margin-top: .25em;
    margin-bottom: .5em;
}

input, select {
    margin-left: 0.5em;
    margin-bottom: 0.5em;
}
select {
    width: 11em;
}

br {
    clear: both;
}
span {
    vertical-align: middle;
}

.error {
    color: red;
}

.notice {
    color: red;
    font-size: 67%;
    text-align: right;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
index.php
<?php
require_once('model/fields.php');
require_once('model/validate.php');

// Add fields with optional initial message
$validate = new Validate();
$fields = $validate->getFields();
$fields->addField('first_name');
$fields->addField('last_name');
$fields->addField('phone', 'Use 888-555-1234 format.');
$fields->addField('email', 'Must be a valid email address.');

$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
    $action = 'reset';
} else {
    $action = strtolower($action);
}

switch ($action) {
    case 'reset':
        // Reset values for variables
        $first_name = '';
        $last_name = '';
        $phone = '';
        $email = '';

        // Load view
        include 'view/register.php';
        break;
    case 'register':
        // Copy form values to local variables
        $first_name = trim(filter_input(INPUT_POST, 'first_name'));
        $last_name = trim(filter_input(INPUT_POST, 'last_name'));
        $phone = trim(filter_input(INPUT_POST, 'phone'));
        $email = trim(filter_input(INPUT_POST, 'email'));

        // Validate form data
        $validate->text('first_name', $first_name);
        $validate->text('last_name', $last_name);
        $validate->phone('phone', $phone);
        $validate->email('email', $email);

        // Load appropriate view based on hasErrors
        if ($fields->hasErrors()) {
            include 'view/register.php';
        } else {
            include 'view/success.php';
        }
        break;
}
?>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
view
success.php
<?php include 'header.php'; ?>
<main>
    <h2>Success</h2>
    <p>The following registration information has been successfully
       submitted.</p>
    <ul>
        <li>First Name: <?php echo htmlspecialchars($first_name); ?></li>
        <li>Last Name: <?php echo htmlspecialchars($last_name); ?></li>
        <li>Phone: <?php echo htmlspecialchars($phone); ?></li>
        <li>Email: <?php echo htmlspecialchars($email); ?></li>
    </ul>
</main>
<?php include 'footer.php'; ?>


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
register.php
<?php include 'header.php'; ?>
<main>
    <form action="." method="post" >
    <fieldset>
        <legend>User Information</legend>
        
        <label>First Name:</label>
        <input type="text" name="first_name" 
               value="<?php echo htmlspecialchars($first_name);?>">
        <?php echo $fields->getField('first_name')->getHTML(); ?><br>

        <label>Last Name:</label>
        <input type="text" name="last_name" 
               value="<?php echo htmlspecialchars($last_name);?>">
        <?php echo $fields->getField('last_name')->getHTML(); ?><br>

        <label>Phone:</label>
        <input type="text" name="phone" 
               value="<?php echo htmlspecialchars($phone);?>">
        <?php echo $fields->getField('phone')->getHTML(); ?><br>

        <label>E-Mail:</label>
        <input type="text" name="email" 
               value="<?php echo htmlspecialchars($email);?>">
        <?php echo $fields->getField('email')->getHTML(); ?><br>
    </fieldset>
    <fieldset>
        <legend>Submit Registration</legend>
        
        <label>&nbsp;</label>
        <input type="submit" name="action" value="Register"/>
        <input type="submit" name="action" value="Reset" /><br>
    </fieldset>
    </form>
</main>
<?php include 'footer.php'; ?>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
header.php
<!DOCTYPE html>
<html>
<head>
    <title>My Guitar Shop</title>
    <link rel="stylesheet" type="text/css" href="main.css" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<header>
    <h1>Register for an Account</h1>
</header>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
footer.php
<footer>
    <p class="copyright">
        &copy; <?php echo date("Y"); ?> My Guitar Shop, Inc.
    </p>
</footer>
</body>
</html>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
model
fields.php
<?php
class Field {
    private $name;
    private $message = '';
    private $hasError = false;

    public function __construct($name, $message = '') {
        $this->name = $name;
        $this->message = $message;
    }
    public function getName()    { return $this->name; }
    public function getMessage() { return $this->message; }
    public function hasError()    { return $this->hasError; }

    public function setErrorMessage($message) {
        $this->message = $message;
        $this->hasError = true;
    }
    public function clearErrorMessage() {
        $this->message = '';
        $this->hasError = false;
    }

    public function getHTML() {
        $message = htmlspecialchars($this->message);
        if ($this->hasError()) {
            return '<span class="error">' . $message . '</span>';
        } else {
            return '<span>' . $message . '</span>';
        }
    }
}

class Fields {
    private $fields = array();

    public function addField($name, $message = '') {
        $field = new Field($name, $message);
        $this->fields[$field->getName()] = $field;
    }

    public function getField($name) {
        return $this->fields[$name];
    }

    public function hasErrors() {
        foreach ($this->fields as $field) {
            if ($field->hasError()) { return true; }
        }
        return false;
    }
}
?>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
validate.php
<?php
class Validate {
    private $fields;

    public function __construct() {
        $this->fields = new Fields();
    }

    public function getFields() {
        return $this->fields;
    }

    // Validate a generic text field
    public function text($name, $value,
            $required = true, $min = 1, $max = 255) {

        // Get Field object
        $field = $this->fields->getField($name);

        // If field is not required and empty, remove error and exit
        if (!$required && empty($value)) {
            $field->clearErrorMessage();
            return;
        }

        // Check field and set or clear error message
        if ($required && empty($value)) {
            $field->setErrorMessage('Required.');
        } else if (strlen($value) < $min) {
            $field->setErrorMessage('Too short.');
        } else if (strlen($value) > $max) {
            $field->setErrorMessage('Too long.');
        } else {
            $field->clearErrorMessage();
        }
    }

    // Validate a field with a generic pattern
    public function pattern($name, $value, $pattern, $message,
            $required = true) {

        // Get Field object
        $field = $this->fields->getField($name);

        // If field is not required and empty, remove errors and exit
        if (!$required && empty($value)) {
            $field->clearErrorMessage();
            return;
        }

        // Check field and set or clear error message
        $match = preg_match($pattern, $value);
        if ($match === false) {
            $field->setErrorMessage('Error testing field.');
        } else if ( $match != 1 ) {
            $field->setErrorMessage($message);
        } else {
            $field->clearErrorMessage();
        }
    }

    public function phone($name, $value, $required = false) {
        $field = $this->fields->getField($name);

        // Call the text method and exit if it yields an error
        $this->text($name, $value, $required);
        if ($field->hasError()) { return; }

        // Call the pattern method to validate a phone number
        $pattern = '/^[[:digit:]]{3}-[[:digit:]]{3}-[[:digit:]]{4}$/';
        $message = 'Invalid phone number.';
        $this->pattern($name, $value, $pattern, $message, $required);
    }

    public function email($name, $value, $required = true) {
        $field = $this->fields->getField($name);

        // If field is not required and empty, remove errors and exit
        if (!$required && empty($value)) {
            $field->clearErrorMessage();
            return;
        }

        // Call the text method and exit if it yields an error
        $this->text($name, $value, $required);
        if ($field->hasError()) { return; }

        // Split email address on @ sign and check parts
        $parts = explode('@', $value);
        if (count($parts) < 2) {
            $field->setErrorMessage('At sign required.');
            return;
        }
        if (count($parts) > 2) {
            $field->setErrorMessage('Only one at sign allowed.');
            return;
        }
        $local = $parts[0];
        $domain = $parts[1];

        // Check lengths of local and domain parts
        if (strlen($local) > 64) {
            $field->setErrorMessage('Username part too long.');
            return;
        }
        if (strlen($domain) > 255) {
            $field->setErrorMessage('Domain name part too long.');
            return;
        }

        // Patterns for address formatted local part
        $atom = '[[:alnum:]_!#$%&\'*+\/=?^`{|}~-]+';
        $dotatom = '(\.' . $atom . ')*';
        $address = '(^' . $atom . $dotatom . '$)';

        // Patterns for quoted text formatted local part
        $char = '([^\\\\"])';
        $esc  = '(\\\\[\\\\"])';
        $text = '(' . $char . '|' . $esc . ')+';
        $quoted = '(^"' . $text . '"$)';

        // Combined pattern for testing local part
        $localPattern = '/' . $address . '|' . $quoted . '/';

        // Call the pattern method and exit if it yields an error
        $this->pattern($name, $local, $localPattern,
                'Invalid username part.');
        if ($field->hasError()) { return; }

        // Patterns for domain part
        $hostname = '([[:alnum:]]([-[:alnum:]]{0,62}[[:alnum:]])?)';
        $hostnames = '(' . $hostname . '(\.' . $hostname . ')*)';
        $top = '\.[[:alnum:]]{2,6}';
        $domainPattern = '/^' . $hostnames . $top . '$/';

        // Call the pattern method
        $this->pattern($name, $domain, $domainPattern,
                'Invalid domain name part.');
    }
}
?>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
main.css
/* the styles for the html elements */
html {
    background-color: rgb(192, 192, 192);
}
body {
    margin-top: 0;
    font-family: Arial, Helvetica, sans-serif;
    width: 760px;
    margin: 0 auto;
    background-color: white;
    border: 1px solid black;
    padding: .5em 2em;
}
header {
    margin: 0;
    border-bottom: 2px solid black;
}
header h1 {
    margin: 0;
    padding: .5em 0;
    color: black;
}
main {
    margin: 0;
}
aside {
    float: left;
    width: 150px;
}
nav ul {
    list-style-type: none;
    margin-left: 0;
    padding-left: 0;
}
nav ul li {
    padding-bottom: 0.5em;
}
section {
    float: left;
    width: 500px;
    padding-bottom: 1.5em;
}
footer {
    clear: both;
    margin-top: 1em;
    border-top: 2px solid black;
}
footer p {
    text-align: right;
    font-size: 80%;
    margin: 1em 0;
}
h1 {
    font-size: 150%;
    margin: 0;
    padding: .5em 0 .25em;
}
h2 {
    font-size: 120%;
    margin: 0;
    padding: .25em 0 .5em;
}
h1, h2 {
    color: rgb(208, 133, 4);
}
ul {
    margin: 0 0 1em 0;
    padding: 0 0 0 2.5em;
}
li {
    margin: 0;
    padding: 0;
}
a {
    color: rgb(41, 64, 124);
    font-weight: bold;
}
a:hover {
    color: rgb(208, 133, 4);
}
table {
    border: 1px solid black;
    border-collapse: collapse;
}
td, th {
    border: 1px dashed black;
    padding: .2em .5em .2em .5em;
    vertical-align: top;
    text-align: left;
}
form {
    margin: 0;
}
br {
    clear: left;
}
/* the styles for classes */
.right {
    text-align: right;
}
.last_paragraph {
	margin-bottom: 2em;	
}
.margin_top_increase {
	margin-top: 1em;	
}

/********************************************************************
* Additional styles for the Product Manager application
********************************************************************/
#add_product_form {
    margin: .5em 0 1em;
}
#add_product_form label {
    width: 6em;
    padding-right: 1em;
    padding-bottom: .5em;
    float: left;
}
#add_product_form input {
    float: left;
}
#add_product_form input[text] {
    width: 15em;
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
index.php
<?php
require_once('database.php');

// Get category ID
if (!isset($category_id)) {
    $category_id = filter_input(INPUT_GET, 'category_id', 
            FILTER_VALIDATE_INT);
    if ($category_id == NULL || $category_id == FALSE) {
        $category_id = 1;
    }
}
// Get name for selected category
$queryCategory = 'SELECT * FROM categories
                  WHERE categoryID = :category_id';
$statement1 = $db->prepare($queryCategory);
$statement1->bindValue(':category_id', $category_id);
$statement1->execute();
$category = $statement1->fetch();
$category_name = $category['categoryName'];
$statement1->closeCursor();


// Get all categories
$query = 'SELECT * FROM categories
          ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$categories = $statement->fetchAll();
$statement->closeCursor();

// Get products for selected category
$queryProducts = 'SELECT * FROM products
                  WHERE categoryID = :category_id
                  ORDER BY productID';
$statement3 = $db->prepare($queryProducts);
$statement3->bindValue(':category_id', $category_id);
$statement3->execute();
$products = $statement3->fetchAll();
$statement3->closeCursor();
?>
<!DOCTYPE html>
<html>

<!-- the head section -->
<head>
    <title>Task 4b</title>
    <link rel="stylesheet" href="main.css" />
</head>

<!-- the body section -->
<body>
<header><h1>Task 4b</h1></header>
<main>
    <h1>Task 4b</h1>

    <aside>
        <!-- display a list of categories -->
        <h2>Categories</h2>
        <nav>
        <ul>
            <?php foreach ($categories as $category) : ?>
            <li><a href=".?category_id=<?php echo $category['categoryID']; ?>">
                    <?php echo $category['categoryName']; ?>
                </a>
            </li>
            <?php endforeach; ?>
        </ul>
        </nav>          
    </aside>

    <section>
        <!-- display a table of products -->
        <h2><?php echo $category_name; ?></h2>
        <table>
            <tr>
                <th>Code</th>
                <th>Name</th>
                <th class="right">Price</th>
                <th>&nbsp;</th>
            </tr>

            <?php foreach ($products as $product) : ?>
            <tr>
                <td><?php echo $product['productCode']; ?></td>
                <td><?php echo $product['productName']; ?></td>
                <td class="right"><?php echo $product['listPrice']; ?></td>
                <td><form action="delete_product.php" method="post">
                    <input type="hidden" name="product_id"
                           value="<?php echo $product['productID']; ?>">
                    <input type="hidden" name="category_id"
                           value="<?php echo $product['categoryID']; ?>">
                    <input type="submit" value="Delete">
                </form></td>
            </tr>
            <?php endforeach; ?>
        </table>
        <p><a href="add_product_form.php">Add Product</a></p>
        <p><a href="category_list.php">List Categories</a></p>        
    </section>
</main>
<footer>
    <p>&copy; <?php echo date("Y"); ?> Task 4b, assignment 4.</p>
</footer>
</body>
</html>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
error.php
<!DOCTYPE html>
<html>

<!-- the head section -->
<head>
    <title>Task 4b</title>
    <link rel="stylesheet" href="main.css" />
</head>

<!-- the body section -->
<body>
    <header><h1>Task 4b</h1></header>

    <main>
        <h2 class="top">Error</h2>
        <p><?php echo $error; ?></p>
    </main>

    <footer>
        <p>&copy; <?php echo date("Y"); ?> Task 4b, assignment 4.</p>
    </footer>
</body>
</html>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
delete_product.php
<?php
require_once('database.php');

// Get IDs
$product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
$category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);

// Delete the product from the database
if ($product_id != FALSE && $category_id != FALSE) {
    $query = 'DELETE FROM products
              WHERE productID = :product_id';
    $statement = $db->prepare($query);
    $statement->bindValue(':product_id', $product_id);
    $success = $statement->execute();
    $statement->closeCursor();    
}

// Display the Product List page
include('index.php');

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
delete_category.php
<?php
// Get ID
$category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);

// Validate inputs
if ($category_id == NULL || $category_id == FALSE) {
    $error = "Invalid category ID.";
    include('error.php');
} else {
    require_once('database.php');

    // Add the product to the database  
    $query = 'DELETE FROM categories 
              WHERE categoryID = :category_id';
    $statement = $db->prepare($query);
    $statement->bindValue(':category_id', $category_id);
    $statement->execute();
    $statement->closeCursor();

    // Display the Category List page
    include('category_list.php');
}
?>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
database_error.php
<!DOCTYPE html>
<html>

<!-- the head section -->
<head>
    <title>Task 4b</title>
    <link rel="stylesheet" href="main.css" />
</head>

<!-- the body section -->
<body>
    <header><h1>Task 4b</h1></header>

    <main>
        <h1>Database Error</h1>
        <p>There was an error connecting to the database.</p>
        <p>The database must be installed as described in the appendix.</p>
        <p>MySQL must be running as described in chapter 1.</p>
        <p>Error message: <?php echo $error_message; ?></p>
        <p>&nbsp;</p>
    </main>

    <footer>
        <p>&copy; <?php echo date("Y"); ?> Task 4b, assignment 4.</p>
    </footer>
</body>
</html>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
database.php
<?php
    $dsn = 'mysql:host=localhost;dbname=my_guitar_shop1';
    $username = 'mgs_user';
    $password = 'pa55word';

    try {
        $db = new PDO($dsn, $username, $password);
    } catch (PDOException $e) {
        $error_message = $e->getMessage();
        include('database_error.php');
        exit();
    }
?>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
category_list.php
<?php
require_once('database.php');

// Get all categories
$query = 'SELECT * FROM categories
          ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$categories = $statement->fetchAll();
$statement->closeCursor();
?>
<!DOCTYPE html>
<html>

<!-- the head section -->
<head>
    <title>Task 4b</title>
    <link rel="stylesheet" href="main.css" />
</head>

<!-- the body section -->
<body>
<header><h1>Product Manager</h1></header>
<main>
    <h1>Category List</h1>
    <table>
        <tr>
            <th>Name</th>
            <th>&nbsp;</th>
        </tr>        
        <?php foreach ($categories as $category) : ?>
        <tr>
            <td><?php echo $category['categoryName']; ?></td>
            <td>
                <form action="delete_category.php" method="post">
                    <input type="hidden" name="category_id"
                           value="<?php echo $category['categoryID']; ?>"/>
                    <input type="submit" value="Delete"/>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>    
    </table>

    <h2 class="margin_top_increase">Add Category</h2>
    <form action="add_category.php" method="post"
          id="add_category_form">

        <label>Name:</label>
        <input type="text" name="name" />
        <input id="add_category_button" type="submit" value="Add"/>
    </form>
    
    <p><a href="index.php">List Products</a></p>

</main>
<footer>
    <p>&copy; <?php echo date("Y"); ?> Task 4b, assignment 4.</p>
</footer>
</body>
</html>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
add_category_form.php
<?php
require('database.php');
$query = 'SELECT *
          FROM categories
          ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$categories = $statement->fetchAll();
$statement->closeCursor();
?>
<!DOCTYPE html>
<html>

<!-- the head section -->
<head>
    <title>Task 4b</title>
    <link rel="stylesheet" href="main.css">
</head>

<!-- the body section -->
<body>
    <header><h1>Task 4b</h1></header>

    <main>
        <h1>Add Product</h1>
        <form action="add_product.php" method="post"
              id="add_product_form">

            <label>Category:</label>
            <select name="category_id">
            <?php foreach ($categories as $category) : ?>
                <option value="<?php echo $category['categoryID']; ?>">
                    <?php echo $category['categoryName']; ?>
                </option>
            <?php endforeach; ?>
            </select><br>

            <label>Code:</label>
            <input type="text" name="code"><br>

            <label>Name:</label>
            <input type="text" name="name"><br>

            <label>List Price:</label>
            <input type="text" name="price"><br>

            <label>&nbsp;</label>
            <input type="submit" value="Add Product"><br>
        </form>
        <p><a href="index.php">View Product List</a></p>
    </main>

    <footer>
        <p>&copy; <?php echo date("Y"); ?> Task 4b, assignment 4.</p>
    </footer>
</body>
</html>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
add_product.php
<?php
// Get the product data
$category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
$code = filter_input(INPUT_POST, 'code');
$name = filter_input(INPUT_POST, 'name');
$price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);

// Validate inputs
if ($category_id == NULL || $category_id == FALSE || $code == NULL || 
        $name == NULL || $price == NULL || $price == FALSE) {
    $error = "Invalid product data. Check all fields and try again.";
    include('error.php');
} else {
    require_once('database.php');

    // Add the product to the database  
    $query = 'INSERT INTO products
                 (categoryID, productCode, productName, listPrice)
              VALUES
                 (:category_id, :code, :name, :price)';
    $statement = $db->prepare($query);
    $statement->bindValue(':category_id', $category_id);
    $statement->bindValue(':code', $code);
    $statement->bindValue(':name', $name);
    $statement->bindValue(':price', $price);
    $statement->execute();
    $statement->closeCursor();

    // Display the Product List page
    include('index.php');
}
?>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
add_category.php
<?php
// Get the category data
$name = filter_input(INPUT_POST, 'name');

// Validate inputs
if ($name == NULL) {
    $error = "Invalid category data. Check all fields and try again.";
    include('error.php');
} else {
    require_once('database.php');

    // Add the product to the database  
    $query = 'INSERT INTO categories (categoryName)
              VALUES (:category_name)';
    $statement = $db->prepare($query);
    $statement->bindValue(':category_name', $name);
    $statement->execute();
    $statement->closeCursor();

    // Display the Category List page
    include('category_list.php');
}
?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
newfolder
index.php
 <?php
 require 'database.php';
 // Get category ID
 $category_id = $_GET['category_id']; 
if (!isset($category_id)) {
 $category_id = 1;
 }
 // Get name for current category 
$query = "SELECT * FROH categories
 WHERE categorylD = $category_id";
 $category = $db->query($query);
 $category = $category->fetch();
 $category_name = $category['categoryName'];
 // Get all categories 
$query = 'SELECT * FROM categories 
ORDER BY categorylD';
 $categories = $db->query($query);
 // Get products for selected category 
$query = "SELECT * FROH products
 WHERE categorylD = $category_id 
ORDER BY productID";
 $products = $db->query($query);
 ?>
<!D0CTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns = "ht tp://www.w3.org/1999/xhtml">
 <!-- the head section -->
 <head>
 <title>Hy Guitar Shop</title>
 <link rel="stylesheet" type="text/css" href="main.css" /> 
</head>
 <!-- the body section -->
 <body>
 <div id="page">
 <div id="main">
 <hl>Product List</hl>
 <div id="sidebar">
 <!-- display a list of categories -->
 <h2>Categories</h2>
 <ul class="nav">
 <?php foreach ($categories as $category) : ?>
 <li>
 <a href="?category_id=<?php echo $category['categorylD']; ?>"> 
<?php echo $category['categoryName']; ?>
 </a>
 </li>
 <?php endforeach; ?>
 </ul>
 </div>
 <div id="content">
 <!-- display a table of products -->
 <h2><?php echo $category_name; ?></h2>
 <table>
 <tr>
 <th>Code</th>
 <th>Name</th>
 <th class="right">Price</th>
 </tr>
 <?php foreach ($products as $product) : ?>
 <tr>
 <td><?php echo $product ['productCode'] ; ?></td>
 <td><?php echo $product ['productName'] ; ?></td>
 <td class="right"><?php echo Sproduct ['listPrice'] ; ?></td> 
</tr>
 <?php endforeach; ?>
 </table>
 </div>
 </div><!-- end main -->
 <div id=" footer">
  <p>&copy; <?php echo date("Yn); ?> My Guitar Shop, Inc.</p> 
 </div>
 </div><!-- end page - ->
 </body>
 </html>
 
 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 delete_product.php
  <?php
 // Get IDs
 $product_id = $_POST[1product_id1];
 $category_ld = $_POST[1category_id1];
 // Delete the product from the database 
require_once(1 database.php1);
 $query = "DELETE FROM products
 WHERE productID = 1$product_id1";
 $db->exec($query);
 // Display the Product List page 
Include(1 Index.php1);
 ?>
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 database_error.php
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns = "ht tp://www.w3.org/19 9 9/xhtml">
 <!-- the head section -->
 <head>
 <title>Task4b</title>
 <link rel="stylesheet" type="text/css" href="main.css" />
 </head>
 <!-- the body section -->
 <body>
 <div id="page">
 <div id="main">
 <hl>Database Error</hl>
 <p>There was an error connecting to the database.</p>
 <p>The database must be installed as described in appendix A.</p> 
<p>The database must be running as described in chapter l.</p> 
<p>Error message: <?php echo $error_message; ?></p>
 </div>
 </div><!-- end page -->
 </body>
 </html>
 
 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 database.php
 <?php
 $dsn = 'mysql:host=localhost;dbname=my_guitar_shop1'; 
$username = 'mgs_user';
 $password = 'pa55word';
 try {
 $db = new PDO($dsn, $username, $password);
 } catch (PDOException $e) {
 $error_message = $e->getMessage(); 
include('database_error.php'); 
exit() ;
 }
 
 ?>
 
 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 add_category_form.php
  <?php
 requireonce(1 database.php1);
 $query = 'SELECT *
 FROH categories 
ORDER BY categorylD';
 $categorles = $db->query($query);
 ?>
 How to use PHP with MySQL 
<!D0CTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtmll/DTD/xhtmll-transitional.dtd"> 
chtml xmlns="ht tp://www.w3.org/19 9 9/xhtml">
 <!-- the head section -->
 <head>
 <title>Task4b</title>
 clink rel="stylesheet" type="text/css" href="main.css" />
 </head>
 <!-- the body section -->
 <body>
 <div id="page">
 <div id="header">
 <hl>Product Manager</hl>
 </div>
 <div id="main">
 <hl>Add Product</hl>
 <form action="add_product.php" method="post" 
id="add_product_form" >
 <label>Category:</label>
 <select name="category_id">
 <?php foreach ($categories as $category) : ?>
 «option value="<?php echo $category['categorylD']; ?>"> 
<?php echo $category['categoryName'] ; ?>
 </option>
 <?php endforeach; ?>
 </select>
 <br />
  <label>Code:</label>
 cinput type="input" name="code" />
 <br />
 <label>Name:</label>
 <input type="input" name="name" />
 <br />
 <label>List Price:</label>
 <input type="input" name="price" />
 <br />
 How to use PHP with MySQL 
<label>&nbsp;</label>
 <input type="submit" value="Add Product" />
 <br />
 </form>
 <pxa href="index.php">View Product List</ax/p>
 </div><!-- end main -->
 <div id="footer">
 <p>&copy; <?php echo date("Y"); ?>Task4b, assignment 4.</p> 
</div>
 </div><!-- end page -->
 </body>
 </html>
 
 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 add_product.php
  <?php
 // Get the product data 
$category_id = $_POST['category_id'];
 $code = $_POST['code'];
 $name = $_POST['name'];
 $price = $_POST['price'];
 
 // Validate inputs
 if (empty($code) || empty($name) || empty($price) ) {
 $error = "Invalid product data. Check all fields and try again."; 
include('error.php');
 } else {
 // If valid, add the product to the database 
reguire_once('database.php');
 $query = "INSERT INTO products
 (categorylD, productCode, productName, listPrice) 
VALUES
 ('$category_id', '$code', '$name', '$price')"; 
$db->exec($query);
 // Display the Product List page 
include('index.php');
 }
 ?>
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 



/////////////////////////////////////////////////////////////////////Task 4(a)////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



/////////////////////////////////////////////////////////////////////Task 4(b)////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////