Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- session_start();
- // Connect to the database
- $db_user = 'root'; $db_pass = 'abc123'; $db_uri = "mysql:dbname=rolls;host=127.0.0.1";
- $conn = new PDO($db_uri, $db_user, $db_pass);
- $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- function add_to_cart($item) {
- // check to see if the item is already here if true increment qty
- if(isset($_SESSION['cart'])) {
- // check for the existence of the item:
- $found = false;
- $loop = 0;
- foreach($_SESSION['cart'] as $item_list) {
- if($item_list[0] == $item) {
- $_SESSION['cart'][$loop][1]++;
- $found = true;
- break;
- }
- $loop++;
- }
- if($found == false) {
- $_SESSION['cart'][] = array($item, 1);
- }
- } else {
- $_SESSION['cart'][] = array($item, 1);
- }
- }
- function del_from_cart($item) {
- $loop = 0;
- $found = false;
- foreach($_SESSION['cart'] as $item_list) {
- // Search in array for item, then set it's qty to 0;
- if($item_list[0] == $item) {
- $_SESSION['cart'][$loop][1] = 0;
- $found = true;
- break;
- }
- $loop++;
- }
- }
- function empty_cart() {
- unset($_SESSION['cart']);
- }
- function show_cart() {
- // iterate through each item and print it to the screen (SELECT on product table may be necessary)
- foreach($_SESSION['cart'] as $item) {
- if($item[1] > 0) {
- echo $item[0] . ' ' . $item[1];
- echo ' <a href="student_cart.php?del_from_cart=' . $item[0] . '">Del</a>';
- echo '<br>';
- }
- }
- echo '<p><a href="student_cart.php?empty=true">Empty Cart</a></p>';
- }
- function show_products() {
- global $conn;
- // SELECT all items available to add to cart and have an 'add to cart' button
- $sql = "SELECT * FROM classroom";
- $check_conn = $conn->prepare($sql);
- $check_conn->execute();
- $result = $check_conn->fetchAll();
- foreach($result as $row) {
- echo $row['Class_name'] . ' ' . $row['Class_room_no'] . ' ' . $row['Class_day'];
- echo ' <a href="student_cart.php?add_to_cart=' . $row['ID'] . '">Add to Cart</a>';
- echo '<br>';
- }
- }
- if(isset($_GET['del_from_cart'])) {
- del_from_cart($_GET['del_from_cart']);
- }
- if(isset($_GET['add_to_cart'])) {
- add_to_cart($_GET['add_to_cart']);
- }
- if(isset($_GET['empty'])) {
- empty_cart();
- }
- ?>
- <html>
- <script>
- </script>
- <body>
- <?php
- show_products();
- echo '<hr>';
- if(isset($_SESSION['cart'])) {
- show_cart();
- echo '<hr>';
- echo count($_SESSION['cart']);
- echo '<br>';
- echo print_r($_SESSION['cart']);
- }
- ?>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement