Login to checkout: Adding item to cart

Hi Team

I want to find a way, if am adding an item(products.php) does that fine, but now i need to find from the login.php logic where if myself as a user when successfully login. I can still continue to checkout page having that item on the cart. How can i achieve this?

// cart.php

<?php
  session_start();
  
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="author" content="Sahil Kumar">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Cart</title>
  <!----Boostrap cdn libraries---->
	<!-- Google Web Fonts -->
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet"> 

    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">

    <!-- Libraries Stylesheet -->
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">

    <!-- Customized Bootstrap Stylesheet -->
    <link href="css/style.css" rel="stylesheet">
    <link href="css/register-messages.css" rel="stylesheet">
  
</head>

<body>
  <nav class="navbar navbar-expand-md bg-green navbar-green">
    <!-- Brand -->
    <a class="navbar-brand" href="index.php"><i class="fas fa-mobile-alt"></i>&nbsp;&nbsp;E Shopper</a>
    <!-- Toggler/collapsibe Button -->
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
      <span class="navbar-toggler-icon"></span>
    </button>
    <!-- Navbar links -->
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item">
          <a class="nav-link active" href="index.php"><i class="fas fa-mobile-alt mr-2"></i>Products</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#"><i class="fas fa-th-list mr-2"></i>Categories</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="checkout.php"><i class="fas fa-money-check-alt mr-2"></i>Checkout</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="cart.php"><i class="fas fa-shopping-cart"></i> <span id="cart-item" class="badge badge-danger"></span></a>
        </li>
      </ul>
    </div>
  </nav>

  <div class="container">
    <div class="row justify-content-center">
      <div class="col-lg-10">
        <div style="display:<?php if (isset($_SESSION['showAlert'])) {
  echo $_SESSION['showAlert'];
} else {
  echo 'none';
} unset($_SESSION['showAlert']); ?>" class="alert alert-success alert-dismissible mt-3">
          <button type="button" class="close" data-dismiss="alert">&times;</button>
          <strong><?php if (isset($_SESSION['message'])) {
  echo $_SESSION['message'];
} unset($_SESSION['showAlert']); ?></strong>
        </div>
        <div class="table-responsive mt-2">
          <table class="table table-bordered table-striped text-center">
            <thead>
              <tr>
                <td colspan="7">
                  <h4 class="text-center text-info m-0">Products in your cart!</h4>
                </td>
              </tr>
              <tr>
                <th>ID</th>
                <th>Image</th>
                <th>Product Name</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Total Price</th>
                <th>
                  <a href="action.php?clear=all" class="badge-danger badge p-1" onclick="return confirm('Are you sure want to clear your cart?');"><i class="fas fa-trash"></i>&nbsp;&nbsp;Clear Cart</a>
                </th>
              </tr>
            </thead>
            <tbody>
			                              <?php
    require 'dbconn.php';
    $stmt = $conn->prepare('SELECT * FROM cart');
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $grand_total = 0;
    foreach ($rows as $row):
        // Access the data using $row['column_name']
        $productID = $row['id'];
        $productName = $row['product_name'];
        $productPrice = floatval($row['product_price']);
        $total_price = $productPrice * $row['qty'];
        $grand_total += $total_price;
        ?>
        <tr>
            <td><?= $row['id'] ?></td>
            <input type="hidden" class="pid" value="<?= $row['id'] ?>">
            <td><img src="<?= $row['product_image'] ?>" width="50"></td>
            <td><?= $row['product_name'] ?></td>
            <td>
                <i class="fas fa-zar-sign"></i>&nbsp;&nbsp;<?= number_format($productPrice, 2); ?>
            </td>
            <input type="hidden" class="pprice" value="<?= $productPrice ?>">
            <td>
                <input type="number" class="form-control itemQty" value="<?= $row['qty'] ?>" style="width: 75px;">
            </td>
            <td><i class="fas fa-zar-sign"></i>&nbsp;&nbsp;<?= number_format($total_price, 2); ?></td>
            <td>
                <a href="action.php?remove=<?= $row['id'] ?>" class="text-danger lead" onclick="return confirm('Are you sure you want to remove this item?');"><i class="fas fa-trash-alt"></i></a>
            </td>
        </tr>
    <?php endforeach; ?>
    
    <tr>
        <td colspan="3">
            <a href="products.php" class="btn btn-success"><i class="fas fa-cart-plus"></i>&nbsp;&nbsp;Continue Shopping</a>
        </td>
        <td colspan="2"><b>Grand Total</b></td>
        <td><b><i class="fas fa-zar-sign"></i>&nbsp;&nbsp;<?= number_format($grand_total, 2); ?></b></td>
        <td>
		
  <?php if (isset($_SESSION['username'])): ?>
    <a class="nav-link" href="checkout.php"><i class="fas fa-money-check-alt mr-2"></i>Checkout</a>
  <?php else: ?>
    <a class="nav-link" href="login.php"><i class="fas fa-sign-in-alt mr-2"></i>Login to Checkout</a>
  <?php endif; ?>


        </td>
    </tr>					
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

//cart_view.php

<body class="hold-transition skin-blue layout-top-nav">
<div class="wrapper">

	<?php include 'includes/navbar.php'; ?>
	 
	  <div class="content-wrapper">
	    <div class="container">

	      <!-- Main content -->
	      <section class="content">
	        <div class="row">
	        	<div class="col-sm-9">
	        		<h1 class="page-header">YOUR CART</h1>
	        		<div class="box box-solid">
	        			<div class="box-body">
		        		<table class="table table-bordered">
		        			<thead>
		        				<th></th>
		        				<th>Photo</th>
		        				<th>Name</th>
		        				<th>Price</th>
		        				<th width="20%">Quantity</th>
		        				<th>Subtotal</th>
		        			</thead>
		        			<tbody id="tbody">
		        			</tbody>
		        		</table>
	        			</div>
	        		</div>
	        		<?php
	        			if(isset($_SESSION['user'])){
	        				echo "
	        					<div id='paypal-button'></div>
	        				";
	        			}
	        			else{
	        				echo "
	        					<h4>You need to <a href='login.php'>Login</a> to checkout.</h4>
	        				";
	        			}
	        		?>
	        	</div>
	        	<div class="col-sm-3">
	        		<?php include 'includes/sidebar.php'; ?>
	        	</div>
	        </div>
	      </section>
	     
	    </div>
	  </div>
  	<?php $pdo->close(); ?>

From what I have seen, you have not identified users or orders with relation to what is being saved to cart. Many items from different users or orders cannot be distinguished other items previously saved to the cart table.

Logically Cart items would be saved to session with the product_id as the KEY and the qty as the VALUE… Roughly like so.

$_SESSION['cart'][$_POST['product_id']] = $_POST['quantity'];

In the “View Cart Phase” it is then easy to loop through $_SESSION['cart'] and get any product details with the product_id. So at this point nothing has been saved to a database table.

It is easy to determine if a user has logged in out not.

  • If the user HAS an account they can log in and “SAVE THEIR CART” or “PLACE THE ORDER”, which would create an ORDER RECORD where an auto_increment order_id number is created when the user_id is saved to an orders table with a field named status as ‘pending’. A second query would then save the items to your cart table along with the order_id which was just created. If they had chosen to “PLACE THE ORDER” you would proceed with that processing and the order status would be updated to an appropriate term, e.g. processing, paid etc. If the user did not “PLACE THE ORDER” they could log in at a later date and view any pending orders from the orders table and cancel the order or proceed to checkout.

  • If the user DOES NOT have an account the “check out form” would have user registration form inputs and a user account is created before the above mentioned orders and cart records are created.

SO no items are saved to the DATABASE if a user is NOT logged in (or creating an account at check out) as an ORDER requires a user_id and cart items are saved with an order_id.

You really should consider making these changes before moving forward. If you are intent on saving items into your cart table while “shopping” that is fine and should only be allowed by a logged in user and an ORDER record should be created saving the user_id and cart items are then saved with the order_id as I mentioned.

@Drummin do you mind showing me via code perhaps?

I assume when you successfully logged in, you are then sent to a secure home page… This page might be your shopping page and on your nav bar. you might have a View Cart link but it would only work if you have items in your cart. So on this page you would make a query to the cart table with $_SESSION['user'] information and based on if results are found, show the link or make the link active to the cart_view.php page.

On cart_view.php page you again query the cart table with $_SESSION['user'] information and display their items for final checkout.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.