Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Team

I am bit struggling with some logic to implement when a user has to login after they have added their item on cart. So in order to continue to checkout page must login and continue and that item should be there.

What I have tried:

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">Products</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">^__i class="fas fa-th-list mr-2">Categories</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="checkout.php">^__i class="fas fa-money-check-alt mr-2">Checkout</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="cart.php">^__i class="fas fa-shopping-cart"> <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">×</button>
          <?php if (isset($_SESSION['message'])) {
  echo $_SESSION['message'];
} unset($_SESSION['showAlert']); ?>
        </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?');">  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>
                  <?= 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>  <?= 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?');">  Continue Shopping</a>
        </td>
        <td colspan="2">^__b>Grand Total</td>
        <td>^__b>^__i class="fas fa-zar-sign">  <?= number_format($grand_total, 2); ?></td>
        <td>
		
  <?php if (isset($_SESSION['username'])): ?>
    <a class="nav-link" href="checkout.php">Checkout</a>
  <?php else: ?>
    <a class="nav-link" href="login.php">^__i class="fas fa-sign-in-alt mr-2">Login to Checkout</a>
  <?php endif; ?>


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



//cart_view.php
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(); ?>
</div>
Posted
Updated 12-Jul-23 0:21am
v2
Comments
Member 15627495 12-Jul-23 5:48am    
to achieve :

one cart is made, all those datas are save in a table.
as the user must be log in, you can use 'cookie',
or 'IP' to retrieve the cart after the login request.

you can make a cookie with 'cart' as name, it won't be lost[ datas stay in until a reset ].

every location with 'datas storing' [ Db / file / session_var by php / cookie ] could be use to achieve your goal.
Andre Oosthuizen 12-Jul-23 8:42am    
I think the question to ask is - when you load each row of a product and a user select a product, how is it saved in the database, how will you know which user selected which product? If I add items to my cart but decide not to check out immediately but in a few days time, how will you show my cart with the products that I selected. I will thus suggest that when a user selects an item, before it is added to the cart, let them login, save their ID and once they view their cart, you will have their ID to match the products.

1 solution

While what Member 15627495 says will work, there are two things to remember: GDPR which requires you to get permission from the user to add cookies to his system, and that IP addresses are not unique to a particular computer or device - they are linked to the router that connects the user to the internet, and are shared by multiple devices. If you use the IP address to identify a user then it will be the same for all other users who are on the same router / LAN / WiFi.

A better idea is to store the "wanted items" in the Session on the server, and when they log in / register get permission to store them as cookies. Alternatively, use a query string to provide a "temporary id" which you set up with the database, and add the shopping to that. When they log in, switch the temporary id to their user ID and carry on as normal.
 
Share this answer
 
Comments
Gcobani Mkontwana 12-Jul-23 6:33am    
@OriginalGriff mind showing an example perhaps?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900