"; mysql_select_db("66_simplycurt") or die(mysql_error()); //echo "Connected to Database"; require('cartbar.php'); echo"
"; require('nav.php'); echo"
"; $product_id = $_GET['id']; //the product id from the URL $action = $_GET['action']; //the action from the URL //the function productExists() checks if a product exists function productExists($product_id) { //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection //sprintf returns a string produced according to the formatting string format. The %d means that the value in $sql is treated as an number $sql = sprintf("SELECT * FROM garment WHERE ID = %d;", $product_id); return mysql_num_rows(mysql_query($sql)) > 0; } //if there is an product_id and that product_id doesn't exist display an error message. if($product_id && !productExists($product_id)) { die("Error. Product Doesn't Exist"); } //decide what to do- add, remove, or empty stuff in the cart switch($action) { case "add": //Here's the session array, called cart, that adds 1 to the quantity of the product with id $product_id $_SESSION['cart'][$product_id]++; $_SESSION['items']++; break; case "remove": //Using the cart session array, remove one from the quantity of the product with id $product_id $_SESSION['cart'][$product_id]--; $_SESSION['items']--; //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise it will show zero, then -1, -2 etc when the user keeps removing items. //unset() destroys the specified variable. if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); if($_SESSION['items'] == 0) unset($_SESSION['items']); break; case "empty": //unset the whole cart, i.e. empty the cart. unset($_SESSION['cart']); unset($_SESSION['items']); break; } //if the cart isn't empty, we want to show it if($_SESSION['cart']) { echo"

Item

Price

Quantity

Total

"; //iterate through the cart, the $product_id is the key and $quantity is the value foreach($_SESSION['cart'] as $product_id => $quantity) { //get the name, description and price from the database. //We're going to use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection $sql = sprintf("SELECT img1, name, price FROM garment WHERE ID = %d;", $product_id); //sprintf sets the format first, then the ID $result = mysql_query($sql); //Only display the row if there is a product if(mysql_num_rows($result) > 0) { list($img1, $name, $price) = mysql_fetch_row($result); $line_cost = $price * $quantity; //work out the line cost $total = $total + $line_cost; //add to the total cost echo"
$img1

$name

$".$price."
$quantity +
$".$line_cost."

"; } } //end of the foreach statement //show the total + empty echo "Empty Cart"; echo "
Total $".$total."
"; } else{ //If the cart is empty, tell the user they have no items in their cart echo "You have no items in your shopping cart."; } require('footer.php'); echo"
" ?>