Webbserverprogrammering 1

Show sourcecode

The following files exists in this folder. Click to view.

webbserverprogrammering/projekt/snake_oil_seller/php/

about_us.php
add_to_cart.php
admin.php
buy_cart.php
config.php
contact.php
create_products.php
create_tables.php
createtable.php
dbconnection.php
delete_post.php
delete_tables.php
deletepost.php
deletetable.php
entry.php
header.php
insert_posts.php
insertposts.php
leaderboard.php
log_in.php
log_out.php
main.php
my_account.php
question_maker.php
quiz_form.php
quiz_list.php
quiz_maker.php
result.php
select_posts.php
selectposts.php
shop.php
shop_item.php
shopping_cart.php
sign_in.php
title_card.php
update_posts.php
updateposts.php
user_verified.php
verify_page.php

buy_cart.php

51 lines UTF-8 Windows (CRLF)
<?php
  
// Initierar sessionen
  
session_start();

  
/** @var PDO $dbconn*/
  
include ("dbconnection.php");

  if (empty(
$_SESSION["cart"])) {
    exit;
  }

  
// Om man inte är inloggad kan man inte köpa
  
if (!isset($_SESSION["user_id"])) {
    exit(
"Not logged in");
  }

  
// Hämtar id från den som köpt varorna
  
$user_id $_SESSION["user_id"];

  
// Initiera order
  
$stmt $dbconn->prepare("INSERT INTO orders (user_id, date) VALUES (?, ?)");
  
$stmt->execute([$user_idtime()]);

  
// Nytt id för senaste beställning
  
$order_id $dbconn->lastInsertId();

  
// Går igenom kundvagnen
  
foreach ($_SESSION["cart"] as $product_id => $amount) {
    
// Hämtar produkt
    
$stmt $dbconn->prepare("SELECT amount FROM product_items WHERE id = ?");
    
$stmt->execute([$product_id]);

    
// Kontrollerar lagret
    
$product $stmt->fetch(PDO::FETCH_ASSOC);
    if (!
$product || $product["amount"] < $amount) {
      continue;
    }
    
    
// Beställer allt i kundvagnen
    
$stmt $dbconn->prepare("INSERT INTO order_items (order_id, product_id, amount) VALUES (?, ?, ?)");
    
$stmt->execute([$order_id$product_id$amount]);

    
// Ändra lagret
    
$stmt $dbconn->prepare("UPDATE product_items SET amount = amount - ? WHERE id = ? AND amount >= ?");
    
$stmt->execute([$amount$product_id$amount]);
  }

  
// Töm kundvagnen
  
$_SESSION["purchase_completed"] = true;
  
$_SESSION["cart"] = [];
?>