Commit 4363a905 authored by danmcquillan's avatar danmcquillan
Browse files

update for week 13

parent c0ef033b
*********************************
* 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/
<?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');
?>
<?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;
?>
<?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 (&pound;):</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);
?>
<?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>&pound;".$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;
?>
<?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;
?>
<?
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';
?>
<?
session_start();
session_destroy();
header('Location: http://localhost/term2labs-dan/week-13/index.php');
?>
<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>
<?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>&pound;".$row['price']."</td>";
$content .= "<td>&pound;".$subtotal."</td>";
$content .= "</tr>";
}
$content .= "<tr><td colspan=4><b>TOTAL</b><td><b>&pound;".$total."</b></td></tr>";
$content .= "</tbody></table>";
// free result set
mysqli_free_result($result);
}
}
// output the content HTML
echo $content;
?>
<?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;
?>
<?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;
?>
<?
$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']);