diff --git a/week-13/README.txt b/week-13/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..3ec4f7e04e250189518ef35eb7d907808868ecb0 --- /dev/null +++ b/week-13/README.txt @@ -0,0 +1,29 @@ +********************************* +* RECORD STORE APPLICATION * +********************************* + +## this recordstore has been hacked for term 2 + +Description +----------- +This is a demo record store application. You can use it to help you complete lab 8. It is You can also read this README file to find out the sorts of things that should be included in a README file! + +Author & Contact +---------------- +Sorrel Harriet s.harriet@gold.ac.uk + +Installation Instructions +------------------------- ++ Check you have a LAMP stack installed with PHP>5 and MySQL>5 ++ Upload the application to your web root folder. ++ Run the record-store.sql file on your database. ++ Run the dummy_data.sql file to insert some data. + +Configuration Instructions +-------------------------- +Modify the includes/db_connect.php script with your MySQL database credentials. + +Live Demo +--------- +A demo version of this app is deployed at the following URL: +http://doc.gold.ac.uk/~sharr003/data-network-web/lab-exercises/week-8/record-store-app/ diff --git a/week-13/admin/index.php b/week-13/admin/index.php new file mode 100644 index 0000000000000000000000000000000000000000..4b5707c19c18855d5214132b5d6f434ce53e3845 --- /dev/null +++ b/week-13/admin/index.php @@ -0,0 +1,70 @@ +<?php + +// connect to the database +require('../includes/db_connect.php'); +require('../includes/functions.php'); + +session_start(); +if (!is_logged_in()) { + header('Location: http://localhost/term2labs-dan/week-13/admin/views/login.php'); +} + +// define a function to sanitise user input (this would ideally be in includes folder) +function clean_input($data) { + $data = trim($data); // strips unnecessary characters from beginning/end + $data = stripslashes($data); // remove backslashes + $data = htmlspecialchars($data); // replace special characters with HTML entities + return $data; +} + +// include the header HTML +include('../templates/header.html'); + +// include the navigation HTML +include('views/navigation.html'); + +// get the page id from the URL +// if no parameter detected... +if (!isset($_GET['page'])) { + $id = 'home'; // display home page +} else { + $id = $_GET['page']; // else requested page +} + +// use switch to determine which view to serve based on $id +switch ($id) { +case 'home' : + include 'views/home.php'; + break; +case 'record' : + include 'views/record.php'; + break; +case 'artist' : + include 'views/artist.php'; + break; +case 'orders' : + include 'views/orders.php'; + break; +case 'order' : + include 'views/order.php'; + break; +case 'add-record' : + include 'views/add-record.php'; + break; +case 'search' : + include 'views/search.php'; + break; +case 'logout' : + include 'views/logout.php'; + break; +default : + include 'views/404.php'; +} + +// close the connection to the database +mysqli_close($link); + +// include the footer HTML +include('../templates/footer.html'); + +?> diff --git a/week-13/admin/views/404.php b/week-13/admin/views/404.php new file mode 100644 index 0000000000000000000000000000000000000000..7ae2fe7434a65afd31bee52d9ef7edb42d0ee2f1 --- /dev/null +++ b/week-13/admin/views/404.php @@ -0,0 +1,10 @@ +<?php + +// create variable for content HTML +$content = "<h1>Page not found</h1>"; +$content .= "<p>Sorry, the page you requested could not be found.</p>"; + +// output the content HTML +echo $content; + +?> diff --git a/week-13/admin/views/add-record.php b/week-13/admin/views/add-record.php new file mode 100644 index 0000000000000000000000000000000000000000..8ba12cf18a76d7695e7f8194a6622d04ff37ec49 --- /dev/null +++ b/week-13/admin/views/add-record.php @@ -0,0 +1,175 @@ +<?php + +$content = "<h1>Add a record</h1>"; + +// define a variable with path to the script which will process form +// -> $_SERVER["PHP_SELF"] is a path to the current script (index.php) +// -> htmlspecialchars() is used to replace special characters with HTML entities */ +$action = htmlspecialchars($_SERVER["PHP_SELF"]."?page=add-record"); + +// fetch the artists so that we have access to their names and IDs +$sql = "SELECT id, first_name, last_name + FROM artist + ORDER BY last_name"; + +$result = mysqli_query($link, $sql); + +// check query returned a result +if ($result === false) { + echo mysqli_error($link); +} else { + $options = ""; + // create an option for each artist + while ($row = mysqli_fetch_assoc($result)) { + $options .= "<option value='".$row['id']."'>"; + $options .= $row['first_name']." ".$row['last_name']; + $options .= "</option>"; + } +} + +// define the form HTML (would ideally be in a template) +$form_html = "<form action='".$action."' enctype='multipart/form-data' method='POST'> +<input type='hidden' name='MAX_FILE_SIZE' value='1000000' /> + <fieldset> + <label for='ean'>EAN (required):</label> + <input type='text' name='ean'/> + </fieldset> + <fieldset> + <label for='title'>Title:</label> + <input type='text' name='title' /> + </fieldset> + <fieldset> + <label for='artist_id'>Artist:</label> + <select name='artist_id'> + + ".$options." + <option value='NULL'>Not listed</option> + </select> + </fieldset> + <fieldset> + <label for='genre'>Genre</label> + <input type='text' name='genre' /> + </fieldset> + <fieldset> + <label for='year'>Year:</label> + <input type='text' name='year' size='5' placeholder='YYYY' /> + </fieldset> + <fieldset> + <label for='price'>Price (£):</label> + <input type='text' name='price' placeholder='00.00' /> + </fieldset> + <fieldset> + <label for='price'>Stock:</label> + <input type='text' name='stock' placeholder='0' /> + </fieldset> +<label>image <input type='file' id='image' name='image' /></label><br /> + <button type='submit'>Submit</button> + </form>"; + +// append form HTML to content string +$content .= $form_html; + +// ------- START form processing code... ------- + + +// define variables and set to empty values +$title = $artist_id = $price = $year = $genre = $stock = ""; + +// check if there was a POST request +if ($_SERVER["REQUEST_METHOD"] == "POST") { + // validate the form data + $ean = mysqli_real_escape_string($link, clean_input($_POST["ean"])); + $title = mysqli_real_escape_string($link, clean_input($_POST["title"])); + $artist_id = mysqli_real_escape_string($link, clean_input($_POST["artist_id"])); + $genre = mysqli_real_escape_string($link, clean_input($_POST["genre"])); + $year = mysqli_real_escape_string($link, clean_input($_POST["year"])); + $price = mysqli_real_escape_string($link, clean_input($_POST["price"])); + $stock = mysqli_real_escape_string($link, clean_input($_POST["stock"])); + + // handle the image upload + $uploadOk = 1; + + $target_dir = "../uploads/"; + $image_dir = "uploads/"; + + // Check if image file is a actual image or fake image + $check = getimagesize($_FILES["image"]["tmp_name"]); + if($check !== false) { + // echo "File is an image - " . $check["mime"] . "."; + $uploadOk = 1; + } else { + echo "File is not an image."; + $uploadOk = 0; + } + + // Check file size + if ($_FILES["image"]["size"] > 1000000) { + echo "Sorry, your file is too large."; + $uploadOk = 0; + } + + $target_file = $target_dir . basename($_FILES["image"]["name"]); + $image = $image_dir . basename($_FILES["image"]["name"]); + + // Check if file already exists + if (file_exists($target_file)) { + echo "Sorry, file already exists."; + $uploadOk = 0; + } + + $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); + + // Allow certain file formats + if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" + && $imageFileType != "gif" ) { + echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; + $uploadOk = 0; + } + + // Check if $uploadOk is set to 0 by an error + if ($uploadOk == 0) { + echo "Sorry, your file was not uploaded."; + + // if everything is ok, try to upload file + } else { + if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) { + echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded."; + } else { + echo "Sorry, there was an error uploading your file."; + } + } + // end of image upload + + // turn autocommit off + mysqli_autocommit($link, FALSE); + + // start a transaction + mysqli_query($link, 'START TRANSACTION'); + + // define the insertion query to add a new record in record table + $query1 = sprintf("INSERT INTO record (ean, title, artist_id, genre, year, price, image) + VALUES ('%s', '%s', %d, '%s', %d, %f, '%s')", $ean, $title, $artist_id, $genre, $year, $price, $image); + + // define the insertion query to add a new record in inventory table + $query2 = sprintf("INSERT INTO inventory (stock, record_ean) + VALUES (%d, '%s')", $stock, $ean); + + // check if either of the queries failed (returned false) + if (!mysqli_query($link, $query1) or !mysqli_query($link, $query2)) { + echo mysqli_error($link); + mysqli_rollback($link); // if so, rollback transaction + } else { + mysqli_commit($link); // else, commit transaction + $content .= "Record successfully added to database."; + } + + + + } + + // ------- END form processing code... ------- + + // output the html + echo($content); + +?> diff --git a/week-13/admin/views/artist.php b/week-13/admin/views/artist.php new file mode 100644 index 0000000000000000000000000000000000000000..ea371d7e2a7a6057ea88edcd8afe2edd4020a582 --- /dev/null +++ b/week-13/admin/views/artist.php @@ -0,0 +1,68 @@ +<?php + +// check if id parameter was not set in query string +if (!isset($_GET['id'])) { + + // define $content with suitable message + $content = "<h1>I don't know which artist you're looking for...</h1>"; + +} else { // id was set, so carry on... + + // define $artist_id variable and assign value of id parameter + $artist_id = $_GET['id']; + + // fetch record titles for artist with id matching $artist_id + $sql = "SELECT r.title, r.year, r.price, a.first_name, a.last_name + FROM record r + INNER JOIN artist a + ON r.artist_id=a.id + WHERE a.id=".$artist_id." + ORDER BY year ASC"; + + $result = mysqli_query($link, $sql); + + // check query returned a result + if ($result === false) { + echo mysqli_error($link); + } else { + + // define a row counter + $i = 0; + + // fetch associative array + while ($row = mysqli_fetch_assoc($result)) { + + // do this if we are on first row + if ($i == 0) { + + // initialise $content string, assigning it a page header + $content = "<h1>".$row['first_name']." ".$row['last_name']." Records</h1>"; + // append $content string with table definition + $content .= "<table border='1'><tbody>"; + + } + + // append table rows to $content string + $content .= "<tr>"; + $content .= "<td>".$row['title']."</td>"; + $content .= "<td>".$row['year']."</td>"; + $content .= "<td>£".$row['price']."</td>"; + $content .= "</tr>"; + + // increment the row counter + $i++; + + } + + // append $content string with closing table tags + $content .= "</tbody></table>"; + + // free result set + mysqli_free_result($result); + } +} + +// output the content HTML +echo $content; + +?> diff --git a/week-13/admin/views/home.php b/week-13/admin/views/home.php new file mode 100644 index 0000000000000000000000000000000000000000..dc1ed44ecb479e1c621c9798b39d42e025002d21 --- /dev/null +++ b/week-13/admin/views/home.php @@ -0,0 +1,10 @@ +<?php + +// create variable for content HTML +$content = "<h1>Welcome to Goldsmith's Record Store</h1>"; +$content .= "<p>Follow the links above to browse the store.</p>"; + +// output the content HTML +echo $content; + +?> diff --git a/week-13/admin/views/login.php b/week-13/admin/views/login.php new file mode 100644 index 0000000000000000000000000000000000000000..f1cd3e33dda00301c6ec8757d98b55321df5ebb5 --- /dev/null +++ b/week-13/admin/views/login.php @@ -0,0 +1,51 @@ +<? +session_start(); +require_once '../../includes/db_connect.php'; +function printform(){ + print "<form action='login.php' method='POST'> + <p><label>username <input type='text' name='username'></label><p> + <p><label>password <input type='password' name='password'></label><p> + <p><input type='submit' name='submit' value='login'><p>"; +} + +$message=""; + +if ($_SERVER['REQUEST_METHOD'] == 'POST'){ + + $username = mysqli_real_escape_string($link, trim(strip_tags($_POST['username']))); + $password = mysqli_real_escape_string($link, trim(strip_tags($_POST['password']))); + + + if ((!empty($username)) && (!empty($password))){ + + $q = "select * from users where name ='$username' and password = SHA('$password')"; + $r = mysqli_query($link, $q); + if (mysqli_affected_rows($link) == 1){ + $row = mysqli_fetch_array($r); + $_SESSION['username'] = $username; + $_SESSION['user_id'] = $row['user_id']; + header('Location: http://localhost/term2labs-dan/week-13/admin/index.php'); + } else { + $message = $message."Login unsuccessful: please try again </br>"; + } + } + if (empty($username)) { + $message = $message."Please include a username </br>"; + } + if (empty($password)) { + $message = $message."Please include a password </br>"; + } + +} + +require_once '../../templates/header.html'; + +//if (!empty($message)){ + print "<p class='error'>".$message."</p>"; +//} +printform(); + + + +require_once '../../templates/footer.html'; +?> diff --git a/week-13/admin/views/logout.php b/week-13/admin/views/logout.php new file mode 100644 index 0000000000000000000000000000000000000000..d606c375ebb0ad9837ff3ced2ba581befc57dcb6 --- /dev/null +++ b/week-13/admin/views/logout.php @@ -0,0 +1,7 @@ +<? +session_start(); + +session_destroy(); +header('Location: http://localhost/term2labs-dan/week-13/index.php'); +?> + diff --git a/week-13/admin/views/navigation.html b/week-13/admin/views/navigation.html new file mode 100644 index 0000000000000000000000000000000000000000..2990306c990239618e2c0f40c07a06a67ebd03df --- /dev/null +++ b/week-13/admin/views/navigation.html @@ -0,0 +1,10 @@ +<nav> + <ul> + <li><a href="?page=home" title="home">Home</a></li> + <li><a href="?page=record" title="records">Records</a></li> + <li><a href="?page=search" title="search">Search</a></li> + <li><a href="?page=orders" title="orders">Orders</a></li> + <li><a href="?page=add-record" title="add record">Add record</a></li> + <li><a href="?page=logout" title="logout">Logout</a></li> + </ul> +</nav> diff --git a/week-13/admin/views/order.php b/week-13/admin/views/order.php new file mode 100644 index 0000000000000000000000000000000000000000..0f81c631d898204086a592a060e6341c59a16f20 --- /dev/null +++ b/week-13/admin/views/order.php @@ -0,0 +1,67 @@ +<?php + +// check the order_id parameter has been set in the URL +if (isset($_GET['order_id'])) +{ + $order_id = $_GET['order_id']; +} else { + $order_id = -1; // if not, set to an implausible value +} + +// fetch order details associated with current order id +$sql = "SELECT r.ean, r.title, ol.quantity, ol.transaction_id, r.price + FROM record r + INNER JOIN orderline ol + ON ol.record_ean=r.ean + WHERE ol.transaction_id=".$order_id; +$result = mysqli_query($link, $sql); + +// check query returned a result +if ($result === false) { + echo mysqli_error($link); +} else { + + // Find the number of rows returned + $num_rows = mysqli_num_rows($result); + + // Check it's not 0 + if ($num_rows == 0) { + $content = "<h1>Order not found</h1>"; + } else { + // create variable for content HTML + $content = "<h1>Order ".$order_id."</h1>"; + $content .= "<table border='1'>"; + $content .= "<thead><tr> + <th>EAN</th> + <th>Title</th> + <th>Quantity</th> + <th>Price</th> + <th>Total</th> + </tr></thead>"; + $content .= "<tbody>"; + // initialise total order price to 0 + $total = 0.00; + // fetch associative array + while ($row = mysqli_fetch_assoc($result)) { + $subtotal = $row['quantity'] * $row['price']; + $total = $total + $subtotal; + $content .= "<tr>"; + $content .= "<td>".$row['ean']."</td>"; + $content .= "<td>".$row['title']."</td>"; + $content .= "<td>".$row['quantity']."</td>"; + $content .= "<td>£".$row['price']."</td>"; + $content .= "<td>£".$subtotal."</td>"; + $content .= "</tr>"; + } + $content .= "<tr><td colspan=4><b>TOTAL</b><td><b>£".$total."</b></td></tr>"; + $content .= "</tbody></table>"; + // free result set + mysqli_free_result($result); + + } +} + +// output the content HTML +echo $content; + +?> diff --git a/week-13/admin/views/orders.php b/week-13/admin/views/orders.php new file mode 100644 index 0000000000000000000000000000000000000000..d1228914e88edccc204d29b7380dabe43fd36aa7 --- /dev/null +++ b/week-13/admin/views/orders.php @@ -0,0 +1,40 @@ +<?php + +// initialise string variable for content HTML +$content = "<h1>Orders</h1>"; + +// fetch all transactions (orders) and group by customer id +$sql = "SELECT id, customer_id FROM transaction + ORDER BY customer_id"; +$result = mysqli_query($link, $sql); + +// check query returned a result +if ($result === false) +{ + echo mysqli_error($link); +} else { + $num_rows = mysqli_num_rows($result); + if ($num_rows > 0) + { + $content .= "<table border='1'>"; + $content .= "<thead><tr><th>Order ID</th><th>Customer ID</th></tr></thead>"; + $content .= "<tbody>"; + // fetch each row in result set as an associative array + while ($row = mysqli_fetch_assoc($result)) { + $content .= "<tr>"; + $content .= "<td><a href=\"?page=order&order_id=".$row['id']."\">".$row['id']."</a></td>"; + $content .= "<td>".$row['customer_id']."</td>"; + $content .= "</tr>"; + } + $content .= "</tbody></table>"; + } else { + $content .= "<p>There are no orders to display.</p>"; + } + // free result set + mysqli_free_result($result); +} + +// output the content HTML +echo $content; + +?> diff --git a/week-13/admin/views/record.php b/week-13/admin/views/record.php new file mode 100644 index 0000000000000000000000000000000000000000..cdeaff20279d9d18e0f21feb8264051800449340 --- /dev/null +++ b/week-13/admin/views/record.php @@ -0,0 +1,43 @@ +<?php + +// create variable for content HTML +$content = "<h1>Records</h1>"; +$content .= "<p>You are now viewing all records in the database.</p>"; + +// fetch records as a result set +$sql = "SELECT r.title, r.ean, a.first_name, a.last_name, r.genre, r.price, r.image, i.stock, a.id + FROM record r + INNER JOIN artist a + ON r.artist_id=a.id + INNER JOIN inventory i + ON r.ean=i.record_ean + ORDER BY r.title, r.price DESC"; +$result = mysqli_query($link, $sql); + +// check query returned a result +if ($result === false) { + echo mysqli_error($link); +} else { + $content .= "<table border='1'>"; + $content .= "<thead><tr><th>Title</th><th>Artist</th><th>Genre</th><th>Price</th><th>Stock</th></tr></thead>"; + $content .= "<tbody>"; + // fetch associative array + while ($row = mysqli_fetch_assoc($result)) { + $content .= "<tr>"; + $content .= "<td>".$row['title']."</td>"; + $content .= "<td><a href='?page=artist&id=".$row['id']."'>".$row['first_name']." ".$row['last_name']."</a></td>"; + $content .= "<td>".$row['genre']."</td>"; + $content .= "<td>".$row['price']."</td>"; + $content .= "<td>".$row['stock']."</td>"; + $content .= "<td><img src='../".$row['image']."' style='height: 100px;' /></td>"; + $content .= "</tr>"; + } + $content .= "</tbody></table>"; + // free result set + mysqli_free_result($result); +} + +// output the content HTML +echo $content; + +?> diff --git a/week-13/admin/views/search.php b/week-13/admin/views/search.php new file mode 100644 index 0000000000000000000000000000000000000000..942e783b49072659b6fceeeadb7c6f25e457f984 --- /dev/null +++ b/week-13/admin/views/search.php @@ -0,0 +1,90 @@ +<? +$content = "<h1>Search</h1>"; + +// define a variable with path to this script which will process form +$action = htmlspecialchars($_SERVER["PHP_SELF"]."?page=search"); + +// define the search form +$form_html = "<form method='post' action='". $action ."'> + <label for='usersearch'>search the record store</label><br /> + <input type='text' id='usersearch' name='usersearch' /><br /> + <input type='submit' name='submit' value='Submit' /> + </form>"; + +// append form HTML to content string +$content .= $form_html; + +// ------- START form processing code... ------- + +// check if there was a POST request +if ($_SERVER["REQUEST_METHOD"] == "POST") { + +// $sort = clean_input($_GET['sort']); + $user_search = clean_input($_POST['usersearch']); + $clean_search = str_replace(',',' ',$user_search); + $search_words = explode(' ',$clean_search); + $final_search_words = array(); + if (count($search_words > 0)){ + foreach ($search_words as $word) { + if (!empty($word)) { + $final_search_words[] = $word; + } + } + } + foreach ($final_search_words as $word) { + $where_list[] = "r.title like '%$word%'"; + } + $where_clause = implode(' OR ', $where_list); + +echo "where clause = " . $where_clause."<br />"; + + // Query to get the results + $sql = "SELECT r.title, r.ean, a.first_name, a.last_name, r.genre, r.price, r.image, i.stock, a.id + FROM record r + INNER JOIN artist a + ON r.artist_id=a.id + INNER JOIN inventory i + ON r.ean=i.record_ean + WHERE $where_clause + ORDER BY r.title, r.price DESC"; +//echo $sql."<br />"; + + // Start generating the table of results + echo '<table border="0" cellpadding="2">'; + + // Generate the search result headings + echo '<tr class="heading">'; + echo '<td>Job Title</td><td>Description</td><td>State</td><td>Date Posted</td>'; + echo '</tr>'; + + +$result = mysqli_query($link, $sql); + + // check query returned a result + if ($result === false) { + echo mysqli_error($link); + } else { + $content .= "<table border='1'>"; + $content .= "<thead><tr><th>Title</th><th>Artist</th><th>Genre</th><th>Price</th><th>Stock</th></tr></thead>"; + $content .= "<tbody>"; + // fetch associative array + while ($row = mysqli_fetch_assoc($result)) { + $content .= "<tr>"; + $content .= "<td>".$row['title']."</td>"; + $content .= "<td><a href='?page=artist&id=".$row['id']."'>".$row['first_name']." ".$row['last_name']."</a></td>"; + $content .= "<td>".$row['genre']."</td>"; + $content .= "<td>".$row['price']."</td>"; + $content .= "<td>".$row['stock']."</td>"; + $content .= "<td><img src='../".$row['image']."' style='height: 100px;' /></td>"; + $content .= "</tr>"; + } + $content .= "</tbody></table>"; + // free result set + mysqli_free_result($result); + } +} + +// output the content HTML +echo $content; + +?> diff --git a/week-13/includes/db_connect.php b/week-13/includes/db_connect.php new file mode 100644 index 0000000000000000000000000000000000000000..53c5fb94ab76b4ae3840501948dfe079b2f35296 --- /dev/null +++ b/week-13/includes/db_connect.php @@ -0,0 +1,18 @@ +<?php + +/* Open a new connection to the MySQL server */ + +/* connect to the database */ +$link = mysqli_connect( + 'localhost', + 'recordstoreuser', + 'recordstorepwd', + 'recordstore' +); + +/* check connection succeeded */ +if (mysqli_connect_errno()) { + echo "Failed to connect to MySQL: " . mysqli_connect_error(); +} + +?> diff --git a/week-13/includes/functions.php b/week-13/includes/functions.php new file mode 100644 index 0000000000000000000000000000000000000000..9a4c18ec2c4c693cbbe246e9d97121b19bf39cd9 --- /dev/null +++ b/week-13/includes/functions.php @@ -0,0 +1,60 @@ +<? + +function is_logged_in(){ + if (isset($_SESSION['username'])){ +// print session_name()."<br />"; +// print $_COOKIE[session_name()]; + return true; + } +/* } else { + return false; + } +*/ +} + + +function build_query ($user_search, $sort) { + $clean_search = str_replace(',',' ',$user_search); + $search_words = explode(' ',$clean_search); + $final_search_words = array(); + if (count($search_words > 0)){ + foreach ($search_words as $word) { + if (!empty($word)) { + $final_search_words[] = $word; + } + } + } + $where_list = array(); + foreach ($final_search_words as $word) { + $where_list[] = "r.title like '%$word%'"; + $where_list[] = "a.first_name like '%$word%'"; + $where_list[] = "a.last_name like '%$word%'"; + } + $where_clause = implode(' OR ', $where_list); + +//echo "where clause = " . $where_clause."<br />"; + + // Query to get the results + $sql = "SELECT r.title, r.ean, a.first_name, a.last_name, r.genre, r.price, r.image, i.stock, a.id + FROM record r + INNER JOIN artist a + ON r.artist_id=a.id + INNER JOIN inventory i + ON r.ean=i.record_ean + WHERE $where_clause"; + +//add the sort to the search, if set + switch ($sort) { + case 1: + $sql .= " ORDER BY r.title"; + break; + case 2: + $sql .= " ORDER BY a.last_name"; + break; + default: + } + + return $sql; +} + +?> diff --git a/week-13/index.php b/week-13/index.php new file mode 100644 index 0000000000000000000000000000000000000000..baae4a2cc2ed867817a28ee0449a870793466335 --- /dev/null +++ b/week-13/index.php @@ -0,0 +1,65 @@ +<?php + +//error_reporting(0); +error_reporting (E_ALL | E_STRICT); // Show all possible problems! + +// connect to the database +require('includes/db_connect.php'); +require('includes/functions.php'); + +// define a function to sanitise user input (this would ideally be in includes folder) +function clean_input($data) { + $data = trim($data); // strips unnecessary characters from beginning/end + $data = stripslashes($data); // remove backslashes + $data = htmlspecialchars($data); // replace special characters with HTML entities + return $data; +} + +// include the header HTML +include('templates/header.html'); + +// include the navigation HTML +include('templates/navigation.html'); + +// get the page id from the URL +// if no parameter detected... +if (!isset($_GET['page'])) { + $id = 'home'; // display home page +} else { + $id = $_GET['page']; // else requested page +} + +// use switch to determine which view to serve based on $id +switch ($id) { +case 'home' : + include 'views/home.php'; + break; +case 'record' : + include 'views/record.php'; + break; +case 'artist' : + include 'views/artist.php'; + break; +case 'orders' : + include 'views/orders.php'; + break; +case 'order' : + include 'views/order.php'; + break; +case 'add-record' : + include 'views/add-record.php'; + break; +case 'search' : + include 'views/search.php'; + break; +default : + include 'views/404.php'; +} + +// close the connection to the database +mysqli_close($link); + +// include the footer HTML +include('templates/footer.html'); + +?> diff --git a/week-13/sql/dummy_data.sql b/week-13/sql/dummy_data.sql new file mode 100644 index 0000000000000000000000000000000000000000..7d0580104297aa0ad65f6d70c33601e128b685d4 --- /dev/null +++ b/week-13/sql/dummy_data.sql @@ -0,0 +1,67 @@ +/* Note that, because foreign key values are being +inserted manually, tables must be recreated before running +this code in order to reset AUTO_INCREMENT */ + +/* Statement to insert some records in the artist table */ +INSERT INTO artist (id, first_name, last_name) +VALUES +(NULL, 'Bob', 'Marley'), +(NULL, 'Peter', 'Tosh'), +(NULL, 'Burning', 'Spear'), +(NULL, 'Alton', 'Ellis'), +(NULL, 'Gregory', 'Issacs'), +(NULL, 'Desmond', 'Dekker'); + +INSERT INTO record (ean, title, artist_id, genre, year, price) +VALUES +('00562056', 'Soul Rebel', 1, 'Reggae', 1970, 25.99 ), +('50264967', 'Catch A Fire', 1, 'Reggae', 1973, 25.99 ), +('00748396', 'Natty Dread', 1, 'Reggae', 1974, 20.99 ), +('00495739', 'Babylon By Bus', 1, 'Reggae', 1978, 24.99 ), +('00738432', 'Legalize It', 2, 'Reggae', 1976, 22.99 ), +('50847583', 'Bush Doctor', 2, 'Reggae', 1978, 20.99 ), +('30748743', 'Marcus Garvey', 3, 'Reggae', 1975, 24.99 ), +('50856384', 'Night Nurse', 5, 'Reggae', 1982, 17.99 ), +('50264972', 'Mr Issacs', 5, 'Reggae', 1982, 9.99 ), +('00649573', 'Black and Dekker', 6, 'Reggae', 1980, 19.99 ), +('00625485', 'Sunday Coming', 4, 'Reggae', 1970, 15.99 ); + +INSERT INTO customer (id, first_name, last_name, email_address, address_1, address_2, postcode) +VALUES +(NULL, 'John', 'Smith', 'john@smith.com', '1 Fake Street', 'London', 'SE3 5RD'), +(NULL, 'Sukie', 'Bapswent', 's.baps@gmail.com', '64 The Terrace', 'Whitby', 'YO65 3TR'), +(NULL, 'John', 'Thumb', 'jthumb@gmail.com', '25 Fantasy Grove', 'Brighton', 'BR2 6LV'); + +INSERT INTO transaction (id, customer_id, delivery_method, dt_date) +VALUES +(NULL, 1, 2, '2015-07-01 14:34:58'), +(NULL, 1, 2, '2015-04-01 11:22:35'), +(NULL, 3, 1, '2015-04-01 19:47:03'), +(NULL, 2, 1, '2015-05-11 22:01:19'); + +INSERT INTO orderline (id, transaction_id, record_ean, quantity) +VALUES +(NULL, 1, '00562056', 1), +(NULL, 1, '00495739', 1), +(NULL, 2, '00649573', 2), +(NULL, 2, '00495739', 1), +(NULL, 3, '00738432', 2), +(NULL, 3, '00562056', 1), +(NULL, 3, '50856384', 3), +(NULL, 3, '00495739', 1), +(NULL, 4, '00625485', 1), +(NULL, 4, '00562056', 2); + +INSERT INTO inventory (stock, record_ean) +VALUES +(25, '00562056'), +(18, '50264967'), +(15, '00748396'), +(20, '00495739'), +(10, '00738432'), +(7, '50847583'), +(3, '30748743'), +(34, '50856384'), +(22, '50264972'), +(15, '00649573'), +(12, '00625485'); diff --git a/week-13/sql/practice_queries.sql b/week-13/sql/practice_queries.sql new file mode 100644 index 0000000000000000000000000000000000000000..ebb0dffa0b828a6072ed93cdede777c89ddd168f --- /dev/null +++ b/week-13/sql/practice_queries.sql @@ -0,0 +1,9 @@ +/* Simple query +Fetch first_name and last_name columns from artist table */ +SELECT first_name, last_name FROM artist; + +/* Query with filters +Fetches titles from record table where year is 1973 and genre is Reggae */ +SELECT title FROM record +WHERE year = 1973 +AND genre = "Reggae"; \ No newline at end of file diff --git a/week-13/sql/record-store.sql b/week-13/sql/record-store.sql new file mode 100644 index 0000000000000000000000000000000000000000..971708804df2996481388ffecf24895dd9047bb8 --- /dev/null +++ b/week-13/sql/record-store.sql @@ -0,0 +1,71 @@ +/* Make sure tables don't exist before creation */ +DROP TABLE IF EXISTS inventory, orderline, transaction, customer, record, artist; + +/* Define table for storing artists */ +CREATE TABLE artist ( + id INT AUTO_INCREMENT, + first_name VARCHAR(50), + last_name VARCHAR(50), + PRIMARY KEY(id) +) ENGINE=InnoDB; + +/* Define table for storing records (products) */ +CREATE TABLE record ( + ean CHAR(8) NOT NULL, + title VARCHAR(50) NOT NULL, + artist_id INT, + genre VARCHAR(50), + year YEAR(4), + price DECIMAL(10, 2) unsigned NOT NULL, + PRIMARY KEY (ean), + FOREIGN KEY (artist_id) + REFERENCES artist (id) + ON DELETE CASCADE +) ENGINE=InnoDB; + +/* Define table for storing customers */ +CREATE TABLE customer ( + id INT AUTO_INCREMENT, + first_name VARCHAR(50) NOT NULL, + last_name VARCHAR(50) NOT NULL, + email_address VARCHAR(50) NOT NULL, + address_1 VARCHAR(50) NOT NULL, + address_2 VARCHAR(50), + postcode VARCHAR(10) NOT NULL, + PRIMARY KEY (id) +) ENGINE=InnoDB; + +/* Define table for storing orders */ +CREATE TABLE transaction ( + id INT AUTO_INCREMENT, + customer_id INT NOT NULL, + delivery_method INT, + dt_date DATETIME, + PRIMARY KEY (id), + FOREIGN KEY (customer_id) + REFERENCES customer(id) +) ENGINE=InnoDB; + +/* Define table for storing orderlines */ +CREATE TABLE orderline ( + id INT AUTO_INCREMENT, + transaction_id INT, + record_ean CHAR(8), + quantity INT NOT NULL, + PRIMARY KEY (id), + FOREIGN KEY (transaction_id) + REFERENCES transaction(id), + FOREIGN KEY (record_ean) + REFERENCES record(ean) + ON UPDATE CASCADE + ON DELETE CASCADE +) ENGINE=InnoDB; + +/* Define table for inventory */ +CREATE TABLE inventory ( + stock INT unsigned DEFAULT 0, + record_ean CHAR(8), + PRIMARY KEY (stock, record_ean), + FOREIGN KEY (record_ean) + REFERENCES record (ean) +) ENGINE=InnoDB; diff --git a/week-13/sql/recordstore-dump.sql b/week-13/sql/recordstore-dump.sql new file mode 100644 index 0000000000000000000000000000000000000000..f9dc7c87b19c8a9d855abce62050f3091f0d5ee5 --- /dev/null +++ b/week-13/sql/recordstore-dump.sql @@ -0,0 +1,196 @@ +-- MySQL dump 10.13 Distrib 5.6.26, for Linux (x86_64) +-- +-- Host: localhost Database: recordstore +-- ------------------------------------------------------ +-- Server version 5.6.26 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `artist` +-- + +DROP TABLE IF EXISTS `artist`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `artist` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `first_name` varchar(50) DEFAULT NULL, + `last_name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `artist` +-- + +LOCK TABLES `artist` WRITE; +/*!40000 ALTER TABLE `artist` DISABLE KEYS */; +INSERT INTO `artist` VALUES (1,'Bob','Marley'),(2,'Peter','Tosh'),(3,'Burning','Spear'),(4,'Alton','Ellis'),(5,'Gregory','Issacs'),(6,'Desmond','Dekker'); +/*!40000 ALTER TABLE `artist` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `customer` +-- + +DROP TABLE IF EXISTS `customer`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `customer` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `first_name` varchar(50) NOT NULL, + `last_name` varchar(50) NOT NULL, + `email_address` varchar(50) NOT NULL, + `address_1` varchar(50) NOT NULL, + `address_2` varchar(50) DEFAULT NULL, + `postcode` varchar(10) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `customer` +-- + +LOCK TABLES `customer` WRITE; +/*!40000 ALTER TABLE `customer` DISABLE KEYS */; +INSERT INTO `customer` VALUES (1,'John','Smith','john@smith.com','1 Fake Street','London','SE3 5RD'),(2,'Sukie','Bapswent','s.baps@gmail.com','64 The Terrace','Whitby','YO65 3TR'),(3,'John','Thumb','jthumb@gmail.com','25 Fantasy Grove','Brighton','BR2 6LV'); +/*!40000 ALTER TABLE `customer` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `inventory` +-- + +DROP TABLE IF EXISTS `inventory`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `inventory` ( + `stock` int(10) unsigned NOT NULL DEFAULT '0', + `record_ean` char(8) NOT NULL DEFAULT '', + PRIMARY KEY (`stock`,`record_ean`), + KEY `record_ean` (`record_ean`), + CONSTRAINT `inventory_ibfk_1` FOREIGN KEY (`record_ean`) REFERENCES `record` (`ean`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `inventory` +-- + +LOCK TABLES `inventory` WRITE; +/*!40000 ALTER TABLE `inventory` DISABLE KEYS */; +INSERT INTO `inventory` VALUES (20,'00495739'),(25,'00562056'),(12,'00625485'),(15,'00649573'),(10,'00738432'),(15,'00748396'),(1,'1010010'),(5,'12121212'),(2,'131313'),(3,'30748743'),(18,'50264967'),(22,'50264972'),(7,'50847583'),(34,'50856384'); +/*!40000 ALTER TABLE `inventory` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `orderline` +-- + +DROP TABLE IF EXISTS `orderline`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `orderline` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `transaction_id` int(11) DEFAULT NULL, + `record_ean` char(8) DEFAULT NULL, + `quantity` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `transaction_id` (`transaction_id`), + KEY `record_ean` (`record_ean`), + CONSTRAINT `orderline_ibfk_1` FOREIGN KEY (`transaction_id`) REFERENCES `transaction` (`id`), + CONSTRAINT `orderline_ibfk_2` FOREIGN KEY (`record_ean`) REFERENCES `record` (`ean`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `orderline` +-- + +LOCK TABLES `orderline` WRITE; +/*!40000 ALTER TABLE `orderline` DISABLE KEYS */; +INSERT INTO `orderline` VALUES (1,1,'00562056',1),(2,1,'00495739',1),(3,2,'00649573',2),(4,2,'00495739',1),(5,3,'00738432',2),(6,3,'00562056',1),(7,3,'50856384',3),(8,3,'00495739',1),(9,4,'00625485',1),(10,4,'00562056',2); +/*!40000 ALTER TABLE `orderline` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `record` +-- + +DROP TABLE IF EXISTS `record`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `record` ( + `ean` char(8) NOT NULL, + `title` varchar(50) NOT NULL, + `artist_id` int(11) DEFAULT NULL, + `genre` varchar(50) DEFAULT NULL, + `year` year(4) DEFAULT NULL, + `price` decimal(10,2) unsigned NOT NULL, + `image` varchar(64) DEFAULT NULL, + PRIMARY KEY (`ean`), + KEY `artist_id` (`artist_id`), + CONSTRAINT `record_ibfk_1` FOREIGN KEY (`artist_id`) REFERENCES `artist` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `record` +-- + +LOCK TABLES `record` WRITE; +/*!40000 ALTER TABLE `record` DISABLE KEYS */; +INSERT INTO `record` VALUES ('00495739','Babylon By Bus',1,'Reggae',1978,24.99,NULL),('00562056','Soul Rebel',1,'Reggae',1970,25.99,NULL),('00625485','Sunday Coming',4,'Reggae',1970,15.99,NULL),('00649573','Black and Dekker',6,'Reggae',1980,19.99,NULL),('00738432','Legalize It',2,'Reggae',1976,22.99,NULL),('00748396','Natty Dread',1,'Reggae',1974,20.99,NULL),('1010010','A test',6,'testy',2000,20.00,'uploads/2009-a32-08-05-adorno-b.jpg'),('12121212','Dek Stop',6,'2 tone',1978,10.99,NULL),('131313','blahblah',4,'hip hop',2011,9.99,NULL),('30748743','Marcus Garvey',3,'Reggae',1975,24.99,NULL),('50264967','Catch A Fire',1,'Reggae',1973,25.99,NULL),('50264972','Mr Issacs',5,'Reggae',1982,9.99,NULL),('50847583','Bush Doctor',2,'Reggae',1978,20.99,NULL),('50856384','Night Nurse',5,'Reggae',1982,17.99,NULL); +/*!40000 ALTER TABLE `record` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `transaction` +-- + +DROP TABLE IF EXISTS `transaction`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `transaction` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `customer_id` int(11) NOT NULL, + `delivery_method` int(11) DEFAULT NULL, + `dt_date` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `customer_id` (`customer_id`), + CONSTRAINT `transaction_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `transaction` +-- + +LOCK TABLES `transaction` WRITE; +/*!40000 ALTER TABLE `transaction` DISABLE KEYS */; +INSERT INTO `transaction` VALUES (1,1,2,'2015-07-01 14:34:58'),(2,1,2,'2015-04-01 11:22:35'),(3,3,1,'2015-04-01 19:47:03'),(4,2,1,'2015-05-11 22:01:19'); +/*!40000 ALTER TABLE `transaction` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2016-01-19 18:54:19 diff --git a/week-13/sql/recordstore-dump2.sql b/week-13/sql/recordstore-dump2.sql new file mode 100644 index 0000000000000000000000000000000000000000..f46498bb1e7c4897a468112326a0b7475b7c3ac9 --- /dev/null +++ b/week-13/sql/recordstore-dump2.sql @@ -0,0 +1,196 @@ +-- MySQL dump 10.13 Distrib 5.6.26, for Linux (x86_64) +-- +-- Host: localhost Database: recordstore +-- ------------------------------------------------------ +-- Server version 5.6.26 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `artist` +-- + +DROP TABLE IF EXISTS `artist`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `artist` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `first_name` varchar(50) DEFAULT NULL, + `last_name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `artist` +-- + +LOCK TABLES `artist` WRITE; +/*!40000 ALTER TABLE `artist` DISABLE KEYS */; +INSERT INTO `artist` VALUES (1,'Bob','Marley'),(2,'Peter','Tosh'),(3,'Burning','Spear'),(4,'Alton','Ellis'),(5,'Gregory','Issacs'),(6,'Desmond','Dekker'); +/*!40000 ALTER TABLE `artist` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `customer` +-- + +DROP TABLE IF EXISTS `customer`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `customer` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `first_name` varchar(50) NOT NULL, + `last_name` varchar(50) NOT NULL, + `email_address` varchar(50) NOT NULL, + `address_1` varchar(50) NOT NULL, + `address_2` varchar(50) DEFAULT NULL, + `postcode` varchar(10) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `customer` +-- + +LOCK TABLES `customer` WRITE; +/*!40000 ALTER TABLE `customer` DISABLE KEYS */; +INSERT INTO `customer` VALUES (1,'John','Smith','john@smith.com','1 Fake Street','London','SE3 5RD'),(2,'Sukie','Bapswent','s.baps@gmail.com','64 The Terrace','Whitby','YO65 3TR'),(3,'John','Thumb','jthumb@gmail.com','25 Fantasy Grove','Brighton','BR2 6LV'); +/*!40000 ALTER TABLE `customer` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `inventory` +-- + +DROP TABLE IF EXISTS `inventory`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `inventory` ( + `stock` int(10) unsigned NOT NULL DEFAULT '0', + `record_ean` char(8) NOT NULL DEFAULT '', + PRIMARY KEY (`stock`,`record_ean`), + KEY `record_ean` (`record_ean`), + CONSTRAINT `inventory_ibfk_1` FOREIGN KEY (`record_ean`) REFERENCES `record` (`ean`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `inventory` +-- + +LOCK TABLES `inventory` WRITE; +/*!40000 ALTER TABLE `inventory` DISABLE KEYS */; +INSERT INTO `inventory` VALUES (20,'00495739'),(25,'00562056'),(12,'00625485'),(15,'00649573'),(10,'00738432'),(15,'00748396'),(1,'1000000'),(1,'1010010'),(5,'12121212'),(2,'131313'),(3,'30748743'),(18,'50264967'),(22,'50264972'),(7,'50847583'),(34,'50856384'),(2,'985'); +/*!40000 ALTER TABLE `inventory` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `orderline` +-- + +DROP TABLE IF EXISTS `orderline`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `orderline` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `transaction_id` int(11) DEFAULT NULL, + `record_ean` char(8) DEFAULT NULL, + `quantity` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `transaction_id` (`transaction_id`), + KEY `record_ean` (`record_ean`), + CONSTRAINT `orderline_ibfk_1` FOREIGN KEY (`transaction_id`) REFERENCES `transaction` (`id`), + CONSTRAINT `orderline_ibfk_2` FOREIGN KEY (`record_ean`) REFERENCES `record` (`ean`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `orderline` +-- + +LOCK TABLES `orderline` WRITE; +/*!40000 ALTER TABLE `orderline` DISABLE KEYS */; +INSERT INTO `orderline` VALUES (1,1,'00562056',1),(2,1,'00495739',1),(3,2,'00649573',2),(4,2,'00495739',1),(5,3,'00738432',2),(6,3,'00562056',1),(7,3,'50856384',3),(8,3,'00495739',1),(9,4,'00625485',1),(10,4,'00562056',2); +/*!40000 ALTER TABLE `orderline` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `record` +-- + +DROP TABLE IF EXISTS `record`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `record` ( + `ean` char(8) NOT NULL, + `title` varchar(50) NOT NULL, + `artist_id` int(11) DEFAULT NULL, + `genre` varchar(50) DEFAULT NULL, + `year` year(4) DEFAULT NULL, + `price` decimal(10,2) unsigned NOT NULL, + `image` varchar(64) DEFAULT NULL, + PRIMARY KEY (`ean`), + KEY `artist_id` (`artist_id`), + CONSTRAINT `record_ibfk_1` FOREIGN KEY (`artist_id`) REFERENCES `artist` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `record` +-- + +LOCK TABLES `record` WRITE; +/*!40000 ALTER TABLE `record` DISABLE KEYS */; +INSERT INTO `record` VALUES ('00495739','Babylon By Bus',1,'Reggae',1978,24.99,NULL),('00562056','Soul Rebel',1,'Reggae',1970,25.99,NULL),('00625485','Sunday Coming',4,'Reggae',1970,15.99,NULL),('00649573','Black and Dekker',6,'Reggae',1980,19.99,NULL),('00738432','Legalize It',2,'Reggae',1976,22.99,NULL),('00748396','Natty Dread',1,'Reggae',1974,20.99,NULL),('1000000','B test',5,'funk',2016,26.00,'uploads/avatar 1.jpg'),('1010010','A test',6,'testy',2000,20.00,'uploads/2009-a32-08-05-adorno-b.jpg'),('12121212','Dek Stop',6,'2 tone',1978,10.99,NULL),('131313','blahblah',4,'hip hop',2011,9.99,NULL),('30748743','Marcus Garvey',3,'Reggae',1975,24.99,NULL),('50264967','Catch A Fire',1,'Reggae',1973,25.99,NULL),('50264972','Mr Issacs',5,'Reggae',1982,9.99,NULL),('50847583','Bush Doctor',2,'Reggae',1978,20.99,NULL),('50856384','Night Nurse',5,'Reggae',1982,17.99,NULL),('985','test',6,'test',0000,22.00,'uploads/think of this as a window.jpg'); +/*!40000 ALTER TABLE `record` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `transaction` +-- + +DROP TABLE IF EXISTS `transaction`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `transaction` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `customer_id` int(11) NOT NULL, + `delivery_method` int(11) DEFAULT NULL, + `dt_date` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `customer_id` (`customer_id`), + CONSTRAINT `transaction_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `transaction` +-- + +LOCK TABLES `transaction` WRITE; +/*!40000 ALTER TABLE `transaction` DISABLE KEYS */; +INSERT INTO `transaction` VALUES (1,1,2,'2015-07-01 14:34:58'),(2,1,2,'2015-04-01 11:22:35'),(3,3,1,'2015-04-01 19:47:03'),(4,2,1,'2015-05-11 22:01:19'); +/*!40000 ALTER TABLE `transaction` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2016-01-26 16:55:43 diff --git a/week-13/sql/user-table.sql b/week-13/sql/user-table.sql new file mode 100644 index 0000000000000000000000000000000000000000..d0a426b347739d9e806f843213c5bdfa672b9838 --- /dev/null +++ b/week-13/sql/user-table.sql @@ -0,0 +1,25 @@ +-- +-- Table structure for table `users` +-- + +DROP TABLE IF EXISTS `users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `users` ( + `user_id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + `password` varchar(50) DEFAULT NULL, + PRIMARY KEY (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `users` +-- + +LOCK TABLES `users` WRITE; +/*!40000 ALTER TABLE `users` DISABLE KEYS */; +INSERT INTO `users` VALUES (1,'alice','5f55cff83a8f2f274947745629d3ede299a05bfd'),(2,'bob','b639bbe4c65ae9ea79b4268701e8656a80c95b14'),(3,'cliff','0c0b7dce234a29cf42d72db5420d708ac9251a82'),(4,'dan','4376fd0454dbaf40ba385212c04c0d18319c572b'),(5,'eric','9b2b6e9f988f06e7807694b7903cd7832e154975'),(6,'fabio','782a7facdc65b96b3896f40e43f5b5ec04393b3e'); +/*!40000 ALTER TABLE `users` ENABLE KEYS */; +UNLOCK TABLES; + diff --git a/week-13/templates/footer.html b/week-13/templates/footer.html new file mode 100644 index 0000000000000000000000000000000000000000..2ab5c0d1fc7b0e6c12fb00bf177037f64450298c --- /dev/null +++ b/week-13/templates/footer.html @@ -0,0 +1,2 @@ + </body> +</html> diff --git a/week-13/templates/header.html b/week-13/templates/header.html new file mode 100644 index 0000000000000000000000000000000000000000..fc565541741ccc043bfeb2c6d3f7a39640740dd9 --- /dev/null +++ b/week-13/templates/header.html @@ -0,0 +1,7 @@ +<!DOCTYPE html> +<html> + <head> + <meta charset="UTF-8"> + <title>Record Store</title> + </head> + <body> diff --git a/week-13/templates/navigation.html b/week-13/templates/navigation.html new file mode 100644 index 0000000000000000000000000000000000000000..9f895997e38d4c0abe5b44ef8352910f14f9e8dc --- /dev/null +++ b/week-13/templates/navigation.html @@ -0,0 +1,7 @@ +<nav> + <ul> + <li><a href="?page=home" title="home">Home</a></li> + <li><a href="?page=record" title="records">Records</a></li> + <li><a href="?page=search" title="search">Search</a></li> + </ul> +</nav> diff --git a/week-13/uploads/2009-a32-08-05-adorno-b.jpg b/week-13/uploads/2009-a32-08-05-adorno-b.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4e896284f0a353698a1567dbd60fe9084352102b Binary files /dev/null and b/week-13/uploads/2009-a32-08-05-adorno-b.jpg differ diff --git a/week-13/uploads/avatar 1.jpg b/week-13/uploads/avatar 1.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0f72ed7d3df1b440ca9e8128ce3bf9b495fac37e Binary files /dev/null and b/week-13/uploads/avatar 1.jpg differ diff --git a/week-13/uploads/je-participe.gif b/week-13/uploads/je-participe.gif new file mode 100644 index 0000000000000000000000000000000000000000..91e7b890942debafe2718187d3f0f785b09d25ea Binary files /dev/null and b/week-13/uploads/je-participe.gif differ diff --git a/week-13/uploads/man-ray-iron-A.gif b/week-13/uploads/man-ray-iron-A.gif new file mode 100644 index 0000000000000000000000000000000000000000..127305ad2f453616c0858c28a09f65dc7a57afcf Binary files /dev/null and b/week-13/uploads/man-ray-iron-A.gif differ diff --git a/week-13/uploads/think of this as a window.jpg b/week-13/uploads/think of this as a window.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6974a3771579395769a65c117e46e5887a83f285 Binary files /dev/null and b/week-13/uploads/think of this as a window.jpg differ diff --git a/week-13/views/404.php b/week-13/views/404.php new file mode 100644 index 0000000000000000000000000000000000000000..7ae2fe7434a65afd31bee52d9ef7edb42d0ee2f1 --- /dev/null +++ b/week-13/views/404.php @@ -0,0 +1,10 @@ +<?php + +// create variable for content HTML +$content = "<h1>Page not found</h1>"; +$content .= "<p>Sorry, the page you requested could not be found.</p>"; + +// output the content HTML +echo $content; + +?> diff --git a/week-13/views/add-record-insecure.php b/week-13/views/add-record-insecure.php new file mode 100644 index 0000000000000000000000000000000000000000..841a5078b968ebf2b18cb97286ab6e8f9d03bbfc --- /dev/null +++ b/week-13/views/add-record-insecure.php @@ -0,0 +1,100 @@ +<?php + +$content = "<h1>Add a record</h1>"; + +// define a variable with path to the script which will process form +// -> $_SERVER["PHP_SELF"] is a path to the current script (index.php) +$action = $_SERVER["PHP_SELF"]."?page=add-record"; + +// fetch the artists so that we have access to their names and IDs +$sql = "SELECT id, first_name, last_name + FROM artist + ORDER BY last_name"; + +$result = mysqli_query($link, $sql); + +// check query returned a result +if ($result === false) { + echo mysqli_error($link); +} else { + $options = ""; + // create an option for each artist + while ($row = mysqli_fetch_assoc($result)) { + $options .= "<option value='".$row['id']."'>"; + $options .= $row['first_name']." ".$row['last_name']; + $options .= "</option>"; + } +} + +// define the form HTML (would ideally be in a template) +$form_html = "<form action='".$action."' method='POST'> + <fieldset> + <label for='ean'>EAN (required):</label> + <input type='text' name='ean'/> + </fieldset> + <fieldset> + <label for='title'>Title:</label> + <input type='text' name='title' /> + </fieldset> + <fieldset> + <label for='artist_id'>Artist:</label> + <select name='artist_id'> + + ".$options." + <option value='NULL'>Not listed</option> + </select> + </fieldset> + <fieldset> + <label for='genre'>Genre</label> + <input type='text' name='genre' /> + </fieldset> + <fieldset> + <label for='year'>Year:</label> + <input type='text' name='year' size='5' placeholder='YYYY' /> + </fieldset> + <fieldset> + <label for='price'>Price (£):</label> + <input type='text' name='price' placeholder='00.00' /> + </fieldset> + <button type='submit'>Submit</button> + </form>"; + +// append form HTML to content string +$content .= $form_html; + +// ------- START form processing code... ------- + +// define variables and set to empty values +$title = $artist_id = $price = $year = $genre = ""; + +// check if there was a POST request +if ($_SERVER["REQUEST_METHOD"] == "POST") { + // validate the form data + $ean = $_POST["ean"]; + $title = $_POST["title"]; + $artist_id = $_POST["artist_id"]; + $genre = $_POST["genre"]; + $year = $_POST["year"]; + $price = $_POST["price"]; + + // define the insertion query + $sql = "INSERT INTO record (ean, title, artist_id, genre, year, price) + VALUES ('$ean', '$title', '$artist_id', '$genre', '$year', '$price')"; + + // run the query to insert the data + $result = mysqli_query($link, $sql); + + // check if the query went ok + if ($result === false) { + echo mysqli_error($link); + } else { + $content .= "Record successfully added to database."; + } +} + +// ------- END form processing code... ------- + +// output the html +echo($content); + +?> diff --git a/week-13/views/add-record.php b/week-13/views/add-record.php new file mode 100644 index 0000000000000000000000000000000000000000..b8d556e457bd6c5211695b034c7295984a870291 --- /dev/null +++ b/week-13/views/add-record.php @@ -0,0 +1,174 @@ +<?php + +$content = "<h1>Add a record</h1>"; + +// define a variable with path to the script which will process form +// -> $_SERVER["PHP_SELF"] is a path to the current script (index.php) +// -> htmlspecialchars() is used to replace special characters with HTML entities */ +$action = htmlspecialchars($_SERVER["PHP_SELF"]."?page=add-record"); + +// fetch the artists so that we have access to their names and IDs +$sql = "SELECT id, first_name, last_name + FROM artist + ORDER BY last_name"; + +$result = mysqli_query($link, $sql); + +// check query returned a result +if ($result === false) { + echo mysqli_error($link); +} else { + $options = ""; + // create an option for each artist + while ($row = mysqli_fetch_assoc($result)) { + $options .= "<option value='".$row['id']."'>"; + $options .= $row['first_name']." ".$row['last_name']; + $options .= "</option>"; + } +} + +// define the form HTML (would ideally be in a template) +$form_html = "<form action='".$action."' enctype='multipart/form-data' method='POST'> +<input type='hidden' name='MAX_FILE_SIZE' value='1000000' /> + <fieldset> + <label for='ean'>EAN (required):</label> + <input type='text' name='ean'/> + </fieldset> + <fieldset> + <label for='title'>Title:</label> + <input type='text' name='title' /> + </fieldset> + <fieldset> + <label for='artist_id'>Artist:</label> + <select name='artist_id'> + + ".$options." + <option value='NULL'>Not listed</option> + </select> + </fieldset> + <fieldset> + <label for='genre'>Genre</label> + <input type='text' name='genre' /> + </fieldset> + <fieldset> + <label for='year'>Year:</label> + <input type='text' name='year' size='5' placeholder='YYYY' /> + </fieldset> + <fieldset> + <label for='price'>Price (£):</label> + <input type='text' name='price' placeholder='00.00' /> + </fieldset> + <fieldset> + <label for='price'>Stock:</label> + <input type='text' name='stock' placeholder='0' /> + </fieldset> +<label>image <input type='file' id='image' name='image' /></label><br /> + <button type='submit'>Submit</button> + </form>"; + +// append form HTML to content string +$content .= $form_html; + +// ------- START form processing code... ------- + + +// define variables and set to empty values +$title = $artist_id = $price = $year = $genre = $stock = ""; + +// check if there was a POST request +if ($_SERVER["REQUEST_METHOD"] == "POST") { + // validate the form data + $ean = mysqli_real_escape_string($link, clean_input($_POST["ean"])); + $title = mysqli_real_escape_string($link, clean_input($_POST["title"])); + $artist_id = mysqli_real_escape_string($link, clean_input($_POST["artist_id"])); + $genre = mysqli_real_escape_string($link, clean_input($_POST["genre"])); + $year = mysqli_real_escape_string($link, clean_input($_POST["year"])); + $price = mysqli_real_escape_string($link, clean_input($_POST["price"])); + $stock = mysqli_real_escape_string($link, clean_input($_POST["stock"])); + + // handle the image upload + $uploadOk = 1; + + $target_dir = "uploads/"; + + // Check if image file is a actual image or fake image + $check = getimagesize($_FILES["image"]["tmp_name"]); + if($check !== false) { + // echo "File is an image - " . $check["mime"] . "."; + $uploadOk = 1; + } else { + echo "File is not an image."; + $uploadOk = 0; + } + + // Check file size + if ($_FILES["image"]["size"] > 1000000) { + echo "Sorry, your file is too large."; + $uploadOk = 0; + } + + $target_file = $target_dir . basename($_FILES["image"]["name"]); + $image = $target_file; + + // Check if file already exists + if (file_exists($target_file)) { + echo "Sorry, file already exists."; + $uploadOk = 0; + } + + $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); + + // Allow certain file formats + if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" + && $imageFileType != "gif" ) { + echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; + $uploadOk = 0; + } + + // Check if $uploadOk is set to 0 by an error + if ($uploadOk == 0) { + echo "Sorry, your file was not uploaded."; + + // if everything is ok, try to upload file + } else { + if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) { + echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded."; + } else { + echo "Sorry, there was an error uploading your file."; + } + } + // end of image upload + + // turn autocommit off + mysqli_autocommit($link, FALSE); + + // start a transaction + mysqli_query($link, 'START TRANSACTION'); + + // define the insertion query to add a new record in record table + $query1 = sprintf("INSERT INTO record (ean, title, artist_id, genre, year, price, image) + VALUES ('%s', '%s', %d, '%s', %d, %f, '%s')", $ean, $title, $artist_id, $genre, $year, $price, $image); + + // define the insertion query to add a new record in inventory table + $query2 = sprintf("INSERT INTO inventory (stock, record_ean) + VALUES (%d, '%s')", $stock, $ean); + + // check if either of the queries failed (returned false) + if (!mysqli_query($link, $query1) or !mysqli_query($link, $query2)) { + echo mysqli_error($link); + mysqli_rollback($link); // if so, rollback transaction + } else { + mysqli_commit($link); // else, commit transaction + $content .= "Record successfully added to database."; + } + + + + } + + // ------- END form processing code... ------- + + // output the html + echo($content); + +?> diff --git a/week-13/views/artist.php b/week-13/views/artist.php new file mode 100644 index 0000000000000000000000000000000000000000..ea371d7e2a7a6057ea88edcd8afe2edd4020a582 --- /dev/null +++ b/week-13/views/artist.php @@ -0,0 +1,68 @@ +<?php + +// check if id parameter was not set in query string +if (!isset($_GET['id'])) { + + // define $content with suitable message + $content = "<h1>I don't know which artist you're looking for...</h1>"; + +} else { // id was set, so carry on... + + // define $artist_id variable and assign value of id parameter + $artist_id = $_GET['id']; + + // fetch record titles for artist with id matching $artist_id + $sql = "SELECT r.title, r.year, r.price, a.first_name, a.last_name + FROM record r + INNER JOIN artist a + ON r.artist_id=a.id + WHERE a.id=".$artist_id." + ORDER BY year ASC"; + + $result = mysqli_query($link, $sql); + + // check query returned a result + if ($result === false) { + echo mysqli_error($link); + } else { + + // define a row counter + $i = 0; + + // fetch associative array + while ($row = mysqli_fetch_assoc($result)) { + + // do this if we are on first row + if ($i == 0) { + + // initialise $content string, assigning it a page header + $content = "<h1>".$row['first_name']." ".$row['last_name']." Records</h1>"; + // append $content string with table definition + $content .= "<table border='1'><tbody>"; + + } + + // append table rows to $content string + $content .= "<tr>"; + $content .= "<td>".$row['title']."</td>"; + $content .= "<td>".$row['year']."</td>"; + $content .= "<td>£".$row['price']."</td>"; + $content .= "</tr>"; + + // increment the row counter + $i++; + + } + + // append $content string with closing table tags + $content .= "</tbody></table>"; + + // free result set + mysqli_free_result($result); + } +} + +// output the content HTML +echo $content; + +?> diff --git a/week-13/views/home.php b/week-13/views/home.php new file mode 100644 index 0000000000000000000000000000000000000000..dc1ed44ecb479e1c621c9798b39d42e025002d21 --- /dev/null +++ b/week-13/views/home.php @@ -0,0 +1,10 @@ +<?php + +// create variable for content HTML +$content = "<h1>Welcome to Goldsmith's Record Store</h1>"; +$content .= "<p>Follow the links above to browse the store.</p>"; + +// output the content HTML +echo $content; + +?> diff --git a/week-13/views/order.php b/week-13/views/order.php new file mode 100644 index 0000000000000000000000000000000000000000..0f81c631d898204086a592a060e6341c59a16f20 --- /dev/null +++ b/week-13/views/order.php @@ -0,0 +1,67 @@ +<?php + +// check the order_id parameter has been set in the URL +if (isset($_GET['order_id'])) +{ + $order_id = $_GET['order_id']; +} else { + $order_id = -1; // if not, set to an implausible value +} + +// fetch order details associated with current order id +$sql = "SELECT r.ean, r.title, ol.quantity, ol.transaction_id, r.price + FROM record r + INNER JOIN orderline ol + ON ol.record_ean=r.ean + WHERE ol.transaction_id=".$order_id; +$result = mysqli_query($link, $sql); + +// check query returned a result +if ($result === false) { + echo mysqli_error($link); +} else { + + // Find the number of rows returned + $num_rows = mysqli_num_rows($result); + + // Check it's not 0 + if ($num_rows == 0) { + $content = "<h1>Order not found</h1>"; + } else { + // create variable for content HTML + $content = "<h1>Order ".$order_id."</h1>"; + $content .= "<table border='1'>"; + $content .= "<thead><tr> + <th>EAN</th> + <th>Title</th> + <th>Quantity</th> + <th>Price</th> + <th>Total</th> + </tr></thead>"; + $content .= "<tbody>"; + // initialise total order price to 0 + $total = 0.00; + // fetch associative array + while ($row = mysqli_fetch_assoc($result)) { + $subtotal = $row['quantity'] * $row['price']; + $total = $total + $subtotal; + $content .= "<tr>"; + $content .= "<td>".$row['ean']."</td>"; + $content .= "<td>".$row['title']."</td>"; + $content .= "<td>".$row['quantity']."</td>"; + $content .= "<td>£".$row['price']."</td>"; + $content .= "<td>£".$subtotal."</td>"; + $content .= "</tr>"; + } + $content .= "<tr><td colspan=4><b>TOTAL</b><td><b>£".$total."</b></td></tr>"; + $content .= "</tbody></table>"; + // free result set + mysqli_free_result($result); + + } +} + +// output the content HTML +echo $content; + +?> diff --git a/week-13/views/orders.php b/week-13/views/orders.php new file mode 100644 index 0000000000000000000000000000000000000000..d1228914e88edccc204d29b7380dabe43fd36aa7 --- /dev/null +++ b/week-13/views/orders.php @@ -0,0 +1,40 @@ +<?php + +// initialise string variable for content HTML +$content = "<h1>Orders</h1>"; + +// fetch all transactions (orders) and group by customer id +$sql = "SELECT id, customer_id FROM transaction + ORDER BY customer_id"; +$result = mysqli_query($link, $sql); + +// check query returned a result +if ($result === false) +{ + echo mysqli_error($link); +} else { + $num_rows = mysqli_num_rows($result); + if ($num_rows > 0) + { + $content .= "<table border='1'>"; + $content .= "<thead><tr><th>Order ID</th><th>Customer ID</th></tr></thead>"; + $content .= "<tbody>"; + // fetch each row in result set as an associative array + while ($row = mysqli_fetch_assoc($result)) { + $content .= "<tr>"; + $content .= "<td><a href=\"?page=order&order_id=".$row['id']."\">".$row['id']."</a></td>"; + $content .= "<td>".$row['customer_id']."</td>"; + $content .= "</tr>"; + } + $content .= "</tbody></table>"; + } else { + $content .= "<p>There are no orders to display.</p>"; + } + // free result set + mysqli_free_result($result); +} + +// output the content HTML +echo $content; + +?> diff --git a/week-13/views/record.php b/week-13/views/record.php new file mode 100644 index 0000000000000000000000000000000000000000..06ffa5efc4b771330005e5732cf3e63a37b77419 --- /dev/null +++ b/week-13/views/record.php @@ -0,0 +1,43 @@ +<?php + +// create variable for content HTML +$content = "<h1>Records</h1>"; +$content .= "<p>You are now viewing all records in the database.</p>"; + +// fetch records as a result set +$sql = "SELECT r.title, r.ean, a.first_name, a.last_name, r.genre, r.price, r.image, i.stock, a.id + FROM record r + INNER JOIN artist a + ON r.artist_id=a.id + INNER JOIN inventory i + ON r.ean=i.record_ean + ORDER BY r.title, r.price DESC"; +$result = mysqli_query($link, $sql); + +// check query returned a result +if ($result === false) { + echo mysqli_error($link); +} else { + $content .= "<table border='1'>"; + $content .= "<thead><tr><th>Title</th><th>Artist</th><th>Genre</th><th>Price</th><th>Stock</th></tr></thead>"; + $content .= "<tbody>"; + // fetch associative array + while ($row = mysqli_fetch_assoc($result)) { + $content .= "<tr>"; + $content .= "<td>".$row['title']."</td>"; + $content .= "<td><a href='?page=artist&id=".$row['id']."'>".$row['first_name']." ".$row['last_name']."</a></td>"; + $content .= "<td>".$row['genre']."</td>"; + $content .= "<td>".$row['price']."</td>"; + $content .= "<td>".$row['stock']."</td>"; + $content .= "<td><img src='".$row['image']."' style='height: 100px;' /></td>"; + $content .= "</tr>"; + } + $content .= "</tbody></table>"; + // free result set + mysqli_free_result($result); +} + +// output the content HTML +echo $content; + +?> diff --git a/week-13/views/search.php b/week-13/views/search.php new file mode 100644 index 0000000000000000000000000000000000000000..8e9482d5df3d96f82499726fff3789c46a17ff59 --- /dev/null +++ b/week-13/views/search.php @@ -0,0 +1,131 @@ +<? +$content = "<h1>Search</h1>"; + +// define a variable with path to this script which will process form +$action = htmlspecialchars($_SERVER["PHP_SELF"]."?page=search"); + +// define the search form +// note: need ?page=search for index to route here +// note: a form wihout an action will submit to the document's address +$form_html = "<form method='get'> + <label for='usersearch'>search the record store</label><br /> + <input type='text' id='usersearch' name='usersearch' /><br /> + <input type='submit' name='page' value='search' /> + </form>"; + +// append form HTML to content string +$content .= $form_html; + +// ------- START form processing code... ------- + +// check if there was a POST request +//if ($_SERVER["REQUEST_METHOD"] == "POST") { +if (!empty($_GET['usersearch'])) { + $sort =""; + +// make a build_query function for the search + $user_search = $_GET['usersearch']; + $user_search = clean_input($user_search); + if (!empty($_GET['sort'])) { + $sort = $_GET['sort']; + $sort = clean_input($sort); + } + $sql = build_query($user_search, $sort); + + //sort pagination + $cur_page = isset($_GET['pagenumber']) ? $_GET['pagenumber'] : 1 ; + $results_per_page = 3; + $skip = (($cur_page - 1) * $results_per_page); + + // Start generating the table of results + echo '<table border="0" cellpadding="2">'; + + // Generate the search result headings + echo '<tr class="heading">'; + echo '<td>Job Title</td><td>Description</td><td>State</td><td>Date Posted</td>'; + echo '</tr>'; + + +$result = mysqli_query($link, $sql); + + // check query returned a result + if ($result === false) { + echo mysqli_error($link); + } else { + + // info needed for pagination + $total = mysqli_num_rows($result); + $num_pages = ceil($total / $results_per_page); + + // query again to get subset of results per page + $sql = $sql .= " LIMIT $skip, $results_per_page"; + $result = mysqli_query($link, $sql); + + $content .= "<table border='1'>"; + $content .= "<thead><tr><th><a href='?page=search&usersearch=$user_search&sort=1'>Title</a></th>"; + $content .= "<th><a href='?page=search&usersearch=$user_search&sort=2'>Artist</a></th><th>Genre</th><th>Price</th><th>Stock</th></tr></thead>"; + $content .= "<tbody>"; + // fetch associative array + while ($row = mysqli_fetch_assoc($result)) { + $content .= "<tr>"; + $content .= "<td>".$row['title']."</td>"; + $content .= "<td><a href='?page=artist&id=".$row['id']."'>".$row['first_name']." ".$row['last_name']."</a></td>"; + $content .= "<td>".$row['genre']."</td>"; + $content .= "<td>".$row['price']."</td>"; + $content .= "<td>".$row['stock']."</td>"; + $content .= "<td><img src='".$row['image']."' style='height: 100px;' /></td>"; + $content .= "</tr>"; + + } + $content .= "</tbody></table>"; + + // This function builds navigational page links based on the current page and the number of pages + function generate_page_links($user_search, $sort, $cur_page, $num_pages) { + $page_links = ''; +/* + // If this page is not the first page, generate the "previous" link + if ($cur_page > 1) { + $page_links .= '<a href="' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=' . $sort . '&page=' . ($cur_page - 1) . '"><-</a> '; + } + else { + $page_links .= '<- '; + } +*/ + // Loop through the pages generating the page number links + for ($i = 1; $i <= $num_pages; $i++) { + if ($cur_page == $i) { + $page_links .= ' ' . $i; + } + else { + $page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?page=search&usersearch=' . $user_search . '&sort=' . $sort . '&pagenumber=' . $i . '"> ' . $i . '</a>'; + } + } +/* + // If this page is not the last page, generate the "next" link + if ($cur_page < $num_pages) { + $page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=' . $sort . '&page=' . ($cur_page + 1) . '">-></a>'; + } + else { + $page_links .= ' ->'; + } +*/ + return $page_links; + } + + + // Generate navigational page links if we have more than one page + if ($num_pages > 1) { + echo generate_page_links($user_search, $sort, $cur_page, $num_pages); + } + + + + // free result set + mysqli_free_result($result); + } + +} +// output the content HTML +echo $content; + +?>