Handling of cart session and user

Hi Team

I need some help when add to cart is called, must hold that item to cart. So when new user login and continue to shop it must hold that item to the cart. Currently i am stuck there, cart session is called but not hold that item either when new user login.


<?php
session_start();
require_once 'dbconn.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $itemId = $_POST['itemId'];

    // Check if the user is logged in
    if (isset($_SESSION['id'])) {
        $userId = $_SESSION['id'];

        // Add the item to the cart in the database
        $query = "INSERT INTO cart (id, product_name) VALUES (:id, :product_name)";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':id', $userId);
        $stmt->bindParam(':product_name', $product_name);
        $stmt->execute();

        // Return a success response with the updated cart item count
        $cartItemCount = getCartItemCount($db, $userId);
        $response = array(
            'status' => 'success',
            'cartItemCount' => $cartItemCount
        );
    } else {
        // User is not logged in
        $response = array('status' => 'login_required');
    }

    // Send the JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
}
    // Function to get the count of items in the cart for a specific user
function getCartItemCount($db, $userId) {
    $query = "SELECT COUNT(*) FROM cart WHERE id = :id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':id', $userId);
    $stmt->execute();
    return $stmt->fetchColumn();
}

?>
<?php
session_start();


$dbHost = 'localhost';
$dbName = 'ecommerce_store';
$dbUser = 'root';
$dbPass = '';

try {
  $pdo = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPass);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
  exit;
}

if (isset($_POST['email']) && isset($_POST['password'])) {
  $email = $_POST['email'];
  $password = $_POST['password'];

  $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
  $stmt->execute(['email' => $email]);
  $user = $stmt->fetch(PDO::FETCH_ASSOC);

  if ($user && password_verify($password, $user['password'])) {
    // valid credentials, store user session
    $_SESSION['user'] = $user;
    $_SESSION['logged_in'] = true; // set logged_in to true
    header("Location: shopping.php");
    exit();
  } else {
    // invalid credentials
    echo "failure";
  }
}
<a href="" class="btn border">
                    <i class="fas fa-shopping-cart text-primary"></i>
                    <span class="badge"id="cart-badge">0</span>
                </a>
     <div class="card-footer d-flex justify-content-between bg-light border">
                        <a href="" class="btn btn-sm text-dark p-0"><i class="fas fa-eye text-primary mr-1"></i>View Detail</a>
                        <a href="" class="btn btn-sm text-dark p-0 add-to-cart-btn" data-id="1"><i class="fas fa-shopping-cart text-primary mr-1"></i>Add To Cart</a>

                    </div>

$(document).ready(function() {
    // Add to cart button click event
    $(document).on('click', '.add-to-cart-btn', function(e) {
        e.preventDefault();
        var itemId = $(this).data('id');

        // Check if the user is logged in
        var isLoggedIn = false; // Set this value based on your authentication logic

        if (isLoggedIn) {
            addToCart(itemId);
        } else {
            showLoginOrRegisterPrompt(itemId);
        }
    });

    // Function to add an item to the cart
function addToCart(itemId) {
  // Send an AJAX request to the server to add the item to the cart
  $.ajax({
    url: 'add-to-cart.php',
    method: 'POST',
    data: { itemId: itemId },
    dataType: 'json',
    success: function(response) {
      if (response.status === 'success') {
        // Item successfully added to the cart
        // You can update the UI to reflect the change, such as updating the cart count
        updateCartCount(response.cartItemCount);
        console.log('Item added to cart.');
      } else if (response.status === 'login_required') {
        // User needs to log in or register to continue
        showLoginOrRegisterPrompt(itemId);
      } else {
        // Error adding item to the cart
        console.log('Error adding item to cart.');
      }
    },
    error: function() {
      console.log('An error occurred while adding item to cart.');
    }
  });
}


    // Function to show the login or register prompt
function showLoginOrRegisterPrompt(itemId) {
  // Create the modal markup
  var modalContent = `
    <div class="modal fade" id="loginRegisterModal" tabindex="-1" role="dialog" aria-labelledby="loginRegisterModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="loginRegisterModalLabel">Login or Register</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <!-- Login and register form here -->
            <form id="loginForm" method="post" action="login.php">
              <h6>Login</h6>
              <div class="form-group">
                <label for="loginEmail">Email</label>
                <input type="email" class="form-control" id="loginEmail" name="loginEmail" required>
              </div>
              <div class="form-group">
                <label for="loginPassword">Password</label>
                <input type="password" class="form-control" id="loginPassword" name="loginPassword" required>
              </div>
              <button type="submit" class="btn btn-primary">Login</button>
            </form>

            <hr>

            <form id="registerForm" method="post" action="register.php">
              <h6>Register</h6>
              <div class="form-group">
                <label for="registerName">Name</label>
                <input type="text" class="form-control" id="registerName" name="registerName" required>
              </div>
              <div class="form-group">
                <label for="registerEmail">Email</label>
                <input type="email" class="form-control" id="registerEmail" name="registerEmail" required>
              </div>
              <div class="form-group">
                <label for="registerPassword">Password</label>
                <input type="password" class="form-control" id="registerPassword" name="registerPassword" required>
              </div>
              <button type="submit" class="btn btn-primary">Register</button>
            </form>
          </div>
        </div>
      </div>
    </div>
  `;

  // Append the modal to the body
  $('body').append(modalContent);

  // Show the modal
  $('#loginRegisterModal').modal('show');

  // Remove the modal from the DOM after it's hidden
  $('#loginRegisterModal').on('hidden.bs.modal', function() {
    $(this).remove();
  });
}

});

So… you’re storing items in your database based on userID:

Where in your login code do you define $_SESSION['id']?

@m_hutley i think i have tried to do this following on login.php

$stmt = $pdo->prepare(“SELECT * FROM users WHERE email = :email”);
$stmt->execute([‘email’ => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user && password_verify($password, $user[‘password’])) {
// valid credentials, store user session
$_SESSION[‘user’] = $user;
$_SESSION[‘logged_in’] = true; // set logged_in to true
header(“Location: shopping.php”);
exit();
} else {
// invalid credentials
echo “failure”;
}

Where in that code block do the characters $_SESSION['id'] appear?

@m_hutley could be the reason, i have not implemented in there.

Your posts seem to have a common thread that you appear to think that the code will be intelligent, and figure out that when you say something, you actually mean this other thing that is in a different form - in this case, i’m GUESSING you’re thinking that because you stuffed the user row into the session, that the code magically expands it into a bunch of other variables. If you tell it ABC = 4, you cant tell it to give you the value of XYZ and assume it knows you mean ABC.

It doesnt.

The code is COMPLETELY literal. There is ZERO interpretation. This is probably the biggest lesson for you to onboard at this point.

Assuming id is a field in the user table and you define a query result row as $user and assign this as the value of $_SESSION[‘user’], then all the fields called in the query are set to session. Personally I would NOT save a password to session so I would unset it from $user before applying it to $_SESSION[‘user’]. In this location.

if ($user && password_verify($password, $user[‘password’])) {
// valid credentials, store user session
unset($user[‘password’]);
$_SESSION[‘user’] = $user;

Now fields like the id can be found under $_SESSION[‘user’].like so

$_SESSION[‘user’]['id']

or say you have firstname as a field.

$_SESSION[‘user’]['firstname']

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