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">×</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();
});
}
});